text:
<repo_name>mohammadhamayel/CoreAPI_React<file_sep>/src/App.js
import { render } from '@testing-library/react';
import TopNavbar from './components/TopNavbar';
import Contactus from "./info/Aboutus";
import Aboutus from './info/Aboutus';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
function App() {
    return (
      <Router>

            <TopNavbar />
            <Switch>
              <Route path="/" exact component={Main} />
              <Route path="/info/contactus" component={Contactus} />
              <Route path="/info/about" component={Aboutus} />
            </Switch>

      </Router>
    );
}

const Main = ()=>(

Main

 More Stuff to be added here soon

);

export default App;

branch_name: refs/heads/master

repo_language: JavaScript


text:
<file_sep>from tkinter import * # Import tkinter

class OrderApplication:
    def __init__(self):
        self.window = Tk() # Create a window
        self.window.title("GW Order Processing Application") # Set title of a window
        photo = PhotoImage(file="P:\GWlogo.gif") # specify the path to your file
        label = Label(self.window, image=photo)  #put the image in a label to disdaply it in the window
        label.grid(sticky = W, column = 1, row = 0)  # show the label on the screen

        #set up labels the left column of the window (Aligned left)
        lbl = Label(self.window, text ="Customer Name:", font = "Times 12 bold")
        lbl.grid(sticky = W, column = 0, row = 2,)
        lbl = Label(self.window, text ="Product Name:", font = "Times 12 bold")
        lbl.grid(sticky = W, column = 0, row = 3)
        lbl = Label(self.window, text ="Product ID:", font = "Times 12 bold")
        lbl.grid(sticky = W, column = 0, row = 4)
        lbl = Label(self.window, text ="Product Quantity:", font = "Times 12 bold")
        lbl.grid(sticky = W, column = 0, row = 5)
        lbl = Label(self.window, text = "Product Price (USD):", font = "Times 12 bold")
        lbl.grid(sticky = W, column = 0, row = 6)
        lbl = Label(self.window, text ="Subtotal:", font = "Times 12 bold")
        lbl.grid(sticky = W, column = 0, row = 8)
        lbl = Label(self.window, text = "Order Total (USD):", font = "Times 12 bold")
        lbl.grid(sticky = W, column = 0, row = 10)
        w = Checkbutton(self.window, text = "2% discount", onvalue = 0.02, font = "Times 12 bold", command = self.checkbuttonvalue1).grid(sticky = W, row = 7, column = 1)
        x = Checkbutton(self.window, text = "No discount", onvalue = 0.02, font = "Times 12 bold", command = self.checkbuttonvalue2).grid(sticky = E, row = 7, column = 1)

        # set up the input area and assigning variables
        self.CustomerNameVar = StringVar()
        Entry(self.window, width = 51, textvariable = self.CustomerNameVar).grid(sticky = W, row = 2, column = 1)
        self.ProductNameVar = StringVar()
        Entry(self.window, width = 51, textvariable = self.ProductNameVar).grid(sticky = W, row = 3, column = 1)
        self.ProductIDVar = StringVar()
        Entry(self.window, width = 51, textvariable = self.ProductIDVar).grid(sticky = W, row = 4, column = 1)
        self.ProductQuantityVar = StringVar()
        Entry(self.window, width = 51, textvariable = self.ProductQuantityVar).grid(sticky = W, row = 5, column = 1)
        self.ProductPriceVar = StringVar()
        Entry(self.window, width = 51, textvariable = self.ProductPriceVar).grid(sticky = W, row = 6, column = 1)

        #set up the output area using two labels and two buttons
        self.subTotalVar = StringVar()
        Label(self.window, textvariable = self.subTotalVar, font = "Times 12 bold").grid(sticky = W, column = 1, row = 8)
        self.orderTotalVar = StringVar()
        Label(self.window, textvariable = self.orderTotalVar, font = "Times 12 bold").grid(sticky = W, column = 1, row = 10)
        R1 = Radiobutton(self.window, text = "English", font = "Times 12 bold"). grid(row = 0, column = 0, sticky = W)
        Button(self.window, text = "Calculate Order Total", font = "Times 14 bold", bg="green", fg="black", command = self.computeTotal).grid(row = 11, column = 0, sticky = W)
        Button(self.window, text = "Help", font = "Times 14 bold", bg="yellow", fg="black").grid(row = 11, column = 1, sticky = E)

        self.window.mainloop() # Create an event loop to display the window

    def computeTotal(self):
            subTotal = self.getSubtotal(
                float(self.ProductPriceVar.get()),
                int(self.ProductQuantityVar.get()))
            self.subTotalVar.set(format(subTotal, '10.2f'))
            lbl = Label(self.window, text = "Sales Tax:", font = "Times 12 bold")
            lbl.grid(sticky = W, column = 0, row = 9)
            lbl = Label(self.window, text = "      13%", font = "Times 12 bold")
            lbl.grid(sticky = W, column = 1, row = 9)
            orderTotal = float(self.subTotalVar.get()) * 0.13 + float(self.subTotalVar.get())
            self.orderTotalVar.set(format(orderTotal, '10.2f',))

    def getSubtotal(self, Productprice, Productquantity):
            subTotal = (Productprice * Productquantity)
            if checkbutton2 == 1:
                subTotal1 = subTotal * 0.98
                return subTotal1
            else:
                return subTotal

    def checkbuttonvalue1(self):
        global checkbutton2
        checkbutton2 = 1

    def checkbuttonvalue2(self):
        global checkbutton2
        checkbutton2 = 0

OrderApplication()  # Create GUI

repo_language: Python

repo_name: seanmollahan/glampingworld


text:
<repo_name>WildcatsC/TechX-2019-Assignments<file_sep>/Pokedex-Webapp/predictor.py
from keras.preprocessing.image import img_to_array
from keras.models import load_model
from PIL import Image
import tensorflow as tf
import numpy as np
import argparse
import imutils
import pickle
import cv2
import os

def preprocess_img(image):
    '''
	This method processes the image into a form that can be accepted by the model.
	'''
    image = cv2.resize(image, (96, 96))
    print(image.shape)
    image = image.astype("float") / 255.0
    image = img_to_array(image)
    image = np.expand_dims(image, axis=0)
    return image

class Predictor:

    def __init__(self):
        # load model, default graph, and class index
        self.model = load_model('model/pokedex.model')
        self.graph = tf.get_default_graph()
        self.lb = pickle.loads(open('model/lb.pickle', 'rb').read())

    def predict(self, request):
        '''
        This method reads the file uploaded from the Flask application POST request,
        and performs a prediction using the trained model
        '''

        # load and preprocess image
        f = request.files['image'].read()
        image = cv2.imdecode(np.fromstring(f, np.uint8), cv2.IMREAD_COLOR)
        image = preprocess_img(image)

        # classification
        result = ''
        with self.graph.as_default():
            prob = self.model.predict(image)[0]
            index = np.argmax(prob)
            label = self.lb.classes_[index]
            result = label

        return result <file_sep>/Assignment_2/A_2.py
#data man and vis

#1.import pack
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import cv2

# hint: never overwrite your original dataset because you never know when you'll need it again.

#2.data man
df = pd.read_csv('/Users/stevenchan/Documents/TECHX_2019/Self/Assignments/Assignment2/dataset/ramen-ratings.csv')
df.fillna(value = 'no') #replace NaN
df['Top Ten'] = df['Top Ten'].str.split('#').str[0] #replace '#' in Top Ten

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

df['Stars'] = pd.to_numeric(df['Stars'])# cast the ratings to numeric numbers from strings
avg = df.groupby(['Country'])['Stars'].mean()# rank all countries based on stars review
avg = avg.reset_index() # resets the column names to the origin ones
avg = avg.sort_values('Stars')
#avg.plot.bar(x='Country', y='Stars')

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

df.tail() #defult 5 rows, tail(1)==1 row
brazil = df[df['Country'] == 'Brazil'] # find the Brazil rows in Country

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

brazil_packs = brazil[(brazil['Style'] == 'Pack')] # select Pack style from Brazil
to_try = brazil_packs.loc[brazil_packs['Stars'].idxmax()] #***

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

countries = ['Japan', 'Malaysia', 'South Korea', 'Singapore']
print(df[(df['Country'].isin(countries)) & (df['Top Ten'] != 'no')]) # include these countries only
# cannot use 'and', but'&'  ==> 1 & 0 = 0; 1 & 1 = 1

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

# In a single day finishes ALL the ramens above 3.0 (inclusive) stars, that are NOT in a 'Pack'. (Yes, he eats a lot).
# Change all of the 'Tries' entries of these rows to True.
mask = (df['Country'] == 'Singapore') & (df['Stars'] >= 3.0) & (df['Style'] != 'Pack') # all
df.loc[mask, 'Tried'] = True # choose all the mask rows and make a new 'Tried' column
print(df[df['Country'] == 'Singapore'])  # can print all columns of this one row

        # similarly, loc[] can do this:
df.loc[df['Top Ten'] == '\n', 'Top Ten'] = 'no' # replace '\n' by 'no'

# To show all the column info:
#   df.columns.values     ==> return a array

'''The Pandas loc indexer can be used with DataFrames for two different use cases:
    a. Selecting rows by label/index
    b. Selecting rows with a boolean / conditional lookup'''

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

# make a new row
df = df.append(pd.Series([len(df) + 1, # Review #: Increment by 1 from the size of the dataset,
           'Prima Taste', # Brand
           'Beef Noodle Soup', # Variety
           'Pack', # Style
           'Singapore', # Country
           5, # Stars
           'no', # Top Ten
           True], index=df.columns), # Tried
           ignore_index=True)

print(df[df['Variety'] == 'Beef Noodle Soup'])

df.drop(df[df['Tried'] == True].index, inplace=True) # drop True
df.drop('Tried', axis=1, inplace=True)
print(df)

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

style = df['Style'].value_counts()
print(style)
style.plot.pie() # count values in Style and make a pie chart

df.drop(df[df['Country'] == 'Singapore'].index, inplace=True)  # .index can show index,
                                                               # returning pandas things: type(df[df['Country'] == 'Singapore'].index)
df.to_csv('/Users/stevenchan/Documents/TECHX_2019/Private/Assignment-Solutions/Assignment2/dataset/assignment-ramen-ratings.csv', index=False) #save file to_csv

######################################################
# data vis

dog = cv2.imread('/Users/stevenchan/Documents/TECHX_2019/Private/Assignment-Solutions/Assignment2/dataset/shiba-inu.jpg')
dog = cv2.cvtColor(dog, cv2.COLOR_BGR2RGB)

# =========== YOUR CODE HERE ========
plt.imshow(dog)
plt.show()

plt.figure(figsize=(100, 120)) #change size
plt.imshow(dog)
plt.show()

baby_dog = cv2.imread('/Users/stevenchan/Documents/TECHX_2019/Private/Assignment-Solutions/Assignment2/dataset/baby-dog.jpg')
baby_dog = cv2.cvtColor(baby_dog, cv2.COLOR_BGR2RGB)
star_boo = cv2.imread('/Users/stevenchan/Documents/TECHX_2019/Private/Assignment-Solutions/Assignment2/dataset/star-boo.jpg')
star_boo = cv2.cvtColor(star_boo, cv2.COLOR_BGR2RGB)
chihuahua = cv2.imread('/Users/stevenchan/Documents/TECHX_2019/Private/Assignment-Solutions/Assignment2/dataset/chihuahua.jpg')
chihuahua = cv2.cvtColor(chihuahua, cv2.COLOR_BGR2RGB)

# Create a subplot for each figure.
plt.subplot(221)
# subplot is equivalent but more general to ax1=plt.subplot(2, 2, 1)
plt.imshow(dog)
plt.subplot(222)
plt.imshow(baby_dog)
plt.subplot(223)
plt.imshow(star_boo)
plt.subplot(224)
plt.imshow(chihuahua)

''' Usage:
    subplot(nrows, ncols, index, **kwargs)
    subplot(pos, **kwargs)
    subplot(ax)
    '''
plt.show()<file_sep>/Pokedex-Webapp/app.py
from flask import Flask, render_template, request, make_response
from functools import wraps, update_wrapper
from PIL import Image
from predictor import Predictor

# Initialize the predictor object.
predictor = Predictor()

# Initialize Flask app.
app = Flask(__name__)

# Base endpoint to perform prediction.
@app.route('/', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST':
        prediction = predictor.predict(request)
        return render_template('index.html', prediction=prediction)
    else:
        return render_template('index.html', prediction=None)

if __name__ == '__main__':
   app.run()<file_sep>/requirements.txt
grpcio==1.22.0
joblib==0.13.2
keras==2.2.2
keras-applications==1.0.4
keras-preprocessing==1.0.2
kiwisolver==1.1.0
Markdown==3.1.1
matplotlib==3.1.1
numpy==1.16.4
opencv-python==4.1.0.25
pandas==0.24.2
protobuf==3.9.0
pyparsing==2.4.0
python-dateutil==2.8.0
pytz==2019.1
PyYAML==5.1.1
scikit-learn==0.21.2
scipy==1.3.0
seaborn==0.9.0
six==1.12.0
sklearn==0.0
tensorflow==1.13.1
wrapt==1.11.2
flask==1.0.2
pillow==5.4.1
imutils==0.5.2
<file_sep>/README.md
# TechX_2019_Assignments
Assignments from intro to ml
 + unofficial solutions

<file_sep>/Assignment_1/MAP.py
import numpy as np

toss = 20
head = 0
total = 0
sample = [1,1,1,1,1,1,1,1,0,0]
theta = 0.5
P = theta**head*(1-theta)**(total-head)
a=2
b=2

for i in range(20):
    print("old theta:", theta)
    result = np.random.choice(sample)
    if result == 1:
        head+=1
    total+=1
    theta = (a+head-1)/(a+b+total-2)
    print("new theta:", theta)
    print("==========")

    #后验概率 MAP  最大似然 MLE
<file_sep>/Assignment_1/A_1.py
#general test function
from pandas.io.html import _importers
from tensorflow.python.ops.gen_array_ops import matrix_set_diag
from networkx.algorithms.centrality import eigenvector
def test_function(function, test_cases, test_cases_answers):
    """Runs function through test cases"""
    passed = True

    for (case, answer) in zip(test_cases, test_cases_answers):
        output = function(case)
        if output != answer:
            print('Your output: ', output, '\t Expected output: ', answer)
            passed = False

    if passed:
        print('Test passed.')
    else:
        print('Test failed.')

#1.average
def average(array):
    sum = 0

    for i in range(len(array)):
        sum+=array[i]

    return sum/len(array)

'''
other solutions:

def average(array):
    avg = sum(array)/len(array)
    return avg

def average(array):
    return np.average(array)

def test_function(average, test_cases_average, test_cases_answers_average):

    for i in test_cases_answers_average:
        average = average(test_cases_average[i])
        if average == test_cases_answers_average[i]:
            print(1)
            return True
        else:
            print(0)
            return False
'''

test_cases_average = [[1, 1, 1, 1, 1, 1, 1, 1, 1],
              [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
              [0.21780088, 0.4118428,  0.62573827, 0.78184048, 0.96162729, 0.21242742, 0.06843751, 0.70688805, 0.98459559, 0.1153083 ]]

test_cases_answers_average = [1, 5.5, 0.508650659]

test_function(average, test_cases_average, test_cases_answers_average)

#############################################################
#2.extract
def extract_username(email):
    list_1 = email.split('@')
    return list_1[0]

'''
another solution:

'''

test_cases_extract_username = ['<EMAIL>',
              'this.is.the.username@abcdefghijklmnopqrstuvwxyz',
              'invalid-email']

test_cases_answers_extract_username = ['john-smith', 'this.is.the.username', 'invalid-email']

test_function(extract_username, test_cases_extract_username, test_cases_answers_extract_username)

#############################################################
#3.& 4. numpy vector x
import numpy as np
import random

x = np.zeros([1,10])
for i in range(10):
    x[0][i] = random.randint(10,15)
print(x)

#max
print(max(x[0]))

#max position
print(np.where(x[0]==max(x[0])))
a = np.where(x[0]==max(x[0])) #a is a tuple

#############################################################
#5.numpy vector y ("1"s)
y = np.ones([1,10])
print(y)

#############################################################
#6. add x and y (numpy ufuncs)
answer = np.add(x,y)
print(answer)

#############################################################
#7.matrix
matrix = np.array([[5,10,15],[2,13,23]])
print(matrix)

#############################################################
#8.transpose
matrix_T = matrix.T
print(matrix_T)

#############################################################
#9.multiplication
matrix_square = np.matmul(matrix,matrix_T)
print(matrix_square)

#det
det = np.linalg.det(matrix_square)
print(det)

#inv
inv = np.linalg.inv(matrix_square)
print(inv)

#eigens
eigenvalues ,eigenvectors = np.linalg.eig(matrix_square)
print('eigenvalues: ', eigenvalues)
print('eigenvectors: ', eigenvectors)

#check eig
result_1 = np.dot(matrix_square,[eigenvectors[0][0],eigenvectors[1][0]])
result_2 = np.dot(eigenvalues[0],[eigenvectors[0][0],eigenvectors[1][0]])
print(result_1,result_2)

#############################################################
#10. Create a 3-element vector with integers of your choice.
v = np.zeros(3)
print(v)

#############################################################
#11. multiply matrix and v
answer = np.dot(matrix, v)
print(answer)

#############################################################
#12. flatten
flatten = matrix.flatten()
print(flatten)

##############################################################
# 13. concatenate
matrix1 = [[1, 2, 3, 4, 5],
           [6, 7, 8, 9, 10],
           [11, 12, 13, 14, 15]]

matrix2 = [[16, 17, 18, 19, 20],
           [21, 22, 23, 24, 25],
           [26, 27, 28, 29, 30]]
mat1 = np.array(matrix1)
mat2 = np.array(matrix2)

ans_0 = np.concatenate((mat1, mat2), axis=0)
print(ans_0)

ans_1 = np.concatenate((mat1, mat2), axis=1)
print(ans_1)

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

#statistics

#randint()
v = np.random.randint(1,20,[1,30])
print(v)

#median, std
md = np.median(v)
std = np.std(v)

#random sampling
list = np.arange(10)
print(list)

sample = np.random.choice(list, 5)
print(sample)

sample = np.random.choice(list, 5, replace = False) #without replacement
print(sample)

#############################################################
#Maximum A Posteriori

toss = 200
total = 0
head = 0
theta = 0.5
sample = np.array([1,1,1,1,1,1,1,1,0,0])
res = np.zeros(toss)

for i in range(toss):
    j=i+1
    print("toss",j)
    print("last theta: ",theta)
    if np.random.choice(sample)==1:
        head+=1
        res[i]=1
    total+=1
    theta = head/total
    print("new theta: ",theta)
    print("---------")

print(res)

################
#DONE

languages: Markdown Text Python

repo_language: Markdown


text:
<repo_name>solarfl4re/gdrive-upload<file_sep>/src/index.js
const fs = require('fs');
const path = require('path');
const client = require('./client')
const {google} = require('googleapis');

function upload(fileName) {
  const auth = client.oAuth2Client;
  const name = path.basename(fileName);
  const drive = google.drive({version: 'v3', auth});
  var fileMetadata = {
    'name': name
  };
  var media = {
    body: fs.createReadStream(fileName)
  };
  drive.files.create({
    resource: fileMetadata,
    media: media,
    fields: 'id'
  }, (err, file) => {
    if (err) {
      console.error(err);
    } else {
      console.log('File ID: ', file.id);
    }
  });
};

module.exports = upload;
<file_sep>/README.md
# gdrive-upload
Exports an 'upload' function to upload a file to Google Drive (Using to backup Ghost website).
Based on Google's Quickstart for the NodeJS Google Drive API.

## Examples
- Upload an archive of my website (`NodeJS`):
  ````js
  const upload = require('gdrive-upload');

  upload("/home/david/backups/backup-09-04-2020.zip")
  ````

languages: Markdown JavaScript


text:
<file_sep><!DOCTYPE html>

    <meta charset="utf-8">
    <title>Bill Details</title>
      <link rel="stylesheet" href="/css/styles.css">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">

      <link rel="preconnect" href="https://fonts.gstatic.com">
      <link href="https://fonts.googleapis.com/css2?family=Montserrat&display=swap" rel="stylesheet">

Bill Details

Bill No:  <%= bill_no  %>

Customer name : <%= c_name %>

Bill Date : <%= b_date %>

Shop Name : <%= s_name %>

Bill Amount : <%= b_amt %>

Bill Rating : <%= b_rate %>

Bill Image :  <%= b_imgt  %>

<file_sep># OCRRecognitionBill

The application which I developed is a validation module for the Mall Coupon Management application. This module is developed for Sysberries located in Abu Dhabi which specializes in developing real-world IT solutions in the Middle East. It is a web application where the customers can enter their invoices to apply for coupons which can be used to avail discounts. The application uses Optical Character Recognition API to read the text content of the invoice image which is uploaded by the customer and it will compare this content with the data entered by the user. The information entered by the customer is invoice number, Invoice date, Invoice Amount, and Shop name. Depending upon the accuracy of data entered the application will assign a score in the range of 1 to 5.This score ease the process of validation for the coupon provider.It also provides validation to check for duplicate entries.

## Following are the Tools Used:

1.	Node JS
2.	Express
3.	Multer
4.	EJS
5.	MySQL
6.	JavaScript
7.	Optical Recognition API (Google Cloud Vision API)

## Database Tables used:

1)bill_details

CREATE TABLE `bill_details` (
  `bill_id` int(11) NOT NULL AUTO_INCREMENT,
  `customer_bill_no` varchar(20) NOT NULL,
  `customer_name` varchar(45) NOT NULL,
  `bill_date` varchar(45) NOT NULL,
  `shop_name` varchar(45) NOT NULL,
  `bill_amount` int(11) NOT NULL,
  `bill_image` varchar(100) NOT NULL,
  `bill_creation_time` datetime NOT NULL,
  `bill_rating` int(11) NOT NULL,
  PRIMARY KEY (`bill_id`)
) ENGINE=InnoDB AUTO_INCREMENT=112 DEFAULT CHARSET=utf8mb4;

2) shops

CREATE TABLE `shops` (
  `shopid` int(11) NOT NULL,
  `shopname` varchar(45) NOT NULL,
  PRIMARY KEY (`shopid`,`shopname`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

## Sample Images:

<file_sep>const express = require('express');
const app = express();
const bodyParser = require("body-parser");
const mysql = require('mysql');
const fileupload = require('express-fileupload');
const multer = require('multer');
const path = require('path');

/*defining the storage-engine */

const storage = multer.diskStorage({
  destination: __dirname + '/public/uploads/',
  filename: function(req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
  }
});

/*init */
const upload = multer({
  storage: storage,
  limits: {
    fileSize: 100000000000
  },
  fileFilter: function(req, file, cb) {
    checkFileType(file, cb);
  }
}).single('billpics');

/*Checking File type */

function checkFileType(file, cb) {
  const filetypes = /jpeg|jpg|png|gif/;
  const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
  const mimetype = filetypes.test(file.mimetype);
  if (mimetype && extname) {
    return cb(null, true);
  } else {
    cb('Error: Images Only!');
  }
}

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(express.static('public'));
app.set("view engine", "ejs");
app.use(express.json())
app.use(bodyParser.json());

var connection = mysql.createConnection({
  host: "localhost",
  user: "root",
  database: "coupon",
  multipleStatements: true
});
connection.connect((err) => {
  if (!err) {
    console.log("Connected");
  } else {
    console.log("Conection Failed");
  }
});

/*routes*/
app.get("/thankyou", function(req, res) {
  res.render("thankyou");
});
app.get("/", function(req, res) {

});

/*Test*/
app.get("/test", function(req, res) {
  var shopsql = "Select * from shops";
  connection.query(shopsql, function(error, results, fields) {
    if (error) throw error;
    if (results.length > 0) {
      var shops = results;
      console.log(results);
      res.render('test', {
        shops: shops
      });
    }
  });
});

app.post('/upload', function(req, res) {
  upload(req, res, (err) => {
    if (err) {
      res.send(err);
    } else {
      if (req.file == undefined) {
        res.send("File is undefined");
      } else {
        console.log(req.file);
        console.log(req.files);
        res.send("File is uploaded and niotanitsed" + req.file.path);
      }
    }
  });
});

app.post("/inserttest", function(req, res) {

  /*bill name*/
  var objcbillnames = JSON.parse(req.body.customerbillnames);
  var billnamearray = objcbillnames.tcustomerbillnames;
  /*bill No's*/
  var objcbillnumbers = JSON.parse(req.body.customerbillnumbers);
  var billnumbersarray = objcbillnumbers.tcustomerbillnumbers;
  /*bill Dates*/
  var objcbilldates = JSON.parse(req.body.customerbilldates);
  var billdatearray = objcbilldates.tcustomerbilldates;
  /*Shop Names*/
  var objcshopnames = JSON.parse(req.body.customershopnames);
  var cshoparray = objcshopnames.tcustomershopnames;
  /*Bill Amounts*/
  var objbillamounts = JSON.parse(req.body.customerbillamounts);
  var billamountarray = objbillamounts.tcustomerbillamounts;
  /*Bill Pics*/
  var objbillpics = JSON.parse(req.body.customerbillpics);
  var billpicarray = objbillpics.tcustomerbillpics;

  console.log("Testing0" + req.body.customerbillpics);
  console.log("Testing" + objbillpics);
  console.log("Testing2" + billpicarray[0].location);

  var lengthofarray = billpicarray.length;
  console.log(lengthofarray);
  var q = new Date();

  console.log(billnamearray);
  console.log(billnumbersarray);
  console.log(billdatearray);
  console.log(cshoparray);
  console.log(billamountarray);

  console.log(lengthofarray);

  res.send("thankyou");
  var i = 0;
  var j = 0;
  for (i = 0; i < lengthofarray; i++) {
    var particularbillname = billnamearray[i];
    var particularbillnumber = billnumbersarray[i];
    var particularbilldate = billdatearray[i];
    var particularshopname = cshoparray[i];
    var particularbillamount = billamountarray[i];
    // var particularbillpic = billpicarray[i];
    for (j = 0; j < lengthofarray; j++) {
      var v = i + 1;
      console.log("For LOop Comparison " + billpicarray[j].location);
      if (Object.values(billpicarray[j]).indexOf(v.toString()) > -1) {
        console.log("Inside Comparison " + billpicarray[j].location);
        var particularbillpic = billpicarray[j].location;
      }
    }

    console.log("<-------------------------------------------------------->");
    console.log(particularbillname);
    console.log(particularbillnumber);
    console.log(particularbilldate);
    console.log(particularshopname);
    console.log(particularbillamount);
    console.log(particularbillpic);
    finish(particularbillname, particularbillnumber, particularbilldate, particularshopname, particularbillamount, particularbillpic, q);
  }

  async function finish(particularbillname, particularbillnumber, particularbilldate, particularshopname, particularbillamount, particularbillpic, q) {
    var rt = await quickstart(particularbillname, particularbillnumber, particularbilldate, particularshopname, particularbillamount, particularbillpic);
    insertentry(particularbillnumber, particularbillname, particularbilldate, particularshopname, particularbillamount, particularbillpic, q, rt);
  }

  async function quickstart(particularbillname, particularbillnumber, particularbilldate, particularshopname, particularbillamount, particularbillpic) {
    var gcn = false;
    var gcb = false;
    var gbd = false;
    var gsn = false;
    var gba = false;
    let gdate = new Date(particularbilldate);
    let rating = 0;
    process.env.GOOGLE_APPLICATION_CREDENTIALS = 'Add your Api Key Json File Here'
    const vision = require('@google-cloud/vision');
    try {
      const client = new vision.ImageAnnotatorClient();
      var filename = particularbillpic.replace(/^.*[\\\/]/, '')
      const [result] = await client.textDetection('public/uploads/' + filename);
      const detections = result.textAnnotations;
      console.log('Text:');
      detections.forEach(function(text) {
        if (text.description.includes(particularbillname) && gcn === false) {
          rating = rating + 1;
          gcn = true;
          console.log("<---------------------------------->cname");
        }
        if (text.description.includes(particularbillnumber) && gcb === false) {
          rating = rating + 1;
          gcb = true;
          console.log("<---------------------------------->cbno");
        }
        if (text.description.includes(gdate.toLocaleDateString()) && gbd === false) {
          rating = rating + 1;
          gbd = true;
          console.log("<---------------------------------->bdate");
        }
        if (text.description.includes(particularshopname) && gsn === false) {
          rating = rating + 1;
          gsn = true;
          console.log("<---------------------------------->sname");
        }
        if (text.description.includes(particularbillamount) && gba === false) {
          rating = rating + 1;
          gba = true;
          console.log("<---------------------------------->bamount");
        }

      });
    } catch (err) {
      console.log(err);
    }

    console.log("<----->rating= " + rating);
    return rating;
  }

  function insertentry(particularbillnumber, particularbillname, particularbilldate, particularshopname, particularbillamount, particularbillpic, q, rt) {
    console.log("<----->inserting ");
    console.log("Finished");
    connection.query('Insert into bill_details (customer_bill_no,customer_name,bill_date,shop_name,bill_amount,bill_image,bill_creation_time,bill_rating) values(?,?,?,?,?,?,?,?)', [particularbillnumber, particularbillname, particularbilldate, particularshopname, particularbillamount, particularbillpic, q, rt], function(error, results, fields) {
      console.log(error);
    });
  };

});

/* <----------------------------------------Test---------------------------------------------------------------------------->*/

app.get("/displaybilldetails", function(req, res) {
  let bid = req.query.bill_id;
  connection.query("Select * from bill_details where bill_id=?", [bid], function(error, results, fields) {
    if (error) throw error;
    let billdt = results;
    console.log(billdt.bill_id);
    res.render('bill_details', {
      bill_no: results[0].customer_bill_no,
      c_name: results[0].customer_name,
      b_date: results[0].bill_date,
      s_name: results[0].shop_name,
      b_amt: results[0].bill_amount,
      b_imgt: results[0].bill_image,
      b_rate: results[0].bill_rating
    });

  });
});

app.get("/getdata", function(req, res) {
  let bid = req.query.bill_id;
  connection.query("Select * from bill_details ORDER BY bill_creation_time ASC", function(error, results, fields) {
    if (error) throw error;
    let billdt = results;
    res.send(results);

  });
});

app.get('/displayallbills', function(req, res) {
  const regno = req.body.regno;

  var bill_sql = "Select * from bill_details ORDER BY bill_creation_time ASC;";

  connection.query(bill_sql, function(error, results, fields) {
    if (error) throw error;
    if (results.length > 0) {
      var bill_details = results;
      let tot_bills = results.length;
      res.render('datadisplay', {
        bill_details: bill_details,
        tot: tot_bills
      });
    } else {
      res.render('empty');
    }
  });
});

/* End Route */

app.listen(3000, function() {
  console.log('App listening on port 8080!')
});

/* For Ajax */
app.post("/checkcorrect", function(req, res) {
  var bno = req.body.Bill_Number;
  var sname = req.body.Shop_Name;
  connection.query('Select * from bill_details where customer_bill_no=? AND shop_name=?', [bno, sname], function(error, results, fields) {
    if (error) {
      console.log(error);
    }
    if (results.length > 0) {
      res.send("Exists");
    } else {
      res.send("Does not exists");
    }
  });
});
<file_sep><!DOCTYPE html>

  <meta charset="utf-8">
  <title>Bill</title>
  <link rel="stylesheet" href="/css/styles.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
  <link rel="preconnect" href="https://fonts.gstatic.com">

  <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&family=Titillium+Web:wght@700&display=swap" rel="stylesheet">

Add Bill

        <form id="billform" class="transperantform" action="/upload" method="post"   enctype="multipart/form-data">

                Name of customer
                Customer Bill Number
                Bill Date
                Shop Name
                Bill Amount
                Attach An Image Of The Bill

                <input class="form-control isize" type="text" name="customername[]" placeholder="Name" autofocus required>
                 <input id="billno1" class="form-control isize identbill " type="text" name="customerbillno[]" placeholder="Customer Bill No"  onkeyup="billnoverify()" autofocus required>
                <input id="billdate1" class="form-control isize identdate" type="date" onchange='datechange()' name="billdate[]" placeholder="Bill Date" autofocus required>
                 <select id="shopname1" class="form-control isize " onchange="shopchange()" name="shopname[]">
                  <% shops.forEach(function(shopn){ %>
                             <option value=<%=shopn.shopname %> > <%= shopn.shopname %> </option>
                  <%  }) %>
                  </select>
                <input class="form-control isize" type="number" name="billamount[]" placeholder="Bill Amount" class="form-control" required>
                 <input type="file" onchange="check()" id="fileUpload1" class="form-control isize inde" name="billpics" placeholder="Image Of The Bill" required>

            <button id="addnewrow" class="btn btn-primary btn-lg fontdesign" value="AddRow">Add</button>

          <button id="applycoupon" class="btn btn-primary btn-block fontdesign" value="Upload">Apply For Coupon</button>
        </form>

<file_sep><!DOCTYPE html>

    <meta charset="utf-8">
    <title>Invalid Date</title>
    <link rel="stylesheet" href="/css/styles.css">
    <link rel="preconnect" href="https://fonts.gstatic.com">
  <link href="https://fonts.googleapis.com/css2?family=Bungee+Shade&family=Montserrat&display=swap" rel="stylesheet">

Invalid Date!!! 🙃

      ‹

The Entered Date is wrong

<file_sep>function validateForm()
{
  if($("#billdate").css("border-color") === "rgb(255, 0, 0)" &&  $("#billno").css("border-color") === "rgb(255, 0, 0)" )
  {
    window.alert("Bill Number Already exists and Invalid Bill Date");
    return false;
  }
  else if( $("#billdate").css("border-color") === "rgb(255, 0, 0)")
  {
      window.alert("Invalid Bill Date");
      return false;

  }
  else if( $("#billno").css("border-color") === "rgb(255, 0, 0)")
  {
      window.alert("Bill Number Already exists");
      return false;
  }
  else if( $(".ident").css("border-color") === "rgb(255, 0, 0)")
  {
    window.alert("Invalid Upload!! Please upload in proper image format");
    return false;
  }

}
<file_sep><!DOCTYPE html>

  <meta charset="utf-8">
  <title>Bill Details</title>
  <link rel="stylesheet" href="/css/styles.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
  <link rel="preconnect" href="https://fonts.gstatic.com">

  <link href="https://fonts.googleapis.com/css2?family=Lato:wght@300&family=Montserrat:wght@500&display=swap" rel="stylesheet">

Customer Bills

            Customer Bill Id
            Customer Bill Number
            Customer Name
            Bill Date
            Shop Name
            Bill Amount
            Bill Image
            Entry Time
            Bill Rating

          <% bill_details.forEach(function( eachbill ){ %>

            <%= eachbill.bill_id %>
            <%= eachbill.customer_bill_no %>
            <%= eachbill.customer_name %>
            <%= eachbill.bill_date %>
            <%= eachbill.shop_name %>
            <%= eachbill.bill_amount %>
            <%= eachbill.bill_image %>
            <%= eachbill.bill_creation_time %>
              <% for (i = 0; i <  eachbill.bill_rating; i++) { %>

              <% } %>

          <% }) %>

    Total No of Bills: <%= tot %>

languages: Markdown EJS JavaScript

repo_name: jodtribhu/OCRRecognitionBill


text:
<file_sep># isync

> A straightforward and zero-dependency [NodeJS](https://nodejs.org/) module to automatically persist JavaScript objects to disk at intervals, in [JSON](http://www.json.org/).

[![npm version](https://badge.fury.io/js/isync.svg)](https://badge.fury.io/js/isync) [![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=kuv_isync&metric=sqale_rating)](https://sonarcloud.io/dashboard?id=kuv_isync)

Released under the terms of the [Beerware](https://fedoraproject.org/wiki/Licensing/Beerware) license.

Contact me on [Telegram](https://telegram.org/) at [@kuvam](https://t.me/kuvam).

## Installation

`npm install isync --save`

## Usage

1\. Load isync.

```javascript
const isync = require('isync')
```

2\. Create an instance of isync. (If the file already exists, isync will attempt to synchronously parse it as JSON to the `data` property.)

```javascript
const store = new isync('./store.json')
```

3\. (a) Use the `data` property as a plain-jane JavaScript object.

```javascript
store.data.x = "foo"
store.data.y = [3, "bar", false]
store.data.z = { baz: store.data.x + "d", _: [null] }
```

3\. (b) Alternatively, set it to an existing object you want to persist.

```javascript
const blob = { pi: 22 / 7, e: [2, 7, 1, 8] }
store.data = blob
```

4\. The `data` object will be automatically synced at the specified interval (defaults to 10 minutes if unspecified) while your NodeJS program is running.

5\. Before exiting, flush any last-minute changes manually using `flushSync()`.

```javascript
store.flushSync()
```

## Details

1\. An instance of isync is initialised with this constructor signature.

```javascript
new isync(path: String, period?: Number)
```

> The period is specified in minutes and optional (defaults to 10 minutes).

2\. Instances expose the following properties.

```javascript
path
```

> File path which this isync instance saves the `data` object to. Change it by assigning a new file path to this property.

```javascript
data
```

> A regular JavaScript object, which is serialised as [JSON](http://www.json.org/) and synced to the file path specified. Properties which aren't JSON-serialisable won't be saved to disk.

```javascript
period
```

> The interval in minutes at which to flush the `data` object to disk. Change this interval by setting this property; its value will be used from the next sync onwards.

3\. Instances expose the following methods.

```javascript
unlink()
```

> Stops syncing the `data` object to disk at intervals. You can still use it as you would, but changes since the last sync won't be saved automatically.

```javascript
link()
```

> Restarts syncing the `data` object, after a call to `unlink()`. (You don't need to call this if you haven't unlinked the instance; by default, newly initialised instances of isync will be syncing automatically.)

```javascript
flushSync()
```

> Force a synchronous (thread blocking) flush of the `data` object to disk, even if the instance is unlinked. It is necessary to call this before your NodeJS application exits, unless you're absolutely sure there have been no changes to `data` since the last sync.

```javascript
flush(link: Boolean)
```

> An asynchronous (non-blocking) call to save the `data` object to disk, even if the instance is unlinked. If the `link` parameter is set, calls `link()` on this instance after completion.
>
> Bear in mind that you can't await this call; however, you can listen on the next `'flush'` event after making this call to proceed whenever the flush is completed.

4\. You can listen on `'flush'` events on an isync instance (`store` in this example) using idiomatic [NodeJS events](https://nodejs.org/api/events.html).

```javascript
store.on('flush', callback)
```

> This event is emitted on completion of both manual and automatic syncs. You can use it to confirm that data has been saved to disk successfully or to log disk syncs.

❤   June, 2017  –  March, 2019.

repo_name: kuvam/isync


text:
<file_sep><?php

namespace App\Controller;

use App\Entity\User;
use App\Form\ProfilType;
use App\Form\SearchType;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

class AppController extends AbstractController
{
    /**
     * @Route("/app", name="app")
     */
    public function index()
    {
        $user = $this->getUser();
        if ($user->getDetail() == null){
            return $this->redirectToRoute('form_details');
        }
        return $this->render('app/index.html.twig', [
            'controller_name' => 'AppController',
        ]);
    }

    /**
     * @Route("/app/profil", name="profil")
     */
    public function profil(Request $request, UserPasswordEncoderInterface $encoder){

        $user = new User();

        $form = $this->createForm(ProfilType::class, $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isRequired()){
            $data = $form->getData();
            $hash = $encoder->encodePassword($user, $data->getPassword());
            $entityManager = $this->getDoctrine()->getManager();
            $user = $entityManager->getRepository(User::class)->find($this->getUser());
            $user->setPassword($hash);
            $user->setUsername($data->getUsername());
            $user->setEmail($data->getEmail());
            $entityManager->flush();
            $this->addFlash(
                'success',
                "Votre informations ont bien été mis à jour !"
            );
            return $this->redirectToRoute("app");
        }
        return $this->render('app/profil.html.twig', [
            'form' => $form->createView()
        ]);
    }

    /**
     * @Route("app/recherche", name="form_recherche")
     */
    public function search(Request $request, ObjectManager $manager){

        $form = $this->createForm(SearchType::class);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isRequired()){
            $data = $form->getData();
            $manager = $this->getDoctrine()->getManager();
            $repository = $manager->getRepository(User::class);
            $query = $repository->createQueryBuilder('u')
                ->join('u.sports', 'c')
                ->where('u.nom = :nom')
                ->orWhere('u.prenom = :prenom')
                ->orWhere('c.nom = :sport')
                ->setParameter('nom', $data['nom'])
                ->setParameter('prenom', $data['prenom'])
                ->setParameter('sport', $data['sports']->getNom())
                ->getQuery()

                ->getResult();

            return $this->render('app/resultat.html.twig', [
                'resultat' => $query
            ]);

        }

        return $this->render('app/rechercher.html.twig', [
            'form' => $form->createView()
        ]);
    }
    /**
     * @Route("/app/mes-sports", name="messports")
     */
    public function viewSport()
    {
        return $this->render('app/mes-sport.html.twig');
    }

}
<file_sep>{% extends 'base.html.twig' %}
{% block body %}

    {{ form_start(form, {'attr': {'class': 'form-signin'}}) }}

Formulaire d'inscription

            {{ form_label(form.nom) }}
            {{ form_widget(form.nom) }}

            {{ form_label(form.prenom) }}
            {{ form_widget(form.prenom) }}

        {{ form_label(form.username) }}
        {{ form_widget(form.username) }}

        {{ form_label(form.email) }}
        {{ form_widget(form.email) }}
        {{ form_errors(form.email) }}

        {{ form_label(form.password) }}
        {{ form_widget(form.password) }}
        {{ form_errors(form.password) }}

            {{ form_widget(form.sexe[0], {'attr': {'class': 'form-check-input'}}) }}
            {{ form_label(form.sexe[0]) }}

            {{ form_widget(form.sexe[1], {'attr': {'class': 'form-check-input'}}) }}
            {{ form_label(form.sexe[1]) }}

        {{ form_label(form.age) }}
        {{ form_widget(form.age) }}

        <button class="btn btn-lg btn-primary btn-block" type="submit">Inscription</button>

retour à la connexion

    {{ form_end(form) }}

{% endblock %}
<file_sep><?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @UniqueEntity(
 *     fields={"email"},
 *     message="L'email est déjà utilisé par un autre utilisateur"
 * )
 */
class User implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $username;

    /**
     * @ORM\Column(type="string", length=255)
     * @
     */
    private $email;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\Length(min="8", minMessage="Votre mot de passe doit faire au minimum 8 caractères !")
     */
    private $password;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $nom;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $prenom;

    /**
     * @ORM\Column(type="integer")
     */
    private $age;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $sexe;

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Sport", inversedBy="users")
     */
    private $sports;

    /**
     * @ORM\OneToOne(targetEntity="App\Entity\Detail", cascade={"persist", "remove"})
     */
    private $detail;

    public function __construct()
    {
        $this->sports = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getUsername(): ?string
    {
        return $this->username;
    }

    public function setUsername(string $username): self
    {
        $this->username = $username;

        return $this;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;

        return $this;
    }

    public function getPassword(): ?string
    {
        return $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    public function getNom(): ?string
    {
        return $this->nom;
    }

    public function setNom(string $nom): self
    {
        $this->nom = $nom;

        return $this;
    }

    public function getPrenom(): ?string
    {
        return $this->prenom;
    }

    public function setPrenom(string $prenom): self
    {
        $this->prenom = $prenom;

        return $this;
    }

    public function getAge(): ?string
    {
        return $this->age;
    }

    public function setAge(string $age): self
    {
        $this->age = $age;

        return $this;
    }

    public function getSexe(): ?string
    {
        return $this->sexe;
    }

    public function setSexe(string $sexe): self
    {
        $this->sexe = $sexe;

        return $this;
    }

    public function eraseCredentials() {}

    public function getSalt() {}

    public function getRoles()
    {
        return ['ROLE_USER'];
    }

    /**
     * @return Collection|Sport[]
     */
    public function getSports(): Collection
    {
        return $this->sports;
    }

    public function addSport(Sport $sport): self
    {
        if (!$this->sports->contains($sport)) {
            $this->sports[] = $sport;
        }

        return $this;
    }

    public function removeSport(Sport $sport): self
    {
        if ($this->sports->contains($sport)) {
            $this->sports->removeElement($sport);
        }

        return $this;
    }

    public function getDetail(): ?Detail
    {
        return $this->detail;
    }

    public function setDetail(?Detail $detail): self
    {
        $this->detail = $detail;

        return $this;
    }
}
<file_sep>{% extends 'app.html.twig' %}

{% block body %}

Mes sports |  modifier mes sports

                {% for sport in app.user.sports %}

{{ sport.nom }}

                {% endfor %}

{% endblock %}
<file_sep><!DOCTYPE html>

        {% block head %}
        <meta charset="UTF-8">
        <title>{% block title %}SOS Partenaire{% endblock %}</title>
            <link rel="stylesheet" href="{{ asset('app.css') }}">
            <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="<KEY>" crossorigin="anonymous">
            <link href="https://stackpath.bootstrapcdn.com/bootswatch/4.3.1/materia/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous">
        {% endblock %}

        SOS Partenaire
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation">

        </button>

                    Accueil

                    Rechercher

                    Profil

                    Mes sports

                <button class="btn btn-danger my-2 my-sm-0" type="button">Déconnexion</button>

        {% block body %}

        {% endblock %}

        {% block javascripts %}

        {% endblock %}

<file_sep>{% extends 'app.html.twig' %}

{% block body %}

Résultat de la recherche : {{ resultat|length }} sportif(s) trouvé(s)

            {% for joueur in resultat %}

{{ joueur.age }}ans - {{ joueur.sexe }}

{{ joueur.nom }} {{ joueur.prenom }}

Joueur de :

                            {% for sport in joueur.sports %}

- {{ sport.nom }}

                            {% endfor %}

Email : {{ joueur.email }}

            {% endfor %}

{% endblock %}
<file_sep>{% extends 'app.html.twig' %}

{% block body %}

Profil de {{ app.user.prenom }}

                    {{ form_start(form) }}
                            <form class="form-signin"  method="post" >

                                    {{ form_label(form.username) }}
                                    {{ form_widget(form.username , {'value' : app.user.username }) }}

                                    {{ form_label(form.email) }}
                                    {{ form_widget(form.email , {'value' : app.user.email }) }}

                                    {{ form_label(form.password) }}
                                    {{ form_widget(form.password) }}

                                        <button class="btn btn-lg btn-success" type="submit"> Mettre à jour</button>
                                        <button class="btn btn-lg" type="reset"> Annuler</button>

                            </form>

{% endblock %}
<file_sep>{% extends 'app.html.twig' %}

{% block body %}

Formulaire détails

Merci d'indiquer ci dessous quelques renseignements sur toi

                {{ form_start(form, {'attr': {'class': 'form-signin'}}) }}

                    {{ form_label(form.telephone) }}
                    {{ form_widget(form.telephone) }}

                    {{ form_label(form.ville) }}
                    {{ form_widget(form.ville) }}

                    {{ form_label(form.codePostal) }}
                    {{ form_widget(form.codePostal) }}

                <button class="mt-3 btn btn-success">Suivant</button>
                {{ form_end(form) }}

{% endblock %}
<file_sep>{% extends 'app.html.twig' %}

{% block body %}

Formulaire sports

Merci d'indiquer ci-dessous, les sports que tu pratiquent

                {% for errorMessage in app.flashes('error') %}

{{ errorMessage }}

                {% endfor %}
                {% for succesMessage in app.flashes('success') %}

{{ succesMessage }}

                {% endfor %}
                {{ form_start(form) }}

                {% for sport in form.users.children%}

                            <input type="checkbox" class="custom-control-input" id="{{ sport.vars.id }}" name="{{ sport.vars.full_name }}" value="{{ sport.vars.name }}">

                                        {{ sport.vars.label }}

                {% endfor %}

                <button class="btn btn-success mt-5" type="submit">Suivant</button>
                {{ form_end(form , {'render_rest': false}) }}

{% endblock %}
<file_sep>{% extends 'app.html.twig' %}

{% block body %}

Accueil

                {% for errorMessage in app.flashes('error') %}

{{ errorMessage }}

                {% endfor %}
                {% for succesMessage in app.flashes('success') %}

{{ succesMessage }}

                {% endfor %}

{% endblock %}
<file_sep>{% extends 'app.html.twig' %}

{% block body %}

Rechercher un joueur

                {{ form_start(form) }}

                    {{ form_label(form.nom,null, {'label_attr' : {'class' : 'col-sm-2 col-form-label'}}) }}

                        {{ form_widget(form.nom, {'attr' : {'class' : 'form-control'}}) }}

                    {{ form_label(form.prenom,null, {'label_attr' : {'class' : 'col-sm-2 col-form-label'}}) }}

                        {{ form_widget(form.prenom, {'attr' : {'class' : 'form-control'}}) }}

                    Jeux :

                        {{ form_widget(form.sports, {'attr' : {'class' : 'form-control'}}) }}

                        <button type="submit" class="btn btn-primary">Lancer la recherche</button>

                {{ form_end(form) }}

{% endblock %}
<file_sep><?php

namespace App\Controller;

use App\Entity\Detail;
use App\Entity\Sport;
use App\Form\DetailType;
use App\Form\SportType;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class FormController extends AbstractController
{
    /**
     * @Route("/app/ajouter-details", name="form_details")
     */
    public function form_details(Request $request, ObjectManager $manager)
    {
        if ($this->getUser()->getDetail() !== null){
            return $this->redirectToRoute("app");
        }
        $detail = new Detail();

        $form = $this->createForm(DetailType::class,$detail);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()){
            $user = $this->getUser();
            $user->setDetail($detail);
            $manager->persist($user);
            $manager->flush();
            $this->addFlash(
                'success',
                "Vos informations ont bien été enregistrées"
            );
            return $this->redirectToRoute('form_sport');
        }

        return $this->render('app/form_details.twig', [
            'form' => $form->createView()
        ]);
    }

    /**
     * @Route("/app/ajouter-sport", name="form_sport")
     */
    public function form_sport(Request $request, ObjectManager $manager){
        $sport = new Sport();

        $form = $this->createForm(SportType::class, $sport);
        $form->handleRequest($request);

        if ($form->isSubmitted()){
            $user = $this->getUser();

            $data = $form->getData();
            foreach ($data->getUsers() as $game){
                $user->addSport($game);
                $manager->persist($user);
                $manager->flush();
            }
            $this->addFlash(
                'success',
                "Vos sports ont bien été prise en compte !"
            );
            return $this->redirectToRoute('app');
        }

        return $this->render('app/form_sport.twig', [
            'form' => $form->createView()
        ]);

    }
}
<file_sep>{% extends 'base.html.twig' %}
{% block body %}

    <form  method="post" action="{{ path('security_login') }}" class="form-signin">

Formulaire de connexion

        {% for errorMessage in app.flashes('error') %}

{{ errorMessage }}

        {% endfor %}
        {% for succesMessage in app.flashes('success') %}

{{ succesMessage }}

        {% endfor %}

            <input id="email" type="email" class="form-control" name="_username" placeholder="Email" value="{{ lastUsername }}">

            <input id="mdp" type="password" class="form-control" name="_password" placeholder="<PASSWORD>">

            <button class="btn btn-lg btn-primary btn-block" type="submit">Connexion</button>

Première visite ?

    </form>

{% endblock %}
<file_sep><?php

declare(strict_types=1);

namespace DoctrineMigrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
final class Version20190525133039 extends AbstractMigration
{
    public function getDescription() : string
    {
        return '';
    }

    public function up(Schema $schema) : void
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('CREATE TABLE sport (id INT AUTO_INCREMENT NOT NULL, nom VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB');
        $this->addSql('CREATE TABLE user_sport (user_id INT NOT NULL, sport_id INT NOT NULL, INDEX IDX_F847148AA76ED395 (user_id), INDEX IDX_F847148AAC78BCF8 (sport_id), PRIMARY KEY(user_id, sport_id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB');
        $this->addSql('ALTER TABLE user_sport ADD CONSTRAINT FK_F847148AA76ED395 FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE CASCADE');
        $this->addSql('ALTER TABLE user_sport ADD CONSTRAINT FK_F847148AAC78BCF8 FOREIGN KEY (sport_id) REFERENCES sport (id) ON DELETE CASCADE');
    }

    public function down(Schema $schema) : void
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE user_sport DROP FOREIGN KEY FK_F847148AAC78BCF8');
        $this->addSql('DROP TABLE sport');
        $this->addSql('DROP TABLE user_sport');
    }
}
<file_sep># Symfony---SOS-Partner
<file_sep><?php

namespace App\Form;

use App\Entity\Game;
use App\Entity\Sport;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class SearchType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('nom',TextType::class, [
                'required' => false,
                'label' => 'Nom du joueur',
                'attr' => [
                    'class' => 'form-control',
                    'placeholder' => 'Entrer le nom du joueur'
                ]
            ])
            ->add('prenom',TextType::class, [
                'required' => false,
                'label' => 'Prénom du joueur',
                'attr' => [
                    'class' => 'form-control',
                    'placeholder' => 'Entrer le prénom du joueur'
                ]
            ])
            ->add('sports', EntityType::class, [
                'class' => Sport::class,
                'multiple' => false,
                'expanded' => false,
                'choice_label' => 'nom',
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            // Configure your form options here
        ]);
    }
}

languages: Twig Markdown PHP

repo_language: Twig

repo_name: SimonGENY/Symfony---SOS-Partner