branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { FacepaintingPage } from './facepainting';
@NgModule({
declarations: [
FacepaintingPage,
],
imports: [
IonicPageModule.forChild(FacepaintingPage),
],
})
export class FacepaintingPageModule {}
<file_sep>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { SolosingingPage } from './solosinging';
@NgModule({
declarations: [
SolosingingPage,
],
imports: [
IonicPageModule.forChild(SolosingingPage),
],
})
export class SolosingingPageModule {}
<file_sep>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { SolodancePage } from './solodance';
@NgModule({
declarations: [
SolodancePage,
],
imports: [
IonicPageModule.forChild(SolodancePage),
],
})
export class SolodancePageModule {}
<file_sep>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { SlowdragPage } from './slowdrag';
@NgModule({
declarations: [
SlowdragPage,
],
imports: [
IonicPageModule.forChild(SlowdragPage),
],
})
export class SlowdragPageModule {}
<file_sep>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { MimePage } from './mime';
@NgModule({
declarations: [
MimePage,
],
imports: [
IonicPageModule.forChild(MimePage),
],
})
export class MimePageModule {}
<file_sep>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { FashionshowPage } from './fashionshow';
@NgModule({
declarations: [
FashionshowPage,
],
imports: [
IonicPageModule.forChild(FashionshowPage),
],
})
export class FashionshowPageModule {}
<file_sep>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { MramdmssvitPage } from './mramdmssvit';
@NgModule({
declarations: [
MramdmssvitPage,
],
imports: [
IonicPageModule.forChild(MramdmssvitPage),
],
})
export class MramdmssvitPageModule {}
<file_sep>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { VegetablecarvingPage } from './vegetablecarving';
@NgModule({
declarations: [
VegetablecarvingPage,
],
imports: [
IonicPageModule.forChild(VegetablecarvingPage),
],
})
export class VegetablecarvingPageModule {}
<file_sep>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { GroupsingingPage } from './groupsinging';
@NgModule({
declarations: [
GroupsingingPage,
],
imports: [
IonicPageModule.forChild(GroupsingingPage),
],
})
export class GroupsingingPageModule {}
<file_sep>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { MadadsPage } from './madads';
@NgModule({
declarations: [
MadadsPage,
],
imports: [
IonicPageModule.forChild(MadadsPage),
],
})
export class MadadsPageModule {}
<file_sep>import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
/**
* Generated class for the GamingPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-gaming',
templateUrl: 'gaming.html',
})
export class GamingPage {
constructor(public navCtrl: NavController, public navParams: NavParams) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad GamingPage');
}
}
<file_sep>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { InstrumentalPage } from './instrumental';
@NgModule({
declarations: [
InstrumentalPage,
],
imports: [
IonicPageModule.forChild(InstrumentalPage),
],
})
export class InstrumentalPageModule {}
<file_sep>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { MehendiPage } from './mehendi';
@NgModule({
declarations: [
MehendiPage,
],
imports: [
IonicPageModule.forChild(MehendiPage),
],
})
export class MehendiPageModule {}
<file_sep>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { DubsmashPage } from './dubsmash';
@NgModule({
declarations: [
DubsmashPage,
],
imports: [
IonicPageModule.forChild(DubsmashPage),
],
})
export class DubsmashPageModule {}
<file_sep>import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
/**
* Generated class for the ShortmoviePage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-shortmovie',
templateUrl: 'shortmovie.html',
})
export class ShortmoviePage {
constructor(public navCtrl: NavController, public navParams: NavParams) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad ShortmoviePage');
}
}
<file_sep>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { CartooningPage } from './cartooning';
@NgModule({
declarations: [
CartooningPage,
],
imports: [
IonicPageModule.forChild(CartooningPage),
],
})
export class CartooningPageModule {}
<file_sep>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { SuperminutePage } from './superminute';
@NgModule({
declarations: [
SuperminutePage,
],
imports: [
IonicPageModule.forChild(SuperminutePage),
],
})
export class SuperminutePageModule {}
<file_sep><!--
Generated template for the MadadsPage page.
See http://ionicframework.com/docs/components/#navigation for more info on
Ionic pages and navigation.
-->
<ion-header>
<ion-navbar>
<ion-title>Mad-Ads</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<h1 style="text-align:center">
Rules
</h1>
<br />
<ul>
<li><h6>Minimum 3 teams are required for the judgement.</h6></li>
<br />
<li><h6>Duration is 10+5 minutes (three minutes is for stage setting).</h6></li>
<br />
<li><h6>Maximum number of members in a team is 8+2.</h6></li>
<br />
<li><h6>The caution should be taken to refrain from displaying obscenity, violence, prejudice, defamation etc.<i>Negative markings will be allocated for showcase of vulgarity.</i></h6></li>
<br />
<li><h6>
Judgement will be based on
<ol>
<li><p>Presentation.</p></li>
<li><p>Variety.</p></li>
<li><p>Skill.</p></li>
</ol>
</h6></li>
<li><h6>Judges decision will be final.</h6></li>
</ul>
<br />
<h1 style="text-align:center">
Faculty Co-ordinators
</h1>
<div text-center>
<ion-img style="width:180px; height:180px; margin:auto;" src="images/mech/arjun.jpg"></ion-img>
<p>Prof. <NAME> (9900098499)</p>
</div>
<br />
<div text-center>
<ion-img style="width:180px; height:180px; margin:auto;" src="images/mech/arun.jpg"></ion-img>
<p>Prof. <NAME> (9916919576)</p>
</div>
<br />
<h3 text-center>Student Co-ordinators</h3>
<ul>
<li><h6><NAME></h6></li>
<li><h6><NAME></h6></li>
<li><h6><NAME></h6></li>
<li><h6><NAME></h6></li>
</ul>
</ion-content>
<file_sep><!--
Generated template for the FacepaintingPage page.
See http://ionicframework.com/docs/components/#navigation for more info on
Ionic pages and navigation.
-->
<ion-header>
<ion-navbar>
<ion-title>Face painting</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<h1 style="text-align:center">
Rules
</h1>
<br />
<ul>
<li><h6>Theme wiil be announced on the spot.</h6></li>
<li><h6>Get your own materials.</h6></li>
<li><h6>Time limit - 1 hour and 30 minutes.</h6></li>
<li><h6>You need to get your partner to do the face painting.</h6></li>
</ul>
<br />
<h1 style="text-align:center">
Faculty Co-ordinators
</h1>
<div text-center>
<ion-img style="width:180px; height:110px; margin:auto;" src="images/chemistry/sathyanarayani.jpg"></ion-img>
<p>Prof. <NAME> (9686517626)</p>
</div>
<br />
<div text-center>
<ion-img style="width:180px; height:180px; margin:auto;" src="images/physics/yashoda.jpeg"></ion-img>
<p>Prof. Yashodha</p>
</div>
<br />
<h3 text-center>Student Co-ordinators</h3>
<ul>
<li><h6>Kusumanjali</h6></li>
<li><h6><NAME></h6></li>
</ul>
</ion-content>
<file_sep>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { CookingwithoutfirePage } from './cookingwithoutfire';
@NgModule({
declarations: [
CookingwithoutfirePage,
],
imports: [
IonicPageModule.forChild(CookingwithoutfirePage),
],
})
export class CookingwithoutfirePageModule {}
<file_sep>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(private navCtrl: NavController) {
}
navigateToHogathonPage(): void {
this.navCtrl.push('HogathonPage');
}
navigateToTreasureHuntPage(): void {
this.navCtrl.push('TreasurehuntPage');
}
navigateToMadAdsPage(): void {
this.navCtrl.push('MadadsPage');
}
navigateToSkitPage(): void {
this.navCtrl.push('SkitPage');
}
navigateToAnthyakshariPage(): void {
this.navCtrl.push('AnthyakshariPage');
}
navigateToBestOutOfWastePage(): void {
this.navCtrl.push('BestoutofwastePage');
}
navigateToCartooningPage(): void {
this.navCtrl.push('CartooningPage');
}
navigateToCookingWithoutFirePage(): void {
this.navCtrl.push('CookingwithoutfirePage');
}
navigateToDumsmashPage(): void {
this.navCtrl.push('DubsmashPage');
}
navigateToFacePaintingPage():void {
this.navCtrl.push('FacepaintingPage');
}
navigateToFashionShowPage(): void {
this.navCtrl.push('FashionshowPage');
}
navigateToGamingShowPage(): void {
this.navCtrl.push('GamingPage');
}
navigateToGroupDancePage(): void {
this.navCtrl.push('GroupdancePage');
}
navigateToGroupSingingPage(): void {
this.navCtrl.push('GroupsingingPage');
}
navigateToInstrumentalPage(): void {
this.navCtrl.push('InstrumentalPage');
}
navigateToMehendiPage(): void {
this.navCtrl.push('MehendiPage');
}
navigateToMimePage(): void {
this.navCtrl.push('MimePage');
}
navigateToMrAndMrsSvitPage(): void {
this.navCtrl.push('MramdmssvitPage');
}
navigatToPaintingPage(): void {
this.navCtrl.push('PaintingPage');
}
navigateToPhotographyPage(): void {
this.navCtrl.push('PhotographyPage');
}
navigateToRangoliPage(): void {
this.navCtrl.push('RangoliPage');
}
navigateToShortMoviePage(): void {
this.navCtrl.push('ShortmoviePage');
}
navigateToSlowDragPage(): void {
this.navCtrl.push('SlowdragPage');
}
navigateToSoloDancepage(): void {
this.navCtrl.push('SolodancePage');
}
navigateToSoloSingingPage(): void {
this.navCtrl.push('SolosingingPage');
}
navigateToSuperMinutePage(): void {
this.navCtrl.push('SuperminutePage');
}
navigateToVegetableCarvingPage(): void {
this.navCtrl.push('VegetablecarvingPage');
}
}
<file_sep>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { ShortmoviePage } from './shortmovie';
@NgModule({
declarations: [
ShortmoviePage,
],
imports: [
IonicPageModule.forChild(ShortmoviePage),
],
})
export class ShortmoviePageModule {}
<file_sep><!--
Generated template for the PaintingPage page.
See http://ionicframework.com/docs/components/#navigation for more info on
Ionic pages and navigation.
-->
<ion-header>
<ion-navbar>
<ion-title>Painting</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<h1 style="text-align:center">
Rules
</h1>
<br />
<ul>
<li><h6>Induvidual event.</h6></li>
<li><h6>Participants shall paint induvidually and not as a team.</h6></li>
<li><h6>Participants will bring their own water colors and the other painting materials.</h6></li>
</ul>
<br />
<h1 style="text-align:center">
Faculty Co-ordinators
</h1>
<div text-center>
<ion-img style="width:180px; height:120px; margin:auto;" src="images/eee/rekhamurthy.jpg"></ion-img>
<p>Prof. Rekhamurthy (9731156201)</p>
</div>
<br />
<div text-center>
<ion-img style="width:180px; height:120px; margin:auto;" src="images/eee/shilpapatil.jpg"></ion-img>
<p>Prof. <NAME> (9902748003)</p>
</div>
<br />
<h3 text-center>Student Co-ordinators</h3>
<ul>
<li><h6><NAME></h6></li>
<li><h6>Sampritha</h6></li>
</ul>
</ion-content>
<file_sep>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { PhotographyPage } from './photography';
@NgModule({
declarations: [
PhotographyPage,
],
imports: [
IonicPageModule.forChild(PhotographyPage),
],
})
export class PhotographyPageModule {}
<file_sep>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { PaintingPage } from './painting';
@NgModule({
declarations: [
PaintingPage,
],
imports: [
IonicPageModule.forChild(PaintingPage),
],
})
export class PaintingPageModule {}
<file_sep>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { RangoliPage } from './rangoli';
@NgModule({
declarations: [
RangoliPage,
],
imports: [
IonicPageModule.forChild(RangoliPage),
],
})
export class RangoliPageModule {}
<file_sep>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { HogathonPage } from './hogathon';
@NgModule({
declarations: [
HogathonPage,
],
imports: [
IonicPageModule.forChild(HogathonPage),
],
})
export class HogathonPageModule {}
| eb624c0cf234eaf983ac39608e4c7f43ae254e97 | [
"TypeScript",
"HTML"
] | 27 | TypeScript | shashank-shark/Android-Apps | d148f98acb5d75250f955de54d8ff1ec0ef7c620 | 69e79c599a2301aeee52ed9c2f42db52ab69542c |
refs/heads/main | <file_sep># SimonSay
A little game in which you must choose the colors that the computer says
<file_sep>const btnEmpezar=document.getElementById("btnEmpezar")
const celeste=document.getElementById("celeste")
const violeta=document.getElementById("violeta")
const naranja=document.getElementById("naranja")
const verde=document.getElementById("verde")
const ULTIMO_NIVEL=parseInt(prompt("cuantos niveles quieres?"))
document.getElementById("NumeroDeNiveles").innerHTML=ULTIMO_NIVEL
var contador=0
class Juego{
constructor(){
this.inicializar=this.inicializar.bind(this)
this.inicializar()
this.generarSecuency()
setTimeout(this.siguienteNivel(),50)
}
inicializar(){
this.siguienteNivel=this.siguienteNivel.bind(this)
this.elegirColor=this.elegirColor.bind(this)
this.toggleBtnEmpezar()
this.nivel=1
this.colores={
celeste,
violeta,
naranja,
verde
}
}
toggleBtnEmpezar(){
if (btnEmpezar.classList.contains("hide")){
btnEmpezar.classList.remove("hide")
}else{
btnEmpezar.classList.add("hide")
}
}
generarSecuency(){
this.secuency=new Array(ULTIMO_NIVEL).fill(0).map(n=>Math.floor(Math.random()*4))}
siguienteNivel(){
this.cambiarContador()
this.subnivel=0
this.iluminarSecuencia()
this.agregarEventosClick()
}
transformarNumeroAColor(num){
switch(num){
case 0:return "celeste"
case 1:return "violeta"
case 2:return "naranja"
case 3:return "verde"
}
}
transformarColorANumber(color){
switch(color){
case "celeste":return 0
case "violeta":return 1
case "naranja":return 2
case "verde":return 3
}
}
iluminarSecuencia(){
for (let i = 0; i < this.nivel; i++) {
const color=this.transformarNumeroAColor(this.secuency[i])
setTimeout(()=>{this.iluminarColor(color)},500*i)
}
}
iluminarColor(color){
this.colores[color].classList.add("light")
setTimeout(()=>this.apagarColor(color),250)
}
apagarColor(color){
this.colores[color].classList.remove("light")
}
agregarEventosClick(){
this.colores.celeste.addEventListener("click",this.elegirColor)
this.colores.verde.addEventListener("click",this.elegirColor)
this.colores.naranja.addEventListener("click",this.elegirColor)
this.colores.violeta.addEventListener("click",this.elegirColor)
}
eliminarEventosClick(){
this.colores.celeste.removeEventListener("click",this.elegirColor)
this.colores.verde.removeEventListener("click",this.elegirColor)
this.colores.naranja.removeEventListener("click",this.elegirColor)
this.colores.violeta.removeEventListener("click",this.elegirColor)
}
cambiarContador(){
contador++
document.getElementById("NumeroDeNivel").innerHTML=contador
}
elegirColor(ev){
const nombreColor=ev.target.dataset.color
const numeroColor =this.transformarColorANumber(nombreColor)
this.iluminarColor(nombreColor)
if(numeroColor===this.secuency[this.subnivel]){
this.subnivel++
if(this.subnivel===this.nivel){
this.nivel++
this.eliminarEventosClick()
if(this.nivel===(ULTIMO_NIVEL+1)){
contador=0
this.ganoElJuego()
}else{
setTimeout(this.siguienteNivel,700)
}
}
}else{
contador=0
this.PerdioElJuego()
}
}
ganoElJuego(){
swal("Oh si","Felicitaciones ,Ganaste el juego","success")
.then(this.inicializar)
}
PerdioElJuego(){
swal("Oh Rayos","Lo lamentamos,Perdiste el juego :(","error")
.then(()=>{
this.eliminarEventosClick()
this.inicializar()
})
}
}
function empezarJuego(){
window.juego=new Juego
}
colores=[celeste,violeta,naranja,verde] | 656cfd48b7ac9c1739116781f63139ef9a20a687 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | IsaiasFer/SimonSay | 89d6eafddb3b28cb3dd4b8bf6d3da02b4638a2a5 | 23e5234e89d823e428e4afc46f712e74b599d519 |
refs/heads/master | <file_sep>const Payment = require('../models/payment');
const Booking = require('../models/booking');
const mongoose = require('mongoose')
const ObjectId = mongoose.Types.ObjectId;
const Rental = require('../models/rental');
const User = require('../models/user');
const Comment = require('../models/comment')
const { normalizeErrors } = require('../helpers/mongoose');
exports.getUserRentals = (req, res) => {
const user = res.locals.user;
Rental
.where({ user })
.sort({ createdAt: -1 })
.populate('bookings')
.exec(function (err, foundRentals) {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
return res.json(foundRentals);
});
}
exports.verifyUser = (req, res) => {
const user = res.locals.user;
Rental
.findById(req.params.id)
.populate('user')
.exec(function (err, foundRental) {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
if (foundRental.user.id !== user.id) {
return res.status(422).send({ errors: { title: 'Invalid User!', detail: 'You are not rental owner!' } });
}
return res.json({ status: 'verified' });
});
}
exports.addSearchHistory = (req, res) => {
const rentalId = req.params.id;
const user = res.locals.user;
Rental.findById(rentalId)
.populate('user', 'username _id image message')
.populate('bookings', 'startAt endAt -_id')
.exec(function (err, foundRental) {
if (err || !foundRental) {
return res.status(422).send({ title: 'Rental Error!', detail: 'Không tồn tại nơi ở!' });
}
if (user) {
const searchHistory = user.searchHistory;
for (var i = 0; i < searchHistory.length; i++) {
if (String(searchHistory[i]._id) === rentalId) {
searchHistory.splice(i, 1);
}
}
if (rentalId)
searchHistory.unshift(rentalId)
user.searchHistory = searchHistory;
user.save((err) => {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
})
}
return res.json(foundRental);
});
}
exports.createRental = (req, res) => {
// const dUri = new Datauri();
Rental.findOne({ title: req.body.title }, (err, foundRental) => {
if (err)
return res.status(422).send({ errors: normalizeErrors(err.errors) });
if (foundRental)
return res.status(422).send({ title: 'Rentals Found!', detail: `Tên nhà ở đã có người sử dụng` });
const { title, city, address, category, bedrooms, bathrooms, description, price, people, isTv, isWifi,
isElevator, isWashing, isFridge, isConditioner, image } = req.body;
// Promise.all(change)
// .then(() => {
const rental = new Rental({
title, city, address, category, bedrooms, bathrooms,
description, price, people, isTv, isWifi, isElevator, isWashing, isFridge,
isConditioner, image
});
const user = res.locals.user._id;
rental.user = user;
Rental.create(rental, function (err, newRental) {
if (err) {
console.log(err)
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
User.update({ _id: user }, { $push: { rentals: newRental } }, function () { });
return res.json(newRental);
});
// })
// .catch((err) => { return res.status(422).send({ errors: normalizeErrors(err.errors) }); })
});
}
exports.deleteRental = (req, res) => {
const user = res.locals.user;
Rental
.findById(req.params.id)
.populate('user', '_id')
.populate({
path: 'bookings',
select: 'startAt',
match: { startAt: { $gt: new Date() } }
})
.exec(function (err, foundRental) {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
if (user.id !== foundRental.user.id) {
return res.status(422).send({ title: 'Invalid User!', detail: 'Bạn không phải là chủ nhà' });
}
if (foundRental.bookings.length > 0) {
return res.status(422).send({ title: 'Active Bookings!', detail: 'Không thể xóa nơi ở này' });
}
foundRental.remove(function (err) {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
Rental.find({}).then((rental) => res.json(rental))
// return res.json({ 'status': 'deleted' });
});
});
}
exports.getTopRentals = (req, res) => {
Rental
.find({ status: 'approved' })
.sort({ rating: -1 })
.limit(10)
.select('_id image title address rating price')
.exec(function (err, foundRental) {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
return res.json(foundRental);
});
}
exports.updateRental = (req, res) => {
const user = res.locals.user
Rental.findById(req.params.id, (err, foundRental) => {
if (err)
return res.status(422).send({ errors: normalizeErrors(err.errors) });
if (!foundRental)
return res.status(404).send({ title: 'No Rentals Found!', detail: `Không tồn tại nơi ở này` });
if (String(foundRental.user) !== String(user._id)) {
return res.status(422).send({ title: 'Không có quyền!', detail: `Bạn không có quyền chỉnh sửa` });
}
const { title, city, address, category, bedrooms, bathrooms, description, price, people, isTv, isWifi,
isElevator, isWashing, isFridge, isConditioner, image } = req.body;
const data = {
title, city, address, category, bedrooms, bathrooms,
description, price, people, isTv, isWifi,
isElevator, isWashing, isFridge, isConditioner, image
}
Rental.findByIdAndUpdate({ _id: req.body._id }, data, { new: true }, (err, rental) => {
res.json(rental)
})
})
}
<file_sep>const Booking = require('../models/booking');
const Rental = require('../models/rental');
const Payment = require('../models/payment');
const User = require('../models/user');
const { normalizeErrors } = require('../helpers/mongoose');
const moment = require('moment');
const config = require('../config');
exports.createBooking = (req, res) => {
var error = false;
var { startAt, endAt, guests, id, price/*rental, paymentToken*/ } = req.body;
const user = res.locals.user;
startAt = moment(startAt,'DD/MM/YYYY').format('MM/DD/YYYY');
endAt = moment(endAt,'DD/MM/YYYY').format('MM/DD/YYYY');
var d1 = new Date(startAt)//"now"
var d2 = new Date(endAt)// some date
var timeDiff = (d2.getTime() - d1.getTime());
if(timeDiff <= 0)
return res.status(422).send({ title: 'Thời gian không hợp lệ!', detail: 'Thời gian đặt phòng không hợp lệ'});
const days = Math.ceil(timeDiff / (1000 * 3600 * 24));
const totalPrice = price * days;
const booking = new Booking({ startAt, endAt, totalPrice, guests, days });
Rental.findById(id)
.populate('bookings')
.populate('user')
.exec(async function (err, foundRental) {
const user = res.locals.user;
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
if (foundRental.user != null) {
if (foundRental.user.id === user._id) {
return res.status(422).send({ title: 'Người dùng không hợp lệ!', detail: 'Không thể đặt phòng cho địa điểm bạn tạo!' });
}
}
// const wait = User.findById(user._id)
// .populate('bookings')
// .exec(async function (err, foundUser){
// if (!isValidUserBook(booking,foundUser))
// error = true;
// });
// Promise.all
if (isValidBooking(booking, foundRental)) {
booking.user = user;
booking.rental = foundRental;
booking.owner = foundRental.user;
foundRental.bookings.push(booking);
// const { payment, err } = await createPayment(booking, foundRental.user, paymentToken);
// if (payment) {
// booking.payment = payment;
booking.save(function (err) {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
foundRental.save()
User.update({ _id: user._id }, { $push: { bookings: booking } }, function () { });
Booking
.where({ user })
.sort({createdAt: -1})
.populate('owner', 'image username _id')
.populate('rental')
.exec(function (err, foundBookings) {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
return res.json(foundBookings);
});
});
// } else {
// return res.status(422).send({ errors: [{ title: 'Payment Error', detail: err }] });
// }
} else {
return res.status(422).send({ title: 'Đặt phòng không hợp lệ!', detail: 'Ngày bạn chọn đã được đặt!' });
}
})
}
exports.deleteBooking = function (req, res) {
const user = res.locals.user;
Booking
.findById(req.params.id)
.populate('user', '_id')
.exec(function (err, foundBooking) {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
if (user.id !== foundBooking.user.id) {
return res.status(403).send({ title: 'Invalid User!', detail: 'Bạn không có quyền xóa!' });
}
foundBooking.remove(function (err) {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
Booking
.where({ user })
.sort({createdAt: -1})
.populate('owner')
.populate('rental')
.exec(function (err, foundBookings) {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
return res.json(foundBookings);
});
});
});
}
exports.getUserBookings = function (req, res) {
const user = res.locals.user;
Booking
.where({ user })
.sort({createdAt: -1})
.populate('owner', 'image username _id')
.populate('rental')
.exec(function (err, foundBookings) {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
return res.json(foundBookings);
});
}
exports.getBookingsById = (req, res) => {
const user = res.locals.user;
const bookingId = req.params.id;
Booking
.findById(bookingId )
.populate('owner', 'image username _id')
.populate('rental')
.exec(function (err, foundBookings) {
if (err) {
console.log(err)
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
if (!foundBookings)
return res.status(422).send({title: 'Invalid Booking!', detail: 'Hóa đơn không tồn tại!' });
if (foundBookings) {
return res.json(foundBookings);
}
});
}
exports.getCustomerBookings = (req,res) => {
const user= res.locals.user;
Booking.find({'owner':user._id})
.populate('rental','_id title address ')
.populate('user','image username _id')
.exec((err, foundBookings) => {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
if (!foundBookings)
return res.status(422).send({title: 'Invalid Booking!', detail: 'Hóa đơn không tồn tại!' });
if (foundBookings) {
return res.json(foundBookings);
}
})
}
// exports.getOldBookings = (req, res) => {
// const user = res.locals.user;
// Booking
// .where({ user })
// .where(+moment(endAt) < +moment())
// .populate('rental')
// .exec(function (err, foundBookings) {
// if (err) {
// return res.status(422).send({ errors: normalizeErrors(err.errors) });
// }
// return res.json(foundBookings);
// });
// }
function isValidBooking(proposedBooking, rental) {
let isValid = true;
if (rental.bookings && rental.bookings.length > 0) {
isValid = rental.bookings.every(function (booking) {
const proposedStart = moment(proposedBooking.startAt);
const proposedEnd = moment(proposedBooking.endAt);
const actualStart = moment(booking.startAt);
const actualEnd = moment(booking.endAt);
return ((actualStart < proposedStart && actualEnd < proposedStart) || (proposedEnd < actualEnd && proposedEnd < actualStart));
});
}
return isValid;
}
function isValidUserBook(proposedBooking, user) {
let isValid = true;
if (user.bookings && user.bookings.length > 0) {
isValid = user.bookings.every(function (booking) {
const proposedStart = moment(proposedBooking.startAt);
const proposedEnd = moment(proposedBooking.endAt);
const actualStart = moment(booking.startAt);
const actualEnd = moment(booking.endAt);
return ((actualStart < proposedStart && actualEnd < proposedStart) || (proposedEnd < actualEnd && proposedEnd < actualStart));
});
}
return isValid;
}<file_sep>const express = require('express');
const router = express.Router();
const UserCtrl = require('../controllers/user');
const CommentCtrl = require('../controllers/comment');
router.post("/post", UserCtrl.authMiddleware, CommentCtrl.postComment)
router.post("/get", CommentCtrl.getComment);
router.delete("/:id", CommentCtrl.removeOneComment);
router.post('/createContact',CommentCtrl.createContact);
module.exports = router;
<file_sep>const express = require('express');
const router = express.Router();
const Rental = require('../models/rental');
const { normalizeErrors } = require('../helpers/mongoose');
const UserCtrl = require('../controllers/user');
const RentalCtrl = require('../controllers/rental')
router.get('/secret', UserCtrl.authMiddleware, function (req, res) {
res.json({ "secret": true });
});
router.get('/manage', UserCtrl.authMiddleware, RentalCtrl.getUserRentals);
router.get('/:id/verify-user', UserCtrl.authMiddleware, RentalCtrl.verifyUser);
router.get('/:id', UserCtrl.authOrNot, RentalCtrl.addSearchHistory);
router.get('/search/top', RentalCtrl.getTopRentals);
router.patch('/:id', UserCtrl.authMiddleware, function (req, res) {
const rentalData = req.body;
const user = res.locals.user;
Rental
.findById(req.params.id)
.populate('booking', 'startAt endAt')
.populate('user')
.exec(function (err, foundRental) {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
if (foundRental.user.id !== user.id) {
return res.status(422).send({ title: 'Invalid User!', detail: 'You are not rental owner!' });
}
foundRental.set(rentalData);
foundRental.save(function (err) {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
return res.status(200).send(foundRental);
});
});
});
router.delete('/:id', UserCtrl.authMiddleware, RentalCtrl.deleteRental);
router.post('/create', UserCtrl.authMiddleware, RentalCtrl.createRental)
router.get('', (req, res) => {
const city = req.query.city;
const query = city ? { city: city.toLowerCase() } : {};
Rental.find(query)
.where({ status: 'approved' })
.sort({ createdAt: -1 })
.populate('user', 'image _id username')
.select('-bookings')
.exec((err, foundRentals) => {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
if (city && foundRentals.length === 0) {
return res.status(422).send({ title: 'No Rentals Found!', detail: `There are no rentals for city ${city}` });
}
return res.json(foundRentals);
});
});
router.post('/update/:id', UserCtrl.authMiddleware, RentalCtrl.updateRental)
module.exports = router;
<file_sep>const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bookingSchema = new Schema({
startAt: { type: Date, required: 'Cần có ngày bắt đầu'},
endAt: { type: Date, required: 'Cần có ngày trả phòng'},
totalPrice: Number,
days: Number,
guests: Number,
owner: { type: Schema.Types.ObjectId, ref: 'User'},
user: { type: Schema.Types.ObjectId, ref: 'User'},
rental: { type: Schema.Types.ObjectId, ref: 'Rental'},
payment: { type: Schema.Types.ObjectId, ref: 'Payment'},
status: { type: String, default: 'pending'}
},{timestamps: {}});
module.exports = mongoose.model('Booking', bookingSchema );
<file_sep>const express = require('express');
const User = require('../controllers/user');
const router = express.Router();
router.post('/forgotpass', User.sendMailToken);
router.get('/info/:id', User.authMiddleware, User.getUser);
router.get('/confirm/:id', User.confirmation);
router.post('/login', User.auth);
router.post('/register', User.register);
router.post('/change',User.authMiddleware, User.changePass);
router.post('/avatar', User.authMiddleware, User.changeAvatar);
router.post('/oldAvatar', User.authMiddleware, User.oldAvatar)
router.post('/updateinfo', User.authMiddleware, User.updateInfo);
router.post('/reset/:token', User.resetPassword);
router.post('/addBookmark', User.authMiddleware,User.addBookmark);
router.post('/removeBookmark', User.authMiddleware,User.removeBookmark);
router.get('/getBookmark', User.authMiddleware, User.getBookmark);
module.exports = router;
<file_sep>const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const rentalSchema = new Schema({
title: { type: String, required: true, max: [128, 'Too long, max is 128 characters'] },
city: { type: String, required: true, lowercase: true },
address: { type: String, required: true, min: [4, 'Too short, min is 4 characters'] },
category: { type: String, required: true, lowercase: true },
image: [String],
bedrooms: { type: Number, required: true },
bathrooms: { type: Number, required: true },
people: { type: Number, default: 0},
// bedrooms: Number,
// shared: Boolean,
description: { type: String, required: true },
// dailyRate: Number,
price : { type: Number, required: true},
rating : { type:Number, default: 0},
isWifi: {type: Boolean, default: false},
isConditioner : { type: Boolean, default: false},
isTv : { type: Boolean, default: false},
isWashing: { type: Boolean, default: false},
isFridge: { type: Boolean, default: false},
isElevator : { type: Boolean, default: false},
user: { type: Schema.Types.ObjectId, ref: 'User' },
bookings: [{ type: Schema.Types.ObjectId, ref: 'Booking' }],
status: {type: String, default:'pending'}
},{timestamps: {}});
module.exports = mongoose.model('Rental', rentalSchema);
<file_sep>const express = require('express');
const router = express.Router();
const User = require('../controllers/user');
const BlogCtrl = require('../controllers/blog');
router.post('/post',User.authMiddleware, BlogCtrl.createBlog );
router.get('/get', BlogCtrl.getBlog);
router.post('/getBlogById', BlogCtrl.getBlogById)
module.exports = router;
<file_sep>const express = require('express');
const router = express.Router();
const AdminCtrl = require('../controllers/admin-user');
const BookingCtrl = require('../controllers/admin-booking');
const RentalCtrl = require('../controllers/admin-rental');
const BlogCtrl = require('../controllers/blog')
router.post('/login', AdminCtrl.auth );
router.get('/getUsers', AdminCtrl.isAdmin,AdminCtrl.getAllUser);
router.post('/deactivate', AdminCtrl.isAdmin,AdminCtrl.deactivateUser);
router.post('/activate', AdminCtrl.isAdmin, AdminCtrl.activateUser)
router.get('/getRentals', AdminCtrl.isAdmin,RentalCtrl.getRentals);
router.get('/getPendingRentals', AdminCtrl.isAdmin, RentalCtrl.getPendingRentals);
router.get('/getForbidRentals', AdminCtrl.isAdmin, RentalCtrl.getForbidRentals);
router.post('/approveRental', AdminCtrl.isAdmin, RentalCtrl.approveRental);
router.post('/forbidRental', AdminCtrl.isAdmin, RentalCtrl.forbidRental);
router.get('/getNumbers', AdminCtrl.isAdmin, AdminCtrl.getNumbers);
router.get('/getPendingBlogs', AdminCtrl.isAdmin, BlogCtrl.getPedingBlogs);
router.post('/approveBlog', AdminCtrl.isAdmin, BlogCtrl.approveBlog);
router.get('/getContact', AdminCtrl.isAdmin, AdminCtrl.getContact)
module.exports = router;
<file_sep>const User = require('../models/user');
const Rental = require('../models/rental');
const { normalizeErrors } = require('../helpers/mongoose');
const jwt = require('jsonwebtoken');
const config = require('../config/prod');
const async = require('async');
const crypto = require('crypto');
const nodemailer = require('nodemailer');
//16/03
const moment = require('moment')
exports.getUser = (req, res) => {
const requestedUserId = req.params.id;
const user = res.locals.user;
if (requestedUserId === user.id) {
User.findById(requestedUserId)
.select('-revenue -createdAt -password -resetPasswordToken -resetPasswordExpires')
.populate("searchHistory",'image title address _id')
.populate('bookmark','title address price rating _id image')
.exec((err, foundUser) => {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
return res.json(foundUser);
})
}
// else
// return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
exports.changeAvatar = (req, res) => {
const user = res.locals.user;
let { _id, email,image, oldImages } = user;
oldImages.unshift(image)
const {avatar} = req.body;
User.findOneAndUpdate({ email }, { oldImages, image: avatar }, { new: true })
.populate('bookmark','title address price rating _id image')
.exec((err, user) => {
if (err)
return res.status(422).send({ errors: normalizeErrors(err.errors) });
if(!user)
return res.status(401).send({detail:"Khong ton tai nguoi dung"})
if (user)
return res.status(200).json(user)
})
}
exports.oldAvatar = (req, res) => {
const user = res.locals.user;
let { oldImages, image, email } = res.locals.user;
oldImages.remove(req.body.src);
oldImages.push(user.image);
image = req.body.src
User.findOneAndUpdate({ email }, { oldImages, image }, { new: true })
.populate('bookmark','title address price rating _id image')
.exec((err, user) => {
if (err)
return res.status(422).send({ errors: normalizeErrors(err.errors) });
if (user)
return res.status(200).json(user)
})
}
exports.auth = (req, res) => {
const { email, password } = req.body;
if (!password || !email) {
return res.status(422).send({ title: 'Data missing!', detail: 'Provide email and password!' });
}
User.findOne({ email }, (err, user) => {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
if (!user) {
return res.status(404).send({ title: 'Người dùng không hợp lệ!', detail: 'Người dùng không tồn tại' });
}
if(!user.isVerified)
return res.status(401).send({ status: 'Error', detail: 'Tài khoản chưa xác thực' });
if(user.status === 'inactive')
return res.status(404).send({ title: 'Tài khoản bị vô hiệu!', detail: 'Tài khoản bạn đã bị vô hiệu' });
if (user.hasSamePassword(password)) {
const token = jwt.sign({
userId: user.id,
username: user.username,
email: user.email,
image: user.image,
role: user.role
}, config.SECRET, { expiresIn: '12h' });
return res.json(token);
} else {
return res.status(400).send({ title: 'Sai dữ liệu!', detail: 'Mật khẩu hoặc email không chính xác' });
}
});
}
exports.register = (req, res) => {
const url = req.get('origin')
const { username, email, password, passwordConfirmation } = req.body;
if (!password || !email) {
return res.status(400).send({ status: 'Error', detail: 'Điền đầy đủ thông tin!' });
}
if (password !== passwordConfirmation) {
return res.status(400).send({ status: 'Error', detail: 'Mật khẩu xác nhận không hợp lệ!' });
}
User.findOne({ email }, (err, existingUser) => {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
if (existingUser) {
return res.status(422).send({ status: 'Email không hợp lệ!', detail: 'Người dùng với email này đã tồn tại!' });
}
User.findOne({ username }, (err, foundUser) => {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
if (foundUser) {
return res.status(422).send({ status: 'Tên người dùng không hợp lệ!', detail: 'Người dùng với username này đã tồn tại!' });
}
const registerToken = crypto.randomBytes(20).toString('hex');
const user = new User({
username,
email,
password,
registerToken
});
user.save((err,user) => {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
var smtpTransport = nodemailer.createTransport(/*'SMTP',*/ {
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
type: 'OAuth2',
user: '<EMAIL>',
clientId: '1084231637210-5s064d297c3enbsfhshjdiq74pjdab7a.apps.googleusercontent.com',
clientSecret: 'N_UDvg3p_N3B8A2tO8eCinLa',
refreshToken: '<KEY>',
accessToken: '<KEY>'
}
});
var mailOptions = {
to: user.email,
from: '<EMAIL>',
subject: 'Account Verification Token',
text: 'Please verify your account by clicking the link:\n\n'
+url+"/confirm/" + registerToken + '\n\n'
};
smtpTransport.sendMail(mailOptions, (err) => {
if (err){
console.log(err)
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
return res.status(200).send({ result: { status: 'OK', detail:"Đăng ký thành công"}});
});
})
})
}
)
}
exports.changePass = (req, res) => {
const { _id, password, <PASSWORD> } = req.body;
User.findOne({ _id }, (err, user) => {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
if (!user) {
return res.status(422).send({ detail: 'Người dùng không tồn tại' });
}
if (user.hasSamePassword(password)) {
user.password = <PASSWORD>;
user.save((err) => {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
return res.json({ 'changed': true });
})
}
else {
return res.status(422).send({ detail: 'Sai mật khẩu' });
}
})
}
exports.resetPassword = (req, res) => {
async.waterfall([
(done) => {
User.findOne({ resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, (err, user) => {
if (!user) {
return res.status(401).send({ detail: 'Token reset mật khẩu không hợp lệ hoặc hết hiệu lực' })
}
if (user) {
if (req.body.newPassword !== req.body.newPasswordConfirmation) {
return res.status(422).send({ detail: 'Mật khẩu xác nhận không hợp lệ!'});
}
user.password = <PASSWORD>;
user.resetPasswordToken = <PASSWORD>;
user.resetPasswordExpires = undefined;
}
user.save((err) => {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
return res.json({ 'reset': true });
});
});
},], (err) => {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
});
}
exports.sendMailToken = (req, res, next) => {
const url = req.get('origin')
async.waterfall([
(done) => {
crypto.randomBytes(20, (err, buf) => {
var token = buf.toString('hex');
done(err, token);
});
},
(token, done) => {
User.findOne({ email: req.body.email }, (err, user) => {
if (!user) {
return res.status(422).send({ title: 'Người dùng không hợp lệ!', detail: 'Người dùng không tồn tại'});
}
if(user.resetPasswordExpires!=undefined && user.resetPasswordExpires > Date.now())
return res.status(403).send({detail:'Đã có email gửi tới bạn. Xin hãy kiểm tra lại.'})
user.resetPasswordToken = <PASSWORD>;
user.resetPasswordExpires = Date.now() + 3600000; // 1 hour
user.save((err) => {
done(err, token, user);
});
});
},
(token, user, done) => {
var smtpTransport = nodemailer.createTransport(/*'SMTP',*/ {
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
type: 'OAuth2',
user: '<EMAIL>',
clientId: '1084231637210-5s064d297c3enbsfhshjdiq74pjdab7a.apps.googleusercontent.com',
clientSecret: 'N_UDvg3p_N3B8A2tO8eCinLa',
refreshToken: '<KEY>',
accessToken: '<KEY>'
}
});
var mailOptions = {
to: user.email,
from: '<EMAIL>',
subject: 'UIT Booking Password Reset',
text: 'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n' +
'Please click on the following link, or paste this into your browser to complete the process:\n\n'
+url+'/reset/' + token + '\n\n' +
'If you did not request this, please ignore this email and your password will remain unchanged.\n'
};
smtpTransport.sendMail(mailOptions, (err) => {
// req.flash('info', 'An e-mail has been sent to ' + user.email + ' with further instructions.');
res.json({ 'sendSuccess': true });
done(err, 'done');
});
}
], (err) => {
if (err) return next(err);
return res.status(422).send({ errors: normalizeErrors(err.errors) });
});
}
exports.authMiddleware = (req, res, next) => {
const token = req.headers.authorization;
if (token) {
const user = parseToken(token);
User.findById(user.userId)
.populate('bookmark','title address price rating _id image')
.exec((err, user) => {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
if (user) {
res.locals.user = user;
next();
} else {
return notAuthorized(res);
}
})
} else {
return notAuthorized(res);
}
}
exports.authOrNot = (req, res, next) => {
const token = req.headers.authorization;
if (token) {
const user = parseToken(token);
User.findById(user.userId, (err, user) => {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
if (user) {
res.locals.user = user;
next();
}
})
}
else next()
}
function parseToken(token) {
return jwt.verify(token.split(' ')[1], config.SECRET);
}
function notAuthorized(res) {
return res.status(401).send({ title: 'Không được chứng thực!', detail: 'Bạn cần phải đăng nhập!'});
}
exports.updateInfo = (req, res) => {
const data = req.body
const user = res.locals.user;
const _id = user.id;
User.findOne({ _id }, (err, user) => {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
if (!user) {
return res.status(422).send({detail: 'Người dùng không tồn tại'});
}
User.findOneAndUpdate({ _id }, data,{new: true}, (err, user) => {
if (err)
return res.status(422).send({ errors: normalizeErrors(err.errors) });
if (user)
{
return res.json(user)
}
}) // returns Query
})
}
exports.confirmation = (req,res) =>{
User.findOneAndUpdate({ registerToken: req.params.id }, {isVerified: true, registerToken: undefined}, { new: true }, (err, user)=>{
if(err)
return res.status(422).send({ errors: normalizeErrors(err.errors) });
if(!user)
return res.status(404).send({ detail: 'Token không hợp lệ hoặc tài khoản đã được xác nhận' });
return res.status(200).send({status:"OK",detail:"Đã xác nhận tài khoản thành công"})
})
}
exports.addBookmark = (req,res) => {
const rentalId = req.body.rentalId;
const user= res.locals.user;
Rental.findById(rentalId)
.exec(function (err, foundRental) {
if (err || !foundRental) {
return res.status(422).send({ detail: 'Could not find Rental!' });
}
if(user){
const bookmark = user.bookmark;
if(rentalId)
bookmark.unshift(rentalId)
User.findByIdAndUpdate(user._id,{bookmark:bookmark},{new:true})
.populate('bookmark','title address price rating _id image')
.exec((err,foundUser)=>{
console.log(foundUser.bookmark[0])
if(err)
return res.status(422).send({ errors: normalizeErrors(err.errors) });
if(foundUser)
return res.status(200).json({"bookmark": foundUser.bookmark}); })
}});
}
exports.removeBookmark = (req,res) => {
const rentalId = req.body.rentalId;
const user= res.locals.user;
Rental.findById(rentalId)
.exec(function (err, foundRental) {
if (err || !foundRental) {
return res.status(422).send({ detail: 'Could not find Rental!' });
}
if(user){
const bookmark = user.bookmark;
if(rentalId)
bookmark.remove(rentalId)
user.bookmark = bookmark;
user.save((err) => {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}})
return res.status(200).json({"bookmark": user.bookmark});
}});
}
exports.getBookmark = (req, res) => {
const userId = res.locals.user;
User.findById(userId)
.sort({createdAt: -1})
.populate('bookmark','title address price rating _id image')
.exec((err,user) => {
if(err)
return res.status(422).send({ errors: normalizeErrors(err.errors) });
if(user){
return res.status(200).json({"bookmark": user.bookmark})}
if(!user)
return res.status(404).json({detail:"Không tìm thấy"})
})
}
// exports.addSearchHistory = (req, res) => {
// const key = req.body.key
// const user = res.locals.user; const _id = user.id
// const searchHistory = user.searchHistory;
// for (var i = 0; i < searchHistory.length; i++) {
// if (searchHistory[i] === key) {
// searchHistory.splice(i, 1);
// }
// }
// if(key!=null)
// searchHistory.unshift(key)
// User.findByIdAndUpdate({_id}, {searchHistory},{ new: true }, (err,user)=>{
// if(err)
// return res.status(422).send({ errors: normalizeErrors(err.errors) });
// if(!user)
// return res.status(422).send({ errors:{ title: 'Người dùng không hợp lệ!', detail: 'Người dùng không tồn tại' }});
// })
// }
<file_sep>const bcrypt = require('bcryptjs');
const mongoose = require('mongoose');
const Schema = mongoose.Schema
const userSchema = new Schema({
username: {
type: String,
min: [4, 'Yêu cầu nhập nhiều hơn 4 ký tự'],
max: [32, 'Yêu cầu tối đa 32 ký tự']
},
email: {
type: String,
min: [4, 'Yêu cầu nhập nhiều hơn 4 ký tự'],
max: [32, 'Yêu cầu tối đa 32 ký tự'],
unique: true,
lowercase: true,
required: 'Yêu cầu email',
match: [/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/]
},
password: {
type: String,
min: [4, 'Yêu cầu nhập nhiều hơn 4 ký tự'],
max: [32, 'Yêu cầu tối đa 32 ký tự'],
required: 'Yêu cầu mật khẩu'
},
phone: {
type: String,
default: ''
// min: [9, 'Yêu cầu ít nhất 9 số' ],
// max: [10, 'Yêu cầu tối đa 10 số'],
// required: true
},
fullname : {
type: String,
default: ''
},
dateOfBirth: {
type: Date,
default: Date.now
// required: true
},
gender : {type: String, default: undefined},
address: {type: String, default:''},
description: {type: String, default:''},
createdAt: { type: Date, default: Date.now },
resetPasswordToken: { type: String, default:undefined},
resetPasswordExpires: { type: String, default:undefined},
image: { type: String, default: 'https://res.cloudinary.com/hsuit/image/upload/q_auto:low/v1553620808/default.png'},
oldImages : [{type:String}],
revenue: Number,
rentals: [{type: Schema.Types.ObjectId, ref: 'Rental'}],
bookings: [{ type: Schema.Types.ObjectId, ref: 'Booking' }],
message: {type: String, default:''},
identityCard: {type: String, default:''},
isVerified: { type: Boolean, default: false },
registerToken : {type: String, default: undefined},
searchHistory: [{type: Schema.Types.ObjectId, ref: 'Rental'}],
role: {type: String, default: 'user'},
status: {type: String, default: 'active'},
bookmark: [{type: Schema.Types.ObjectId, ref: 'Rental'}]
},{timestamps: {}});
userSchema.methods.hasSamePassword = function(requestedPassword) {
return bcrypt.compareSync(requestedPassword, this.password);
}
userSchema.pre('save', function(next) {
const user = this;
if(user.password.length < 15)
{
bcrypt.genSalt(10, async function(err, salt) {
await bcrypt.hash(user.password, salt)
.then(hash => {
user.password = <PASSWORD>;
next();
});
});
}
else next();
});
module.exports = mongoose.model('User', userSchema );
<file_sep>const Payment = require('../models/payment');
const Booking = require('../models/booking');
const mongoose = require('mongoose')
const ObjectId = mongoose.Types.ObjectId;
const Rental = require('../models/rental');
const User = require('../models/user');
const Comment = require('../models/comment');
const Contact = require('../models/contact');
const _ = require('lodash')
const { normalizeErrors } = require('../helpers/mongoose');
exports.postComment = (req,res) => {
const user = res.locals.user._id;
const rental = req.body.rentalId;
const comment = req.body.comment;
const rating = req.body.rating;
const cmt = new Comment ({user,rental,comment,rating});
Comment.find({rental:rental, user:user},(err,cmts)=>{
if(err)
return res.status(422).send({ errors: normalizeErrors(err.errors) });
if(cmts.length > 0){
return res.status(403).send({ detail: 'Bạn không thể đánh giá nữa' } );
}
if(cmts.length === 0)
{
Comment.create(cmt, (err, cmt) => {
if(err)
return res.status(422).send({ errors: normalizeErrors(err.errors) });
if(cmt)
{
Comment
.aggregate([{$match: {rental:ObjectId(rental)}},
{
$group: {_id: rental,avgRating: {$avg: "$rating"}}
}
])
.exec((err,result) =>
Rental.findByIdAndUpdate({_id:rental},{rating:result[0].avgRating},{new:true},(err,rental)=>{
if(err) throw err;
})
);
Comment.findById(cmt._id)
.populate('user','username image _id')
.exec((err,foundCmt) =>{
return res.status(200).json(foundCmt);
})
}
})
}
})
}
exports.getComment = (req,res) =>{
const limit = req.body.limit;
const page = req.body.page;
const rentalId = req.body.rentalId;
Rental.findById(rentalId)
.exec((err, rental) =>{
// if(err)
// return res.status(422).send({ errors: normalizeErrors(err.errors) });
if(err | !rental)
return res.status(404).send({detail:"Không tồn tại nơi này"})
Comment.find({rental:rentalId})
.sort('-createdAt')
.populate('user','username image _id')
.skip(limit*(page - 1))
.limit(limit)
.exec((err, comment)=>{
if(err)
return res.status(422).send({ errors: normalizeErrors(err.errors) });
if(comment)
return res.status(200).json(comment);
})
})
}
exports.removeOneComment = (req, res) =>{
const user = res.locals.user;
const cmtId = req.params.id;
Comment.findById(cmtId)
.exec((err, cmt) => {
if(err || ! cmt)
return res.status(404).send({detail:"Không tồn tại đánh giá"})
if(cmt)
{
cmt.remove(err =>{
if(err)
return res.status(422).send({ errors: normalizeErrors(err.errors) });
})
return res.status(200).send({detail:'Xóa đánh giá thành công'})
}
})
}
exports.createContact = (req, res) => {
const { name, email, message} = req.body;
const contact = new Contact({name, email, message})
Contact.create(contact, (err,ctc) => {
if(err ||!ctc)
return res.status(422).send({ errors: normalizeErrors(err.errors) });
if(ctc)
return res.status(200).send({detail:'Cảm ơn sự góp ý của bạn!'})
})
}<file_sep>const Payment = require('../models/payment');
const Booking = require('../models/booking');
const Rental = require('../models/rental');
const User = require('../models/user');
const { normalizeErrors } = require('../helpers/mongoose');
exports.getPendingPayments = function (req, res) {
const user = res.locals.user;
Payment
.where({ toUser: user })
.populate({
path: 'booking',
populate: { path: 'rental' }
})
.populate('fromUser')
.exec(function (err, foundPayments) {
if (err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
return res.json(foundPayments);
})
}
exports.createPayment = (req, res) => {
const user = res.locals.user;
const { toUser, booking, totalPrice, payerID, paymentID, paymentToken } = req.body;
const fromUser = user._id;
Booking.findByIdAndUpdate({ _id: booking }, { status: 'paid' })
.populate('rental')
.populate('owner','_id image username message')
.exec((err, foundBooking) => {
if (err)
return res.status(422).send({ errors: normalizeErrors(err.errors) });
if (!foundBooking)
return res.status(403).send({ title: 'Không tìm thấy', detail: 'Đặt phòng không tồn tại!'});
if (foundBooking) {
const payment = new Payment({ fromUser, toUser, booking, totalPrice, payerID, paymentID, paymentToken })
Payment.create(payment, (err, newPayment) => {
if (err)
return res.status(422).send({ errors: normalizeErrors(err.errors) });
if (newPayment)
{
foundBooking.payment = newPayment._id;
foundBooking.status = "Paid";
foundBooking.save(err => {
if(err)
return res.status(422).send({ errors: normalizeErrors(err.errors) });
return res.status(200).json(foundBooking);
})
}
// Booking.find({ user: fromUser }, (err, foundBooking) => {
// if (err)
// return res.status(422).send({ errors: normalizeErrors(err.errors) });
// if(foundBooking)
// return res.json(foundBooking);
// })
})
}
})
}
<file_sep>const Payment = require('../models/payment');
const Booking = require('../models/booking');
const mongoose = require('mongoose')
const ObjectId = mongoose.Types.ObjectId;
const Rental = require('../models/rental');
const User = require('../models/user');
const Blog = require('../models/blog')
const _ = require('lodash')
const { normalizeErrors } = require('../helpers/mongoose');
exports.createBlog = (req,res) => {
const author = res.locals.user._id;
const {title, content, image} = req.body;
const blog = new Blog({ title, content, image, author});
blog.save((err) => {
if(err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}})
return res.status(200).json({detail:"Xin hãy đợi kiểm duyệt"})
}
exports.getBlog = (req,res) => {
Blog.find({status:"approved"})
.sort({createdAt: -1})
.populate('author','image username _id')
.exec((err, blogs) => {
if(err) {
return res.status(422).send({ errors: normalizeErrors(err.errors) });
}
return res.status(200).json(blogs)
})
}
exports.getBlogById = (req, res) => {
const blogId = req.body.blogId;
Blog.findByIdAndUpdate(blogId,{ $inc: { viewCount: 1 }})
.populate('author','image username _id')
.exec((err,blog) => {
if(err)
return res.status(422).send({ errors: normalizeErrors(err.errors) });
if(blog){
return res.status(200).json(blog)
}
if(!blog)
return res.status(404).json({detail: "Không tìm thấy bài blog"})
})
}
exports.getPedingBlogs = (req,res) => {
Blog.find({status:'pending'})
.sort({createdAt: -1})
.populate('author','image _id user')
.exec((err,blog) => {
if(err)
return res.status(422).send({ errors: normalizeErrors(err.errors) });
if(blog)
return res.status(200).json(blog)
if(!blog)
return res.status(404).json({detail: "Không tìm thấy bài blog"})
})
}
exports.approveBlog = (req, res) => {
const blog = req.body.blogId;
Blog.findByIdAndUpdate(blog,{'status':'approved'},{new: true},(err,blogs)=>{
if(err)
return res.status(422).send({ errors: normalizeErrors(err.errors) });
if(blogs){
Blog.find({ $or:[ {'status':undefined}, {'status':'pending'}]})
.sort({createdAt: -1})
.populate('author','image username _id')
.exec((err,rentals)=>{
if(err)
return res.status(422).send({ errors: normalizeErrors(err.errors) });
if(rentals)
return res.status(200).json(rentals)
})
}
if(!blog)
return res.status(401).send({detail: `Không tồn tại hoặc đã được duyệt` });
})
}
| 9111b6f9c282b510d576fc1e4f51c305850bb5d2 | [
"JavaScript"
] | 14 | JavaScript | HieuNguyen15520228/hsbookingback | b3d0503ae76598341a7e34a65ce906bb3b067af2 | a768369255c09224557f6a38704edd5eda00c5ce |
refs/heads/master | <file_sep>document.addEventListener("DOMContentLoaded", () => {
let button = document.querySelector('#button');
button.addEventListener('click', getRandomJoke);
})
const getRandomJoke = () => {
fetch("https://official-joke-api.appspot.com/random_joke")
.then(response => {
return response.json();
})
.then(dataObj => {
renderJoke(dataObj.setup)
renderAnswer(dataObj.punchline)
})
.catch(err => {
console.log("Not found", err)
})
renderJoke = (joke) => {
let prevJoke = document.querySelector('p')
if (!prevJoke) {
let tellJoke = document.createElement(tellJoke);
tellJoke.innerHTML = joke
document.body.appendChild(tellJoke);
} else {
let newJoke = document.createElement('p')
newJoke.innerHTML = joke
prevJoke.parentNode.replaceChild(newJoke, prevJoke)
}
}
renderAnswer = (answer) => {
// let answer = document.createElement("button");
// answer.id = "answer";
// answer.innerText = "Punchline";
// document.body.appendChild(answer);
// document.addEventListener
let jokeAnswer = document.createElement('p');
jokeAnswer.innerText = answer;
document.body.appendChild(jokeAnswer)
}
// createAnswer = () => {
// let answer = document.createElement("button");
// answer.id = "answer";
// answer.innerText = "Punchline";
// document.body.appendChild(answer);
// }
// createAnswer()
}
| 2b5f3665ca3abf8e5d3c65a8e6dd3062f844d0f6 | [
"JavaScript"
] | 1 | JavaScript | hupaulcamacho/Pursuit-Core-Web-Promises-Fetch-Lab | dba668d30c8de2d2b17d49cd2e14699c8c428f8e | 1620d3ae42ad0392c1976000432e4efa8c1c1e8d |
refs/heads/master | <repo_name>Shubhamchinda/AttendanceRecord<file_sep>/app/controllers/_utils.js
import moment from "moment";
export const isLoggedIn = (req, res, next) => {
if (req.isAuthenticated()) {
return next();
}
res.redirect("/");
};
export const setDateTime = (date, time) => {
let dateNtime = moment(date, "DD-MM-YYYY");
console.log(time);
let splitTime = time.split(":");
let hrs = dateNtime.add("hours", splitTime[0]);
let mins = dateNtime.add("minute", splitTime[1]);
let sec = dateNtime.add("second", splitTime[2]);
return dateNtime;
};
export default {};
<file_sep>/app/models/AllTickets.js
import mongoose, { Schema } from "mongoose";
class AllTicketsSchema extends Schema {
constructor() {
const user = super(
{
ticketId: { type: String, unique: true },
status: { type: String },
CustId: { type: String },
EmpId: { type: String },
title: String,
category: String,
opendOn: Date,
updatedOn: Date,
priority: String,
reason: String,
assignDate: Date,
timeToComplete: Date
},
{ timestamps: { createdAt: "created_at" } }
);
return user;
}
}
export default mongoose.model("AllTickets", new AllTicketsSchema()); // eslint-disable-line
<file_sep>/app.js
// server.js
// set up ======================================================================
import express from "express";
import mongoose from "mongoose";
import passport from "passport";
import flash from "connect-flash";
import morgan from "morgan";
import cookieParser from "cookie-parser";
import bodyParser from "body-parser";
import session from "express-session";
import compression from "compression";
import path from "path";
import expressLayouts from "express-ejs-layouts";
import cors from "cors";
import swaggerUi from "swagger-ui-express";
import YAML from "yamljs";
import configDB from "./config/database";
import passportConfig from "./config/passport";
// routes ======================================================================
import routes from "./app/routes";
// import authRoutes from "./app/authRoutes";
import getAttendance from "./app/controllers/getAttendance";
import newEmp from "./app/controllers/newEmp";
const app = express();
const swaggerDocument = YAML.load("./swagger.yaml");
// configuration ===============================================================
mongoose.connect(configDB.url); // connect to our database
passportConfig(passport); // pass passport for configuration
const rejectFolders = [
"css",
"bower_components",
"js",
"img",
"fonts",
"images"
];
// removing static resources from the logger
app.use(
morgan(":method :url :status :res[content-length] - :response-time ms", {
skip: req => rejectFolders.indexOf(req.url.split("/")[1]) !== -1
})
);
app.use(compression({ threshold: 0 }));
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
app.set("view engine", "ejs");
app.use(expressLayouts);
app.set("layout extractScripts", true);
app.set("layout extractStyles", true);
app.set("layout", "layouts/main");
app.use(express.static(path.join(__dirname, "public")));
// required for passport
app.use(
session({
secret: process.env.SECRET_KEY || "<KEY>", // session secret
resave: true,
saveUninitialized: true
})
);
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDocument));
routes(app, passport); // load our routes and pass in our app and fully configured passport
// app.use("/", authRoutes);
// app.use("/", newRoutes);
// app.use((req, res, next) => {
// const err = new Error("Not Found");
// console.log(res);
// err.status = 404;
// next(err);
// });
mongoose.set("debug", true);
module.exports = app;
<file_sep>/config/settings.js
export const websiteUrl = 'https://medmetrxmerlin-n.newparadigmbd.com'
export const websiteTitle = 'HTAMPS'
export const errorObj = {error: true, type: 'error', success: false}
export const successObj = {error: false, type: 'success', success: true}
export const secret = process.env.SECRET_KEY
export default {
websiteUrl,
}
<file_sep>/app/models/newEmployee.js
import mongoose, { Schema } from "mongoose";
class AddEmployee extends Schema {
constructor() {
const user = super(
{
employeeId: { type: Number },
name: String,
contactnumber: { type: Number, unique: true }
},
{ timestamps: { createdAt: "created_at" } }
);
return user;
}
}
export default mongoose.model("NewEmp", new AddEmployee()); // eslint-disable-line
<file_sep>/app/models/CustomerModel.js
import mongoose, { Schema } from "mongoose";
class CustomerSchema extends Schema {
constructor() {
const user = super(
{
CustomerId: { type: Number },
CustEmail: { type: String, unique: true },
CustContactNum: { type: Number, unique: true },
Address: String
},
{ timestamps: { createdAt: "created_at" } }
);
return user;
}
}
export default mongoose.model("Customer", new CustomerSchema()); // eslint-disable-line
<file_sep>/app/controllers/newEmp.js
import express from "express";
import request from "request";
import Async from "async";
import EmpController from "./../models/newEmployee";
import { secret, errorObj, successObj } from "../../config/settings";
import newEmployee from "../models/newEmployee";
const console = require("tracer").colorConsole();
const app = express.Router();
const empCtrl = {
msgg: "hello",
addEmp: data => {
return new Promise(resolve => {
let newUser = new EmpController({
employeeId: data.employeeId,
name: data.name,
contactnumber: data.contact
});
newUser.save(function(err) {
if (err) {
console.log(err);
}
});
});
},
listEmp: () => {
newEmployee.find({}).exec(function(err, users) {
if (err) throw err;
console.log(users);
});
}
};
// empCtrl.addEmp({
// employeeId: 4,
// name: "shubham",
// contact: 1232067891
// });
// empCtrl.listEmp();
export default app;
<file_sep>/app/controllers/getAttendance.js
import express from "express";
import request from "request";
import _ from "lodash";
import mongoose from "mongoose";
import ordinal from "ordinal";
import pluralize from "pluralize";
import capitalize from "capitalize";
import Async from "async";
import AttendanceController from "../models/attendances";
import EmpCtrl from "../models/newEmployee";
import { secret, errorObj, successObj } from "../../config/settings";
import { setDateTime } from "./_utils";
import MachineConfig from "./../../config/machineConfig.json";
import newEmployee from "../models/newEmployee";
const console = require("tracer").colorConsole();
var moment = require("moment");
var schedule = require("node-schedule");
const app = express.Router();
const emp = {
msgg: "hello",
add: (user, machineId) => {
return new Promise(resolve => {
let dateNtime = setDateTime(user.date, user.time);
console.log("add");
AttendanceController.findOne(
{ employeeId: user.employeeId },
async function(err, result) {
if (result) {
console.log("user already exists");
if (user.type == "OUT") {
console.log("OUt");
result.outTime = dateNtime;
return result.save(function(err) {
if (err) {
console.log(err);
}
});
}
} else if (user.type == "IN") {
console.log("New User");
let newUser = new AttendanceController({
employeeId: user.employeeId,
inTime: dateNtime,
date: new Date(),
machineId: machineId
});
newUser.save(function(err) {
if (err) {
console.log(err);
}
});
}
}
);
});
},
getRequest: ({ url, machineId = 1 }) => {
return new Promise(resolve => {
request(url, async (error, response, body) => {
if (error) {
resolve({ ...errorObject });
}
let recordBody = await emp.bodyToJson(body);
Async.each(recordBody, async value => {
console.log("yess");
let addUser = await emp.add(value, machineId);
});
resolve({ recordBody, ...successObj });
});
});
},
getAttendance: machineId => {
return new Promise(resolve => {
console.log("IN getAttendance");
let today = new Date();
const startDate = moment(today)
.startOf("day")
.toDate();
const endDate = moment(today)
.endOf("day")
.toDate();
let query = AttendanceController.find();
query.where({ machineId });
// query.where({ inTime: { $lte: endDate } });
query.exec((err, docs) => {
if (err) {
return resolve({ ...errorObj });
}
resolve({ ...successObj, docs });
});
});
},
getReport: async machine => {
const { machineId } = machine;
const { error, docs } = await emp.getAttendance(machineId);
let { openingTime } = machine;
let temp = openingTime.split(":");
openingTime = moment()
.startOf("day")
.add(temp[0], "hour")
.add(temp[1], "minute")
.add(temp[2], "second");
console.log(openingTime);
let late = [];
let onTime = [];
let msg = ``;
Async.each(
docs,
(value, done) => {
let isLate = moment(value.inTime).isAfter(openingTime);
console.log(isLate, value.inTime);
if (isLate) {
console.log(value.employeeId);
const minutes = moment(value.inTime).diff(
moment(openingTime),
"minute"
);
value.minutes = minutes;
late.push(value);
} else {
onTime.push(value);
}
done();
},
() => {
msg = `${docs.length} are present out of ${
newEmployee.length
} of ${ordinal(machineId)} machine.\n`;
msg += `${onTime.length} out of ${docs.length} are on time.\n`;
Async.each(
late,
async (item, done) => {
let { name } = await emp.getEmpName(item.employeeId);
msg += `${capitalize(name)} was ${item.minutes} ${pluralize(
"minute"
)} late.\n`;
done();
},
() => {
console.log(msg);
}
);
}
);
},
bodyToJson: data => {
data = data.replace('"', "");
data = data.replace('"', "");
data = data.split("\\r\\n");
data = data.map(item => {
let newItem = item.split(",");
return {
employeeId: newItem[0],
date: newItem[1],
time: newItem[2],
type: newItem[3]
};
});
return _.filter(data, x => !!x.employeeId);
},
getEmpName: id => {
return new Promise(resolve => {
let query = EmpCtrl.findOne({ employeeId: id });
query.exec((err, data) => {
if (err) {
return resolve({ ...errorObj, err, message: "User not added yet" });
}
resolve({ ...successObj, name: data.name });
});
});
}
};
// schedule.scheduleJob("*/20 * * * * *", function() {
// Async.each(MachineConfig, machine => {
// console.log(machine.url, machine.machineId);
// emp.getRequest({
// url: machine.url,
// machineId: machine.machineId
// });
// });
// });
// console.log("hello");
// });
// schedule.scheduleJob("30 15 * * *", function() {
// console.log(MachineConfig[0].url);
// emp.getReport(MachineConfig[0]);
// });
// emp.getReport(MachineConfig[0]);
export default app;
| f26c2260b01ca4198c77c68ad6633ae4dcc85f1e | [
"JavaScript"
] | 8 | JavaScript | Shubhamchinda/AttendanceRecord | 29beb8b43b609bad870b539c8d1049c9a0f053f9 | 3deb77ddc8595ce1ef7706e1985b11a8a9bb47b8 |
refs/heads/master | <repo_name>pocketu/pocket<file_sep>/protected/views/app/jobs.php
<header id="top" >
<a id = "back" href="javascript:history.go(-1);">返回</a>
<div id = "title" class = "span1" >招聘信息轴</div>
<a id = "home" href="<?php echo Yii::app()->request->baseUrl; ?>">首页</a>
</header>
<div class = "flexbox" style="margin:0 10px 10px;" >
<div class="sort span1 flexbox" >
<a class="span1">按发布时间</a>
<a class="span1">按招聘时间</a>
</div>
<div class="search flexbox" >
<p class="span1" ><input type="text" /></p>
<a class="icon-search"></a>
</div>
</div>
<ul class = "form-list" >
<li class = "rarr" >
<span>期限</span>
<span class = "form-list-val j_s_val">未过期</span>
<select class = "j_sel" data-key = "qixian" >
<option value="2" selected >未过期</option>
<option value="1">已过期</option>
<option value="0">全部</option>
</select>
</li>
<li class = "rarr" >
<span>类型</span>
<span class = "form-list-val j_s_val">本校</span>
<select class = "j_sel" data-key = "type" >
<option value="1" selected >本校招聘</option>
<option value="2">外校招聘</option>
<option value="3">社会招聘</option>
<option value="0">全部</option>
</select>
</li>
<li class = "rarr" >
<span>行业</span>
<span class = "form-list-val j_s_val">全部</span>
<select class = "j_sel" data-key = "hangye" >
<option value="0" selected>全部</option>
<option value="1">计算机/互联网/通讯/电子</option>
<option value="2">会计/金融/银行/保险</option>
<option value="3">贸易/消费/制造/营运</option>
<option value="4">制药/医疗</option>
<option value="5">广告/媒体</option>
<option value="6">房地产/建筑</option>
<option value="7">专业服务/教育/培训</option>
<option value="8">服务业</option>
<option value="9">物流/运输</option>
<option value="10">能源/原材料</option>
<option value="11">政府/非盈利机构</option>
<option value="12">其他行业</option>
</select>
</li>
<li><a class = "form-btn" >立即筛选</a></li>
</ul>
<section id = "chain" >
<div class="chain-nodes ">
<h2>本周发布<i class="alarm"></i></h2>
<ul>
<li>
<a href = "{$createUrl(app/jobs_p)}">中国石油化工有限公司招聘</a>
<span>10/16</span>
</li>
<li>
<a href = "#">中国石油化工有限公司招聘</a>
<span>10/14</span>
</li>
<li>
<a href = "#">东营联合石化有限责任公司招聘化工、储运、电气、仪表等专业毕业生</a>
<span>10/15</span>
</li>
</ul>
</div>
<div class="chain-nodes ">
<h2>上周发布<i class="alarm"></i></h2>
<ul>
<li>
<a href="#">中国石油化工有限公司招聘</a>
<span>10/10</span>
</li>
<li>
<a href="#">中国石油化工有限公司招聘</a>
<span>10/09</span>
</li>
<li>
<a href="#">中国石油化工有限公司招聘</a>
<span>10/07</span>
</li>
</ul>
</div>
<div class="chain-nodes " style="position:absolute;width:100%;">
<h2>更早<i class="alarm"></i></h2>
<ul>
<li>
<a href="#">中国石油化工有限公司招聘</a>
<span>09/30</span>
</li>
<li>
<a href="#">中国石油化工有限公司招聘</a>
<span>09/30</span>
</li>
<li>
<a href="#">中国石油化工有限公司招聘</a>
<span>09/30</span>
</li>
</ul>
</div>
</section>
<script>
//var div = document.getElementsByTagName("ul");
var div = document.querySelector(".chain-nodes:last-child ul");
window.onscroll = function (){
var d = window.innerHeight;
var h = document.body.scrollHeight;
var t = document.body.scrollTop;
var li = div.getElementsByTagName("li")[0].cloneNode(true);
if( (h-d) == t ){
div.appendChild(li);
$.ajax({
url : "<?php echo Yii::app()->request->baseUrl; ?>/test/web.php?para=说话",
type : "post",
dataType : "json",
data : {
a : "saddsa",
b : 1,
c : [ 1, "haha"],
d : function(){
alert(777);
}
}
});
}else{
console.log(d+"--"+h+"--"+t);
}
}
function Jlist (){
}
Jlist.prototype = {
init : function(){
this.deal();
this.change();
},
// 绑定提交事件
deal : function(){
var ul = document.getElementsByClassName("form-list"),
len = ul.length;
for( var i = 0; i < len; i++ ){
var btn = ul[i].getElementsByClassName("form-btn");
btn[0].onclick = function(){
var sel = this.parentNode.parentNode.getElementsByClassName("j_sel"),
val = [];
for( var i = 0; i < sel.length; i++ ){
val.push( sel[i].getAttribute( "data-key" ) +"="+sel[i].value );
}
console.log( val.join("&") +"---"+ window.location.href);
window.location.href += "?"+val.join("&");
};
}
btn = null;
},
// 选项更改事件
change : function(){
var sel = document.getElementsByClassName("j_sel"),
span = document.getElementsByClassName("j_s_val");
if( sel.length == span.length ){
for ( var i = 0; i < sel.length; i++){
(function(j){
sel[j].onchange = function(){
span[j].innerText = this.options[this.selectedIndex].text;
}
})(i);
}
} else {
console.log("错误;select和span数目不一致!!");
}
}
}
var mylist = new Jlist();
mylist.init();
</script><file_sep>/protected/controllers/app/BuspAction.php
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of GameAction
*
* @author Administrator
*/
class BuspAction extends StageAction{
//put your code here
public function run() {
// var_dump($this->tags);
$model = Bus::model()->findbyPk($_GET['id']);
$this->controller->render("bus_p", array(
'model' => $model,
));
}
}
?>
<file_sep>/protected/models/Tshops.php
<?php
/**
* This is the model class for table "{{tshops}}".
*
* The followings are the available columns in table '{{tshops}}':
* @property integer $id
* @property string $name
* @property string $short
* @property string $slogan
* @property string $meal_time
* @property string $speed
* @property string $brief
* @property string $remark
* @property string $tels
* @property string $ps
* @property integer $count
* @property integer $grade
*/
class Tshops extends NActiveRecord
{
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return Tshops the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return '{{tshops}}';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('name, short, slogan, meal_time, speed, brief, tels, count, grade', 'required'),
array('count, grade', 'numerical', 'integerOnly'=>true),
array('name, meal_time', 'length', 'max'=>40),
array('short, speed', 'length', 'max'=>20),
array('slogan', 'length', 'max'=>80),
array('remark, tels, ps', 'length', 'max'=>100),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, name, short, slogan, meal_time, speed, brief, remark, tels, ps, count, grade', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
public function fieldType(){
return array(
'id' => 'ID',
'name' => 'varchar',
'short' => 'varchar',
'slogan' => 'varchar',
'meal_time' => 'varchar',
'speed' => 'varchar',
'brief' => 'longtext',
'remark' => 'varchar',
'tels' => 'varchar',
'ps' => 'varchar',
'count' => 'int',
'grade' => 'int',
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'name' => '商家全称',
'short' => '商家简称',
'slogan' => '标语',
'meal_time' => '送餐时间',
'speed' => '送餐速度',
'brief' => '简介',
'remark' => '备注',
'tels' => '送餐电话',
'ps' => '吐槽',
// 'count' => 'Count',
// 'grade' => 'Grade',
);
}
public function attributeAddLabels(){
return array(
'name' => '商家全称',
'short' => '商家简称',
'slogan' => '标语',
'meal_time' => '送餐时间',
'speed' => '送餐速度',
'brief' => '简介',
'remark' => '备注',
'tels' => '送餐电话',
'ps' => '吐槽',
);
}
public function attributeAdminLabels(){
return array(
'name' => '商家全称',
'short' => '商家简称',
// 'slogan' => '标语',
'meal_time' => '送餐时间',
'speed' => '送餐速度',
// 'brief' => '简介',
// 'remark' => '备注',
'tels' => '送餐电话',
// 'ps' => '吐槽',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('name',$this->name,true);
$criteria->compare('short',$this->short,true);
$criteria->compare('slogan',$this->slogan,true);
$criteria->compare('meal_time',$this->meal_time,true);
$criteria->compare('speed',$this->speed,true);
$criteria->compare('brief',$this->brief,true);
$criteria->compare('remark',$this->remark,true);
$criteria->compare('tels',$this->tels,true);
$criteria->compare('ps',$this->ps,true);
$criteria->compare('count',$this->count);
$criteria->compare('grade',$this->grade);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}<file_sep>/protected/controllers/tshops/IndexAction.php
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of GameAction
*
* @author Administrator
*/
class IndexAction extends AdminAction{
//put your code here
public function run() {
// var_dump($this->tags);
$this->setCustomTags(array(
'merchant',
),'<onlyone>');
$this->controller->render('index',array(
));
}
public function tagMerchant(){
$m = $this->getTagContents('merchant');
if(!empty ($m)){
$dataProvider=new CActiveDataProvider('Tshops');
$data = $dataProvider->getData();
$html = '';
foreach($data as $d){
$html .= Yii::t('nan',$m[0],array(
'$url'=>Yii::app()->createUrl('tshops/view',array('id'=>$d['id'])),
'$short'=>$d['short'],
'$slogan'=>$d['slogan'],
'$count'=>$d['count'],
));
}
return $html;
}
}
}
?>
<file_sep>/test/web.php
<?php
$yourdb = "xianshannan";//在这里注册账号http://wx.xiaojo.com
$yourpw = "<PASSWORD>";
if(trim($_GET['para'])!="")
{
$chat = $_GET['para'];
$reply = xiaojo($chat);
echo $reply;
//echo 'test(' . json_encode($reply) . ')';
}
function xiaojo($chat) { //小九接口函数,该函数可通用于其他程序
global $yourdb,$yourpw;
$chat = get_utf8_string($chat);
$chat=urlencode($chat);
$yourdb=urlencode($yourdb);
// $from=urlencode($from);
// $to=urlencode($to);
$doc = new DOMDocument();
$doc->load("http://www.xiaojo.com/api3.php?chat=".$chat."&db=".$yourdb."&pw=".$yourpw); //读取xml文件
$youdaos = $doc->getElementsByTagName( "weixen" ); //取得humans标签的对象数组
foreach( $youdaos as $youdao )
{
$paragraphs = $youdao->getElementsByTagName( "responce" ); //取得name的标签的对象数组
$paragraph = $paragraphs->item(0)->nodeValue; //取得node中的值,如<name> </name>
$paragraph=get_utf8_string($paragraph);
}
$reply = urldecode($paragraph);//
return $reply;
}
function get_utf8_string($content)
{
// 将一些字符转化成utf8格式
$encoding = mb_detect_encoding($content, array('ASCII','UTF-8','GB2312','GBK','BIG5'));
return mb_convert_encoding($content, 'utf-8', $encoding);
}
?>
<file_sep>/protected/extensions/mylib/NDataAction.php
<?php
/**
* 用来处理标签替换,只能再...Action类中能用
*
* @author Administrator
*/
class NDataAction extends CWidget{
//put your code here
public function insertDatasByTagsPk($tag,$criteria=array()){
}
/**
* 循环替换标签插入数据
*@param string $tag标签id值
*@param array $options
* Model名<br>
* $options['criteria']criteria配置
* $options['all']所有字段开启
*/
public function insertDatasByTags($options){
$tag = $this->tagId;
$m = $this->getTagContents($tag);
if(!empty($m)){
if(!isset($options['criteria']))
$options['criteria'] = array();
$dataProvider = new CActiveDataProvider($options['model'],array(
'criteria'=>$options['criteria'],
));
$data = $dataProvider->getData();
$showColumns = $dataProvider->model->attributeStageLabels();
$labels = array_keys( $dataProvider->model->attributeAddLabels());
if(isset($options['all']))
$showColumns = array_merge($showColumns,$labels);
// var_dump($showColumns);
$t = array();
$html = '';
foreach($data as $key=>$d){
$function = $tag.'Data';
if(method_exists($this,$function))
$d = $this->$function($d);
foreach($showColumns as $s){
$t['$'.$s] = $d[$s];
}
$html .= Yii::t('nan',$m[0],$t);
}
return $html;
}
}
}
?>
<file_sep>/protected/views/app/bus.php
<header id="top" >
<a id = "back" href="javascript:history.go(-1);" >返回</a>
<div id = "title" class = "span1" >常见公交</div>
<a id = "home" href="<?php echo Yii::app()->request->baseUrl; ?>" >首页</a>
</header>
<div class = "bus-li" >
<?php
$data = $model->getData();
$stops = array();
foreach($data as $d):
$stops = explode(';', $d['stop']);
?>
<a class = "rarr" href = "{$createUrl(app/bus_p?id=$id)}" >
<span class = "number" ><strong ><?php echo $d['road'];?>路</strong></span>
<span class = "info span1" >
<span><?php echo $stops[0];?>→<?php echo $stops[count($stops)-1];?></span>
间隔:<?php echo $d['interval'];?>min</span>
<?php
endforeach;
?>
</a>
</div><file_sep>/protected/views/app/sel1.php
<header id="top" >
<a id = "back" href="javascript:history.go(-1);">返回</a>
<div id = "title" class = "span1" >选择学院阵营</div>
<a id = "home" href="<?php echo Yii::app()->request->baseUrl; ?>">首页</a>
</header>
<?php
$ds = DIRECTORY_SEPARATOR;
$exclePath = Yii::getPathOfAlias('application.data.timetable.excel');
$department = file_get_contents($exclePath.$ds."department.txt");
$departments = explode(';', $department);
?>
<div id = "selection" >
<p>请告诉小U,你是蛋黄派,还是草莓派?</p>
<ul>
<?php foreach($departments as $key=>$d): ?>
<li>
<?php echo $d;?>
<input type="radio" name="colleges" value="<?php echo $key;?>" style="display:none;"/>
</li>
<?php
endforeach;
?>
</ul>
</div>
<div>
<a id = "next-btn" href = "{$createUrl(app/sel2?department=)}" >下一步</a>
</div>
<script>
sel1();
</script>
<file_sep>/protected/views/takeout/admin.php
<?php
$this->breadcrumbs=array(
'外卖商家列表'=>array('index'),
'外卖分类管理',
);
?>
<?php
$data = $options['dataProvider']->getData();
foreach($data as $key=>$d){
$data[$key]['takeouts'] = GlobalFunction::substrcn($d['takeouts'], '15');
$data[$key]['brief'] = GlobalFunction::substrcn($d['brief'], '15');
}
$this->widget('ext.mylib.NGridView',$options);
?>
<file_sep>/protected/views/app/organizations.php
<header id="top" >
<a id = "back" href="javascript:history.go(-1);">返回</a>
<div id = "title" class = "span1" >机构协会</div>
<a id = "home" href="<?php echo Yii::app()->request->baseUrl; ?>/">首页</a>
</header>
<?php
$ds = DIRECTORY_SEPARATOR;
$org = Yii::getPathOfAlias('application.data.organization');
$org_con = file_get_contents($org.$ds.'set.set');
$orgs = explode(';', $org_con);
?>
<nav id = "nav" class = "clearfix">
<a href = "{$createUrl(app/activities)}"><span>活动</span></a>
<a href = "{$createUrl(app/apply)}" ><span>可申请</span></a>
<a class="current"><span>机构协会</span></a>
</nav>
<ul id = "category-bar" >
<?php
foreach($orgs as $key=>$o):
?>
<li>
<a class = "academy barr" ><?php echo $o;?></a>
<ul class = "o-list" >
<?php
$org2 = Yii::getPathOfAlias('application.data.organization');
$org_con2 = file_get_contents($org.$ds.$key.$ds.'set.set');
$orgs2 = explode(';', $org_con2);
foreach($orgs2 as $key2=>$o2):
?><li><a href = "{$createUrl(/app/organizations_p?id=)}<?php echo $key.'.'.$key2; ?>" ><?php echo $o2;?></a></li><?php
endforeach;
?>
</ul>
</li>
<?php
endforeach;
?>
</ul>
<p style="text-align:center;margin-top:30px;font-size:13px;color:#999;" >需要填注资料的协会机构部门请联系我们<br>联系方式在关于&反馈页面<br>感谢</p>
<script src = "<?php echo yii::app()->request->baseUrl;?>/js/control.js" ></script>
<script>
organizations();
</script><file_sep>/protected/views/app/robot.php
<!--<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>-->
<header id="top" >
<a id = "back" href="javascript:history.go(-1);">返回</a>
<div id = "title" class = "span1" >小U机器人</div>
<a id = "home" href="<?php echo Yii::app()->request->baseUrl; ?>">首页</a>
</header>
<div id = "chat" >
<section class = "dialog-r fadeInLeft" >
<img class = "portrait" src = "#" >
<p>你好,有什么可以跟小U聊聊吗?</p>
</section>
</div>
<div id="chat-loading">
<img src = "<?php echo Yii::app()->request->baseUrl; ?>/images/loading.gif" />
</div>
<div id = "chat-input" >
<div><input type = "textarea" id="text" /></div>
<a onclick="javascript:chat();" id="btn" >发送</a>
</div>
<script type="text/javascript">
function replacep(str)
{
str = str.replace(/\+/g,"%2b");
str = str.replace(/([\da-zA-Z]+)([\u4E00-\u9FA3])/,"$1"+"%20"+"$2");
return str;
}
var box = document.getElementById("chat"),
text = document.getElementById("text"),
loading = document.getElementById("chat-loading"),
btn = document.getElementById("btn");
function chat()
{
var reg = (/[\u4e00-\u9fa5]/);
var val = text.value;
if ( val.length == 0 ) return false;
var s = document.createElement( "section" ),
img = document.createElement( "img" ),
p = document.createElement( "p" );
p.appendChild(document.createTextNode( val ));
s.appendChild(img);
s.appendChild(p);
s.className = "dialog-u";
box.appendChild(s);
setTimeout( function(){
s.className += " fadeInLeft";
},100);
box.scrollTop = box.scrollHeight ;
var url = "<?php echo Yii::app()->request->baseUrl; ?>/test/web.php?para=" + val;
var mark = setTimeout(
function(){
loading.setAttribute("style", "display:block;");
},
1000
);
$.ajax({
type : "get",
url : url,
success : function (d){
d.length == 0 ? d = "无力吐槽" : d.replace( /<[^>]+>/, function(){ d = "看,有美女!";} ) ;
test(d);
clearTimeout(mark);
loading.setAttribute("style", "display:none;");
}
});
}
function test(res)
{
text.value="";
box.innerHTML+="<section class = 'dialog-r' ><img class = 'portrait' src = '#' ><p>"+res+"</p></section>";
var t = document.querySelector( ".dialog-r:last-child" );
setTimeout( function(){
t.className += " fadeInLeft";
},100);
box.scrollTop = box.scrollHeight ;
btn.disabled=false;
text.focus();
};
box.setAttribute( "style", "height:" + ( window.innerHeight-document.getElementById("page").scrollHeight+box.offsetHeight-10 ) + "px;overflow-y:scroll;" );
//开启聊天功能
$.ajax({
type : "get",
url : "<?php echo Yii::app()->request->baseUrl; ?>/test/web.php?para=说话"
});
</script><file_sep>/protected/views/app/sel2.php
<header id="top" >
<a id = "back" href="javascript:history.go(-1);">返回</a>
<div id = "title" class = "span1" >选择专业班级</div>
<a id = "home" href="<?php echo Yii::app()->request->baseUrl; ?>">首页</a>
</header>
<?php
$ds = DIRECTORY_SEPARATOR;
$exclePath = Yii::getPathOfAlias('application.data.timetable.excel');
$department = file_get_contents($exclePath.$ds."department.txt");
$departments = explode(';', $department);
$majorPath = Yii::getPathOfAlias("application.data.timetable.excel.{$_GET['department']}.2013-2014");
$major = file_get_contents($majorPath.$ds."major.txt");
$majors = explode(';', $major);
?>
<form id = "selection" >
<p>请选择专业班级</p>
<select>
<option value="" >心无杂念</option>
<?php
foreach($majors as $key=>$m):
?>
<option value = "<?php echo $key;?>"><?php echo $m;?></option>
<?php
endforeach;
?>
?>
</select>
<div id = "sel-result">
<p>你选择的结果:</p>
<div><?php echo $departments[$_GET['department']];?> <span></span></div>
</div>
</form>
<div><a id = "next-btn" href = "{$createUrl(app/timetable_p?id=)}" >决定</a></div>
<script>
sel2( "<?php echo $_GET['department'];?>" );
</script><file_sep>/protected/views/app/apply.php
<header id="top" >
<a id = "back" href="javascript:history.go(-1);">返回</a>
<div id = "title" class = "span1" >可申请项目</div>
<a id = "home" href="<?php echo Yii::app()->request->baseUrl; ?>/">首页</a>
</header>
<?php
$ds = DIRECTORY_SEPARATOR;
$org = Yii::getPathOfAlias('application.data.organization');
$org_con = file_get_contents($org.$ds.'set.set');
$orgs = explode(';', $org_con);
?>
<section>
<nav id = "nav" class = "clearfix">
<a href = "{$createUrl(app/activities)}"><span>活动</span></a>
<a class="current" ><span>可申请</span></a>
<a href = "{$createUrl(app/organizations)}" ><span>机构协会</span></a>
</nav>
<div class = "flexbox" style="margin:0 10px 10px;" >
<div class="sort span1 flexbox" >
<a class="span1 selected">全部</a>
<a class="span1">学术科技</a>
<a class="span1">文化体育</a>
<a class="span1">社会实践</a>
</div>
<div class="search flexbox" >
<p class="span1" ><input type="text" /></p>
<a class="icon-search"></a>
</div>
</div>
<div id = "apply-header" class = "clearfix" >
<span>名称</span>
<span class="order down">申请截止<b><i class="icon-down-big" ></i><i class="icon-up-big"></i></b></span>
<span>类型</span>
</div>
</section>
<div id = "apply" >
<ul>
<li class = "clearfix" >
<span>参军</span>
<span>无限制</span>
<span>社会实践类</span>
</li>
<li class = "clearfix" >
<span>2012-2013学年第二学期社会实践活动(参与无偿献血)</span>
<span>2013/11/25</span>
<span>社会实践类</span>
</li>
<li class = "clearfix" >
<span>2012-2013学年第二学期社会实践活动(参与无偿献血)</span>
<span>2013/11/25</span>
<span>社会实践类</span>
</li>
<li class = "clearfix" >
<span>2012-2013学年第二学期社会实践活动(参与无偿献血)</span>
<span>2013/11/25</span>
<span>社会实践类</span>
</li>
<li class = "clearfix" >
<span>2012-2013学年第二学期社会实践活动(参与无偿献血)</span>
<span>2013/11/25</span>
<span>社会实践类</span>
</li>
<li class = "clearfix" >
<span>2012-2013学年第二学期社会实践活动(参与无偿献血)</span>
<span>2013/11/25</span>
<span>社会实践类</span>
</li>
<li class = "clearfix" >
<span>2012-2013学年第二学期社会实践活动(参与无偿献血)</span>
<span>2013/11/25</span>
<span>社会实践类</span>
</li>
<li class = "clearfix" >
<span>2012-2013学年第二学期社会实践活动(参与无偿献血)</span>
<span>2013/11/25</span>
<span>社会实践类</span>
</li>
<li class = "clearfix" >
<span>2012-2013学年第二学期社会实践活动(参与无偿献血)</span>
<span>2013/11/25</span>
<span>社会实践类</span>
</li>
<li class = "clearfix" >
<span>2012-2013学年第二学期社会实践活动(参与无偿献血)</span>
<span>2013/11/25</span>
<span>社会实践类</span>
</li>
<li class = "clearfix" >
<span>2012-2013学年第二学期社会实践活动(参与无偿献血)</span>
<span>2013/11/25</span>
<span>社会实践类</span>
</li>
<li class = "clearfix" >
<span>2012-2013学年第二学期社会实践活动(参与无偿献血)</span>
<span>2013/11/25</span>
<span>社会实践类</span>
</li>
<li class = "clearfix" >
<span>2012-2013学年第二学期社会实践活动(参与无偿献血)</span>
<span>2013/11/25</span>
<span>社会实践类</span>
</li>
<li class = "clearfix" >
<span>2012-2013学年第二学期社会实践活动(参与无偿献血)</span>
<span>2013/11/25</span>
<span>社会实践类</span>
</li>
<li class = "clearfix" >
<span>2012-2013学年第二学期社会实践活动(参与无偿献血)</span>
<span>2013/11/25</span>
<span>社会实践类</span>
</li>
</ul>
</div>
<script>
</script><file_sep>/protected/views/app/about.php
<header id="top" >
<a id = "back" href="javascript:history.go(-1);">返回</a>
<div id = "title" class = "span1" >关于小U</div>
<a id = "home" href="<?php echo Yii::app()->request->baseUrl; ?>">首页</a>
</header>
<article id = "about">
<header><h1>口袋广油<br><span>开发测试版</span></h1></header>
<section>
<h2>关于目的</h2>
<p>在广油已经度过三个春秋,看着一个个满载着亲人期望的“起点”来到广油,真是感慨万分。</p>
<p>“对头,所谓青春不就是有想法就做吧。”这样的想法现在领悟算不算有点迟?</p>
<p>我们想尝试创造一种特色,让今后的新生来到后会发现“哇,原来我们学校还有这样的东西”。</p>
<p>没错,我们意在传递一股正能量。</p>
</section>
<section>
<h2>关于团队</h2>
<p>暂时3人。基本上,规划,开发甚至今后宣传都是一手抓。(唉呀...唉呀,前路荆棘,进度缓慢)
<p>当然,我期望看到志同道合的同学加入。</p>
</section>
<section>
<h2>关于发展</h2>
<p>以考虑各位的爪姬流量为设计的重要准则。</p>
<p>口袋广油暂时没有赞助商,也不以盈利为目的。我们最需要听到的声音来自使用者。</p>
<p>我们希望做出真正对在广油奋斗的大家起到帮助的应用。</p>
</section>
<section>
<h2>反馈</h2>
<p>
如果使用中出现以下情况,可以进行反馈:
<ul>
<li>发现程序中某些Bug</li>
<li>对功能有自己的需求或建议</li>
<li>相关内容有侵权行为</li>
<li>对师妹有独特见解</li>
<li>这样那样之类的事</li>
</ul>
</p>
<p>邮箱:<EMAIL></p>
<p>新浪微博@打鸡血的梏桎</p>
<p>同时欢迎到广东石油化工学院贴吧加入讨论交流!</p>
</section>
<section>
<h2>感谢以下同学的无偿帮助:</h2>
<p>张三,李四</p>
</section>
<footer>
<p>Copyright©2013 口袋广油<br>你们的使用与反馈,是我们前进的最大动力</p>
</footer>
</article><file_sep>/protected/controllers/app/BusAction.php
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of GameAction
*
* @author Administrator
*/
class BusAction extends StageAction{
//put your code here
private $dataProvider;
public function run() {
// var_dump($this->tags);
$this->setCustomTags(array(
'id',
),'[]');
$this->dataProvider = new CActiveDataProvider('Bus');
$this->controller->render("bus", array(
'model' => $this->dataProvider,
));
}
public function tagId(){
$m = $this->getTagContents('id');
$id = $this->dataProvider->getData();
if(isset($m[0])){
$html = Yii::t('nan',$m[0],array(
'$id'=>$id[0]['id'],
));
return $html;
}
}
}
?>
<file_sep>/protected/views/sutuo/admin.php
<?php
/* @var $this SutuoController */
/* @var $model Sutuo */
$this->breadcrumbs=array(
'素拓管理后台',
);
$this->menu=array(
array('label'=>'添加素拓管理', 'url'=>Yii::app()->createUrl('sutuo/admin'),'active'=>true),
array('label'=>'添加素拓活动', 'url'=>Yii::app()->createUrl('sutuo/create')),
);
?>
<br>
<br>
<?php
$data = $options['dataProvider']->data;
$chosen = $options['dataProvider']->model->chosen();
foreach($data as $key=>$d){
switch($d['module']){
case 0:
$data[$key]['module'] = $chosen['module'][0];
break;
case 1:
$data[$key]['module'] = $chosen['module'][1];
break;
case 2:
$data[$key]['module'] = $chosen['module'][2];
break;
}
$data[$key]['name'] = GlobalFunction::substrcn($d['name'],15);
}
$this->widget('ext.mylib.NGridView',$options);
?>
<file_sep>/protected/controllers/layout/StageAction.php
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of GameAction
*
* @author Administrator
*/
class StageAction extends TagsAction{
public $startdate;
public function __construct($controller, $id) {
// $this->setCustomTags(array(
// 'test',
// ),'<content>');
parent::__construct($controller, $id);
}
/**
* 获取当前周次
*/
public function getWeek(){
$dataProvider = new CActiveDataProvider('Week',array(
));
$data = $dataProvider->getData();
$date = explode("-",$data[0]["b_time"]);
$startdate=mktime("0","0","0",$date[1],$date[2],$date[0]);
$this->startdate = $startdate;
$y = date("Y"); $m = date("m"); $d = date("d");
$enddate=mktime("0","0","0",$m,$d,$y);
return $weeks = floor(($enddate-$startdate)/3600/24/7)+1;
}
/**
* 通过周次获取星期一的日期
*/
public function getDateByWeek($week){
$enddate = ($week-1)*7*24*3600+$this->startdate;
return date('Y-m-d',$enddate);
}
public function tagTest(){
$m = $this->getTagContents('test');
// return "sdfsdfsfdf";
}
}
?>
<file_sep>/protected/views/layouts/main.php
<?php
// function isMobile() {
// 如果有HTTP_X_WAP_PROFILE则一定是移动设备
// if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])) {
// return true;
// }
// 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
// if (isset ($_SERVER['HTTP_VIA'])) {
// 找不到为flase,否则为true
// return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
// }
// 脑残法,判断手机发送的客户端标志,兼容性有待提高
// if (isset ($_SERVER['HTTP_USER_AGENT'])) {
// $clientkeywords = array (
// 'nokia',
// 'sony',
// 'ericsson',
// 'mot',
// 'samsung',
// 'htc',
// 'sgh',
// 'lg',
// 'sharp',
// 'sie-',
// 'philips',
// 'panasonic',
// 'alcatel',
// 'lenovo',
// 'iphone',
// 'ipod',
// 'blackberry',
// 'meizu',
// 'android',
// 'netfront',
// 'symbian',
// 'ucweb',
// 'windowsce',
// 'palm',
// 'operamini',
// 'operamobi',
// 'openwave',
// 'nexusone',
// 'cldc',
// 'midp',
// 'wap',
// 'mobile'
// );
// 从HTTP_USER_AGENT中查找手机浏览器的关键字
// if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
// return true;
// }
// }
// 协议法,因为有可能不准确,放到最后判断
// if (isset ($_SERVER['HTTP_ACCEPT'])) {
//如果只支持wml并且不支持html那一定是移动设备
//如果支持wml和html但是wml在html之前则是移动设备
// if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
// return true;
// }
// }
// return false;
// }
// if(!isMobile()) {
// header("Content-type: text/html; charset=utf-8");
// $this->renderPartial('abort');
// exit();
// }
// echo $_SERVER['HTTP_USER_AGENT'];
$id = $this->action->id;
;?>
<!--
<n:link>
{
"baseUrl":"{baseUrl}/css/",
"layout":["main"],
"action":{
"take_out_p":["take_out_p,"],
"robot":["robot"],
"about":["about"],
"timetable":["timetable_p"],
"sel":["sel1","sel2"],
"bus":["bus"],
"take_out":["take_out"],
"organizations":["organizations","organizations_p"],
"jobs":["jobs","activities"],
"jobs_p":["jobs_p","activities_p"],
"apply":[ "apply"],
"index":["index"],
"bus_p":["bus_p"]
}
}
</n:link>
<n:script>
{
"baseUrl":"{baseUrl}/js/",
"layout":["lib","control"]
}
</n:script>
-->
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8" >
<meta name = "viewport" content = "width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0" >
<title>{$pageTitle}</title>
</head>
<body>
<div class="container" id="page">
<?php echo $content; ?>
</div><!-- page -->
</body>
</html>
<file_sep>/protected/models/Sutuo.php
<?php
/**
* This is the model class for table "{{sutuo}}".
*
* The followings are the available columns in table '{{sutuo}}':
* @property integer $id
* @property string $name
* @property string $level
* @property string $host
* @property string $begin
* @property string $end
* @property string $address
* @property string $principal
* @property string $cornet
* @property integer $module
* @property string $score
* @property string $brief
* @property string $tag
* @property string $remark
*/
class Sutuo extends NActiveRecord
{
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return Sutuo the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return '{{sutuo}}';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('name, level, host, object,begin, end, address, principal, cornet, module, score, brief, tag', 'required'),
array('module', 'numerical', 'integerOnly'=>true),
array('name, host', 'length', 'max'=>90),
array('level', 'length', 'max'=>30),
array('address, tag', 'length', 'max'=>120),
array('principal', 'length', 'max'=>15),
array('cornet', 'length', 'max'=>20),
array('score', 'length', 'max'=>10),
array('remark', 'length', 'max'=>255),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, name, level, host, begin, end, address, principal, cornet, module, score, brief, tag, remark', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations(){
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels(){
return array(
'id' => 'ID',
'name' => '活动名称',
'level' => '活动级别',
'object' => '活动对象',
'host' => '主办单位',
'begin' => '开始时间',
'end' => '结束时间',
'address' => '地点',
'principal' => '负责人',
'cornet' => '短号',
'module' => '素拓分模块',
'score' => '素拓分',
'brief' => '简介',
'tag' => '标签',
'remark' => '备注',
);
}
public function fieldType(){
return array(
'id' => 'ID',
'name' => 'varchar',
'level' => 'varchar',
'host' => 'varchar',
'object' => 'varchar',
'begin' => 'datetime',
'end' => 'datetime',
'address' => 'varchar',
'principal' => 'varchar',
'cornet' => 'varchar',
'module' => 'chosen',
'score' => 'varchar',
'brief' => 'longtext',
'tag' => 'varchar',
'remark' => 'varchar',
);
}
public function chosen(){
return array(
'module' => array(
"学术科技与专业技能活动",
"专业文化艺术与体育竞技活动技能",
"社会实践与志愿服务活动",
),
);
}
public function attributeAddLabels(){
return array(
'name' => 'varchar',
'level' => 'varchar',
'host' => 'varchar',
'object' => 'varchar',
'begin' => 'datatime',
'end' => 'datatime',
'address' => 'varchar',
'principal' => 'varchar',
'cornet' => 'varchar',
'module' => 'chosen',
'score' => 'varchar',
'brief' => 'longtext',
'tag' => 'varchar',
'remark' => 'varchar',
);
}
public function attributeAdminLabels(){
return array(
'id' => 'ID',
'name' => '活动名称',
'level' => '活动级别',
'host' => '主办单位',
'module' => '素拓分模块',
);
}
public function attributeStageLabels(){
return array(
'id',
'name',
'end',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('name',$this->name,true);
$criteria->compare('level',$this->level,true);
$criteria->compare('host',$this->host,true);
$criteria->compare('begin',$this->begin,true);
$criteria->compare('end',$this->end,true);
$criteria->compare('address',$this->address,true);
$criteria->compare('principal',$this->principal,true);
$criteria->compare('cornet',$this->cornet,true);
$criteria->compare('module',$this->module);
$criteria->compare('score',$this->score,true);
$criteria->compare('brief',$this->brief,true);
$criteria->compare('tag',$this->tag,true);
$criteria->compare('remark',$this->remark,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}<file_sep>/protected/views/app/bus_p.php
<header id="top" >
<a id = "back" href="javascript:history.go(-1);">返回</a>
<div id = "title" class = "span1" >公交7路</div>
<a id = "home" href="<?php echo Yii::app()->request->baseUrl; ?>">首页</a>
</header>
<?php
$stops = explode(';', $model['stop']);
$count = count($stops);
?>
<div id = "bus-post" >
<ul id = "bus-info" >
<li>间隔:<?php echo $model['interval'];?>min</li>
<li>首班:<?php echo $model['start'];?></li>
<li>末班:<?php echo $model['end'];?></li>
<li>
<span id = "state-hot" >热点站</span>
<span id = "state-BAE" >始末站</span><br>
<span style = "margin-right:10px;" >共计站数:<?php echo $count;?></span>
<span>更新时间:<?php echo $model['created'];?></span>
</li>
</ul>
<ul id = "stations">
<?php
$h_stops = json_decode($model['h_stop']);
$class = '';
// var_dump($h_stops);
foreach($stops as $i=>$s):
if($i==0||$i==$count-1){
?>
<li class = "station-BAE"><?php echo $s;?></li>
<?php
}else{
if($i!=$h_stops[$i])
$class = "station-hot";
else $class = "";
?>
<li class="<?php echo $class;?>"><?php echo $s;?></li>
<?php
}
endforeach;
?>
</ul>
</div><file_sep>/protected/views/app/timetable_p.php
<header id="top" >
<a id = "back" href="javascript:history.go(-1);">返回</a>
<div id = "title" class = "span1" >课表</div>
<a id = "home" href="<?php echo Yii::app()->request->baseUrl; ?>/">首页</a>
</header>
<?php
$ds = DIRECTORY_SEPARATOR;
$exclePath = Yii::getPathOfAlias('application.data.timetable.excel.'.$_GET['id']);
?>
<?php
$knob = array(
array(
'周一 1、2节'=>0,'周一 3、4节'=>1,'周一 5、6节'=>2,'周一 7、8节'=>3,'周一 9、10节'=>4,
),
array(
'周二 1、2节'=>0,'周二 3、4节'=>1,'周二 5、6节'=>2,'周二 7、8节'=>3,'周二 9、10节'=>4,
),
array(
'周三 1、2节'=>0,'周三 3、4节'=>1,'周三 5、6节'=>2,'周三 7、8节'=>3,'周三 9、10节'=>4,
),
array(
'周四 1、2节'=>0,'周四 3、4节'=>1,'周四 5、6节'=>2,'周四 7、8节'=>3,'周四 9、10节'=>4,
),
array(
'周五 1、2节'=>0,'周五 3、4节'=>1,'周五 5、6节'=>2,'周五 7、8节'=>3,'周五 9、10节'=>4,
),
);
$ds = DIRECTORY_SEPARATOR;
Yii::registerAutoloader(array('YiiExcel', 'autoload'), true);
$path = Yii::getPathOfAlias('application.data');
$objPHPExcel = PHPExcel_IOFactory::load($exclePath . ".xlsx");
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$schedule = array();
foreach($sheetData as $key=>$s){
if($key>1){
foreach($knob as $key2=>$k){
if(array_key_exists($s['B'],$k)){
// echo $k[$s['B']];
$schedule[$key2][$k[$s['B']]]['lesson'] = $s['A'];
$schedule[$key2][$k[$s['B']]]['site'] = $s['C'];
$schedule[$key2][$k[$s['B']]]['teacher'] = $s['D'];
}
}
}
}
?>
<div id = "reset" ><a href = "{$createUrl(app/sel1)}" >重新选择课表</a></div>
<table id = "timetable">
<thead>
<tr>
<th></th>
<th>一</th>
<th>二</th>
<th>三</th>
<th>四</th>
<th>五</th>
</tr>
</thead>
<tbody>
<?php
$j = 5;
$l_j = array(
'1~2','3~4','5~6','7~8','9~10',
);
for($i=0;$i<$j;$i++):
?>
<tr>
<th><?php echo $l_j[$i];?></th>
<?php
for($k=0;$k<$j;$k++):
$lesson = '';
$site = '';
$teacher = '';
if(!empty($schedule[$k][$i]['lesson'])){
$lesson = preg_replace('/([^^]+)|\(.*\)/', '', $schedule[$k][$i]['lesson']);
$site = $schedule[$k][$i]['site'];
$teacher = $schedule[$k][$i]['teacher'];
}
?>
<td><?php echo $lesson.'<br>'.$site.'<br>'.$teacher;?></td>
<?php
endfor;
?>
</tr>
<?php
endfor;
?>
</tbody>
</table>
<p style="text-align:center;font:bold 12px/16px 'arail';" >说明:带“*”标记为单周课程,带“**”为双周课程</p>
<script src = "<?php echo yii::app()->request->baseUrl;?>/js/control.js" ></script>
<script>
mark();
if ( window.localStorage ){
var s = window.localStorage,
o = s.getItem( "ud" );
if ( o ){
o = JSON.parse(o);
if ( o.collegeName ){
var e = document.getElementById( "reset" );
e.innerHTML += o.majorName;
}
};
}
</script><file_sep>/protected/views/app/take_out_p.php
<header id="top" >
<a id = "back" href="javascript:history.go(-1);">返回</a>
<div id = "title" class = "span1" ></div>
<a id = "home" href="<?php echo Yii::app()->request->baseUrl; ?>">首页</a>
</header>
<div id = "bus-post" >
<ul id = "bus-info" >
<li>送餐时间:</li>
<li>速度:
</li>
<li>简介:
</li>
<li>备注:</li>
<li style="margin:10px 0;">
送餐拨号(点击拨打):<br>
<span style="display:inline-block;width:50%;" ></span>
<a class = "tel icon-phone" href = "tel:" > 拨号</a>
<p style="display:inline-block;margin-top:5px;width:100%;">
</p>
</li>
</ul>
<div class = "take_out-box">
<h2>快餐</h2>
<ul class = "take_out-content j_dto">
<li class = "ton1">
<a id = "k-ton1" name = "k-ton1"></a>
<h3>7元(含7元以下)</h3>
<ul class = "take_out-menu">
<li>叉烧</li>
</ul>
</li>
</ul>
</div>
</div>
<script>
take_out_p();
</script><file_sep>/protected/controllers/AppController.php
<?php
class AppController extends NController {
/**
* Declares class-based actions.
*/
public function actions() {
return array(
'index'=>'application.controllers.app.IndexAction',
'activities'=>'application.controllers.app.ActivitiesAction',
'activities_p'=>'application.controllers.app.ActivitiespAction',
'robot'=>'application.controllers.app.RobotAction',
'take_out'=>'application.controllers.app.TakeoutAction',
'take_out_p'=>'application.controllers.app.TakeoutpAction',
'bus'=>'application.controllers.app.BusAction',
'bus_p'=>'application.controllers.app.BuspAction',
'sel1'=>'application.controllers.app.Sel1Action',
'sel2'=>'application.controllers.app.Sel2Action',
'timetable_p'=>'application.controllers.app.TimetablepAction',
'about'=>'application.controllers.app.AboutAction',
'jobs'=>'application.controllers.app.JobsAction',
'jobs_p'=>'application.controllers.app.JobspAction',
'apply'=>'application.controllers.app.ApplyAction',
'organizations'=>'application.controllers.app.OrganizationsAction',
'organizations_p'=>'application.controllers.app.OrganizationspAction',
);
}
/**
* This is the action to handle external exceptions.
*/
public function actionError() {
if ($error = Yii::app()->errorHandler->error) {
if (Yii::app()->request->isAjaxRequest)
echo $error['message'];
else
$this->render('error', $error);
}
}
/**
* Displays the contact page
*/
public function actionContact() {
}
}
<file_sep>/protected/controllers/SutuoController.php
<?php
class SutuoController extends NController
{
/**
* @var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/modelAdmin';
/**
* @return array action filters
*/
public function filters(){
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
);
}
public function actions() {
parent::actions();
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules(){
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('@'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* @param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
public function setWeek($mydate){
$dataProvider = new CActiveDataProvider('Week',array(
));
$data = $dataProvider->getData();
$date = explode("-",$data[0]["b_time"]);
$startdate=mktime("0","0","0",$date[1],$date[2],$date[0]);
$y = $mydate['Y']; $m =$mydate['m']; $d = $mydate['d'];;
$enddate=mktime("0","0","0",$m,$d,$y);
return $weeks = floor(($enddate-$startdate)/3600/24/7)+1;
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate() {
$model=new Sutuo;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Sutuo'])){
$model->setAttributes($_POST['Sutuo'],false);
if($model->save())
$this->redirectUser($model->id);
}
$this->render('create',array(
'model'=>$model,
));
}
public function splitDate($date){
$mydate['Y'] = substr($date, 0,4);
$mydate['m'] = substr($date, 5,2);
$mydate['d'] = substr($date, 8,2);
return $mydate;
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id){
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Sutuo'])){
// echo $_POST['Sutuo']['end'];
$begin = $this->splitDate($_POST['Sutuo']['begin']);
$end = $this->splitDate($_POST['Sutuo']['end']);
$b = $this->setWeek($begin);
$e = $this->setWeek($end);
$week = $b;
for($i=$b;$i<$e;$i++){
$week .= ','.($i+1);
}
if($week=='') $week = $b;
$_POST['Sutuo']['week'] = $week;
$model->setAttributes($_POST['Sutuo'],false);
if($model->save())
$this->redirectUser($model->id);
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* @param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
/**
* Lists all models.
*/
public function actionIndex() {
$this->redirect('sutuo/admin');
}
/**
* Manages all models.
*/
public function actionAdmin()
{
NDataRender::$dataProviderOptions = array(
'criteria' => array(
),
);
$dataRender = new NDataRender($this,'admin',array(
'show_checkbox_select'=>false,
'operate'=>'delete',
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* @param integer $id the ID of the model to be loaded
* @return Sutuo the loaded model
* @throws CHttpException
*/
public function loadModel($id)
{
$model=Sutuo::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* @param Sutuo $model the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='sutuo-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
<file_sep>/protected/views/layouts/main1.php
<!DOCTYPE html>
<html manifest = "/pocket/pocket/cache.manifest">
<head>
<meta charset = "utf-8" >
<meta name = "viewport" content = "width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0" >
<link rel="apple-touch-icon" href="http://bcs.duapp.com/mygyapp/s.png?sign=MBO:7f836d73f4717ff743eee8154ecb1697:vsXhpDrFXsaJV1JVLhd%2FFcW26HY%3D" />
<link rel="apple-touch-icon-precomposed" href="http://bcs.duapp.com/mygyapp/s.png?sign=MBO:7f836d73f4717ff743eee8154ecb1697:vsXhpDrFXsaJV1JVLhd%2FFcW26HY%3D" />
<title><?php echo CHtml::encode($this->pageTitle); ?></title>
<link rel = "stylesheet" type = "text/css" href = "<?php echo Yii::app()->request->baseUrl; ?>/css/main.css" >
</head>
<body>
<div class="container" id="page">
<?php echo $content;?>
</div><!-- page -->
</body>
</html><file_sep>/protected/views/sutuo/index.php
<?php
/* @var $this SutuoController */
/* @var $dataProvider CActiveDataProvider */
$this->breadcrumbs=array(
'Sutuos',
);
$this->menu=array(
array('label'=>'Create Sutuo', 'url'=>array('create'),'active'=>true),
array('label'=>'Manage Sutuo', 'url'=>array('admin')),
);
?>
<h1>Sutuos</h1>
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
)); ?>
<file_sep>/js/control.js
/* index */
/** 告示 **/
function slider (){
var content = document.getElementById( "notice-bar" ).getElementsByTagName( "ul" )[0],
unit = document.getElementById( "notice-bar" ).offsetHeight,
total = content.getElementsByTagName( "li" ).length,
t = 4000,
duration = 300,
transition = "-webkit-transition:" + duration + "ms;transition:" + duration + "ms;",
count = 0;
function sliding (){
content.setAttribute( "style", "top : " + (-count*unit) + "px;" + transition);
count += 1;
if( count >= total ){
setTimeout(
function (){
content.setAttribute( "style", "top : 0;-webkit-transition:0;transition:0;" );
},
duration
);
count = 1;
}
setTimeout( sliding, t );
}
sliding();
}
/** 关于和反馈 **/
function rotater(){
var r = document.querySelectorAll( "#rotate-tiles .j_tiles" ),
front = false,
t = 3500,
style = [ "background:"+r[0].style.background, "background:"+r[1].style.background ];
function rotating(){
if ( front ) {
r[1].setAttribute( "style", "-webkit-transform : rotate3d(0,1,0,0deg);z-index:999;" + style[1] );
r[0].setAttribute( "style", "-webkit-transform : rotate3d(0,1,0,-180deg);" + style[0] );
front = false;
} else{
r[0].setAttribute( "style", "-webkit-transform : rotate3d(0,1,0,0deg);z-index:999;" + style[0] );
r[1].setAttribute( "style", "-webkit-transform : rotate3d(0,1,0,-180deg);" + style[1] );
front = true;
}
setTimeout( rotating, t );
}
rotating();
}
// take_out_p
function take_out_p(){
var navs = document.querySelectorAll(".take_out-nav a");
var list = document.querySelectorAll( ".j_dto > li" );
for( var i = 0; i < navs.length; i++ ) {
(function(i){
var n = i;
var li = list[n];
var status = [ 'fadeOut', 'fadeIn'];
navs[i].onclick = function(){
var className = 'ton'+(n+1);
if( $.hasClass( this, className ) ){
$.removeClass( this, className );
$.addClass( li, status[0] );
$.removeClass( li, status[1] );
} else{
$.addClass( this, className );
$.addClass( li, status[1] );
$.removeClass( li, status[0] );
}
return false;
};
})(i);
}
}
// organizations
function organizations(){
var academy = document.querySelectorAll( ".academy" );
for( var i = 0; i < academy.length; i++ ) {
(function(){
var n = i,
toggleClass = "showO",
p = academy[n].parentNode;
academy[n].onclick = function(){
if( $.hasClass( p, toggleClass ) ){
$.removeClass( p, toggleClass );
}else {
$.addClass( p, toggleClass );
}
};
})();
}
}
/* timetable_p */
function mark() {
var d = new Date(),
x = d.getDay(),
h = d.getHours() + d.getMinutes() *0.01,
y = 0,
grid = document.querySelectorAll( "#timetable td" ),
head = document.querySelectorAll( "#timetable thead th" );
switch (true){
case 8 < h && h < 9.4:
y = 1;
break;
case 10 < h && h < 11.4:
y = 2;
break;
case 14.3 < h && h < 16.1:
y = 3;
break;
case 16.2 < h && h < 17.5:
y = 4;
break;
case 19.4 < h && h < 21.2:
y = 5;
break;
default:
break;
}
if ( 1<= x && x <= 5){
head[x].setAttribute( "class", "cur-day" );
if( y > 0 ){
grid[ x+((y-1)*5)-1 ].setAttribute( "class", "cur-course" );
}
}
}
/* sel1 */
function sel1() {
var colleges = document.querySelectorAll( "#selection li" ),
cur = {},
className = "actived",
btn = document.getElementById( "next-btn" ),
l = btn.getAttribute( "href" ),
value = 0,
name = "";
for ( var i = 0; i < colleges.length; i++ ){
var j = i;
( function(j){
colleges[j].onclick = function (){
if ( cur.tagName ){
cur.removeAttribute( "class" );
} else {
btn.setAttribute( "style", "display:block;" );
}
this.setAttribute( "class", className );
cur = this;
value = this.getElementsByTagName( "input" )[0].getAttribute("value");
btn.setAttribute( "href", l+value );
name = this.childNodes[0].nodeValue;
};
} )(j);
}
btn.onclick = function (){
if( window.localStorage ){
var ud = {
college : value,
collegeName : name
};
localStorage.setItem ( "ud", JSON.stringify( ud ) );
};
// return false;
}
}
/* sel2 */
function sel2( department ){
var sel = document.querySelectorAll( "#selection select" ),
btn = document.getElementById( "next-btn" );
span = document.querySelectorAll( "#sel-result span" ),
v = 0,
href = btn.getAttribute( 'href' ) + department + '.2013-2014.',
index = 0,
majorName = "";
sel[0].onchange = function (){
v = this.value;
if ( v === ""){
span[0].innerHTML = "";
btn.setAttribute( "style", "display:none;" );
return false;
}
if ( span[0].innerHTML === "" ) {
btn.setAttribute( "style", "display:block;" );
}
btn.setAttribute( "href", href + v );
index = this.selectedIndex;
majorName = this.options[index].innerHTML
span[0].innerHTML = majorName;
};
btn.onclick = function (){
if( window.localStorage ){
var ud = JSON.parse(localStorage.getItem ( "ud" ));
ud.major = v;
ud.course = href+v;
ud.majorName = majorName;
localStorage.setItem ( "ud", JSON.stringify(ud) );
};
}
}<file_sep>/protected/views/takeout/update.php
<?php
$this->breadcrumbs=array(
'外卖分类管理列表'=>array('index'),
$model->sort=>array('view','id'=>$model->id),
'修改更新',
);
?>
<?php echo $this->renderPartial('_form', array('model'=>$model)); ?><file_sep>/protected/views/app/abort.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script src="<?php echo Yii::app()->request->baseUrl; ?>/js/jquery.js"></script>
<style>
* {
padding : 0;
margin : 0;
}
.fl{
float : left;
}
.fr{
float : right;
}
.clearfix:after{content:".";display:block;height:0;clear:both;visibility:hidden;}
.fixj::after {
display : inline-block;
width : 100%;
height : 0;
overflow : hidden;
content : "";
}
#wrapper {
width : 100%;
height : 100%;
position :absolute;
top : 0;
left : 0;
}
#wrapper li {
position : absolute;
width : 100%;
height : 100%;
top : 0;
left : 0;
background-size : 100% 100%;
-webkit-background-size : 100% 100%;
-ms-background-size : 100% 100%;
-moz-background-size : 100% 100%;
-o-background-size : 100% 100%;
transition: .7s ease-in-out;
-webkit-transition: .7s ease-in-out;
-ms-transition: .7s ease-in-out;
-moz-transition: .7s ease-in-out;
-o-transition: .7s ease-in-out;
opacity : 0;
}
#wrapper .show {
opacity : 1;
}
.bgs1 {
background : url("http://bcs.duapp.com/poceket/images%2F1s.jpg?sign=MBO:7f836d73f4717ff743eee8154ecb1697:YIrDQTWlsGrfT%2FZDW%2FnfWBqw4Us%3D") center no-repeat;
}
.bgs2 {
background : url("http://bcs.duapp.com/poceket/images%2F2s.jpg?sign=MBO:7f836d73f4717ff743eee8154ecb1697:XO2AHxQAbh4U7jPNAZMlbhGjqtY%3D") center no-repeat;
}
.bgs3 {
background : url("http://bcs.duapp.com/poceket/images%2F3s.jpg?sign=MBO:7f836d73f4717ff743eee8154ecb1697:9rkWDakVqBR6ZobubuHFpJW5I0c%3D") center no-repeat;
}
.bgs4 {
background : url("http://bcs.duapp.com/poceket/images%2F4s.jpg?sign=MBO:7f836d73f4717ff743eee8154ecb1697:3RM9k4RLyERPOI%2FatRUiVaNhfbc%3D") center no-repeat;
}
.bg1 {
background : url("http://bcs.duapp.com/poceket/images%2F1.jpg?sign=MBO:7f836d73f4717ff743eee8154ecb1697:BUH9%2FfI9SlIKlx8oiVGAXxbWwNI%3D") center no-repeat;
}
.bg2 {
background : url("http://bcs.duapp.com/poceket/images%2F2.jpg?sign=MBO:7f836d73f4717ff743eee8154ecb1697:jQefg7JebRSszKv1lHgkvV4eBZo%3D") center no-repeat;
}
.bg3 {
background : url("http://bcs.duapp.com/poceket/images%2F3.jpg?sign=MBO:7f836d73f4717ff743eee8154ecb1697:mZddZDS1zQexyRTJjTBQwu8jxSk%3D") center no-repeat;
}
.bg4 {
background : url("http://bcs.duapp.com/poceket/images%2F4.jpg?sign=MBO:7f836d73f4717ff743eee8154ecb1697:pZRx3GH8FB6Qg%2FhFhpLwyGgS4GM%3D") center no-repeat;
}
#bgmask {
background : url("http://bcs.duapp.com/poceket/images%2Fbgmask.png?sign=MBO:7f836d73f4717ff743eee8154ecb1697:de%2BjOifMYk8%2FzNocbW73Of8KlDc%3D");
width : 100%;
height :100%;
position :absolute;
top : 0;
left : 0;
z-index : 10;
}
#container {
position : relative;
z-index : 99;
width : 1200px;
margin : 50px auto 0;
padding : 10px;
}
#banner {
b11ackground-color : rgba(0,0,0,.5);
width : 400px;
}
#banner h1,
#banner p {
color : #fff;
font-family : "微软雅黑",arial;
text-shadow : 2px 1px 1px #555;
}
#banner h1{
letter-spacing : .2em;
}
#banner p {
margin-top : 20px;
font-size : 14px;
letter-spacing : 1px;
}
#logo {
width : 90px;
height : 90px;
border-radius : 8px;
margin-right : 15px;
}
#ewm {
position:relative;
z-index : 5;
}
#ewm img {
width : 120px;
height : 120px;
position : relative;
cursor : pointer;
z-index : 10;
}
#ewm p {
position : absolute;
padding : 0 10px;
background-color : #fff;
top : 15px;
left : 20px;
font : 14px/35px "微软雅黑",arial;
width : 70px;
opacity : 0;
transform:translateX(-20px);
-webkit-transform:translateX(-20px);
-ms-transform:translateX(-20px);
-moz-transform:translateX(-20px);
-o-transform:translateX(-20px);
transition: opacity 0.5s, transform 0.5s;
-webkit-transition: opacity 0.5s, -webkit-transform 0.5s;
-ms-transition: opacity 0.5s, -ms-transform 0.5s;
-moz-transition: opacity 0.5s, -moz-transform 0.5s;
-o-transition: opacity 0.5s, -o-transform 0.5s;
}
#ewm p::before {
border : 6px solid transparent;
border-left-color : #fff;
content : "";
width : 0;
height : 0;
position : absolute;
right : -12px;
top : 10px;
}
#ewm:hover p {
opacity : 1;
transform:translateX(0);
-webkit-transform:translateX(0);
-ms-transform:translateX(0);
-moz-transform:translateX(0);
-o-transform:translateX(0);
left : -170px;
width : auto;
}
#suggest {
width : 110px;
font-size : 12px;
background-color : #FFF;
padding : 5px;
text-align : justify;
height : 90px;
overflow : hidden;
position : absolute;
opacity : 0;
transform:translateY(-103px);
-webkit-transform:translateY(-103px);
-ms-transform:translateY(-104px);
-moz-transform:translateY(-103px);
-o-transform:translateY(-103px);
transition: opacity 0.5s, transform 0.5s;
-webkit-transition: opacity 0.5s, -webkit-transform 0.5s;
-ms-transition: opacity 0.5s, -ms-transform 0.5s;
-moz-transition: opacity 0.5s, -moz-transform 0.5s;
-o-transition: opacity 0.5s, -o-transform 0.5s;
}
#ewm:hover #suggest {
opacity : 1;
transform:translateY(-3px);
-webkit-transform:translateY(-3px);
-ms-transform:translateY(-4px);
-moz-transform:translateY(-3px);
-o-transform:translateY(-3px);
}
#suggest div {
line-height : 20px;
}
#suggest a {
display : inline-block;
width : 25px;
height : 25px;
margin : 6px 3px 0;
background-size : 100% 100%;
-webkit-background-size : 100% 100%;
-ms-background-size : 100% 100%;
-moz-background-size : 100% 100%;
-o-background-size : 100% 100%;
background : url("http://bcs.duapp.com/poceket/images%2Fbrowsers.jpg?sign=MBO:7f836d73f4717ff743eee8154ecb1697:WczaG7JV3WpS5TxNjxRZnsinzMw%3D") no-repeat;
}
#suggest #uc {
background-position : 0 0;
}
#suggest #bd {
background-position : -25px 0;
}
#suggest #qq {
background-position : -50px 0;
}
#suggest #chrome {
background-position : -75px 0;
}
#suggest #ht {
background-position : -100px 0;
}
#suggest #lb {
background-position : -125px 0;
}
#chain {
border-left : 3px solid rgb(238,238,238);
width : 0;
margin-left : 30px;
}
#chain a {
display : block;
background-color : rgb(196,205,214);
border-radius : 50%;
cursor : pointer;
width : 10px;
height : 10px;
border : 3px solid #fff;
margin : 0 0 110px -9px;
transition: transform 0.5s linear, background-color .5 linear;
-webkit-transition: -webkit-transform 0.5s, background-color .5s;
-ms-transition: -ms-transform 0.5s, background-color .5s;
-moz-transition: -moz-transform 0.5s, background-color .5s;
-o-transition: -o-transform 0.5s, background-color .5s;
}
#chain a:last-child {
margin-bottom : 0;
}
#chain .actived {
background-color : #36c;
width : 12px;
height : 12px;
border-width : 2px;
transform : scale(1.5);
-webkit-transform : scale(1.5);
-ms-transform : scale(1.5);
-moz-transform : scale(1.5);
-o-transform : scale(1.5);
}
#content {
position : absolute;
margin : 0 auto;
left : 0;
right : 0;
width : 760px;
height : 100%;
font-family : "微软雅黑",arial;
}
#content div {
position : absolute;
left : 0;
width : 100%;
background-color : rgba(255,255,255,.65);
padding : 10px;
opacity:0;
transform:translate(20px);
-webkit-transform:translateX(20px);
-ms-transform:translateX(20px);
-moz-transform:translateX(20px);
-o-transform:translateX(20px);
transition: 0.5s;
-webkit-transition: 0.5s;
-ms-transition: 0.5s;
-moz-transition: 0.5s;
-o-transition: 0.5s;
}
#content .current{
opacity:1;
transform:translateX(0);
-webkit-transform:translateX(0);
-ms-transform:translateX(0);
-moz-transform:translateX(0);
-o-transform:translateX(0);
}
.statement,
.time {
font-size : 13px;
text-align : right;
margin-top : 5px;
padding-right : 10px;
}
.statement {
color : rgb(55,150,60);
font-weight : bold;
font-family : "宋体";
}
#footer{
position : absolute;
bottom : 0;
left : 0;
background-color : rgba(0,0,0,.8);
text-align : center;
color : #fff;
width : 100%;
padding : 15px 0;
}
#fixie{
display : none;
}
</style>
<!--[if lt IE 9]>
<link rel = "stylesheet" type = "text/css" href = "/demos/blog/css/fixie.css" />
<!--<![endif]-->
</head>
<body>
<div id = "bgmask"></div>
<ul id = "wrapper">
<li class="bgs1 show"></li>
<li class="bgs2"></li>
<li class="bgs3"></li>
<li class="bgs4"></li>
</ul>
<div id = "container">
<div id = "ewm" class = "fr" >
<img src = "http://bcs.duapp.com/poceket/images%2Fliantu.png?sign=MBO:7f836d73f4717ff743eee8154ecb1697:I70dFlxZsHPAGHvE%2BZP1klhmPvs%3D" />
<p>请用移动设备扫描!</p>
<div id = "suggest" class="fixj" >
<div>浏览器支持:</div>
<a href="http://as.baidu.com/a/item?docid=4474944&pre=web_am_se" target="_bank" id = "uc" title = "UC9.0+" ></a>
<a href="http://as.baidu.com/a/item?docid=4240518&pre=web_am_se" target="_bank" id = "bd" title = "百度浏览器4.0+" ></a>
<a href="http://as.baidu.com/a/item?docid=4383793&pre=web_am_se" target="_bank" id = "qq" title = "QQ浏览器2.3+" ></a>
<a href="http://as.baidu.com/a/item?docid=4414683&pre=web_am_se" target="_bank" id = "chrome" title = "谷歌浏览器" ></a>
<a href="http://as.baidu.com/a/item?docid=4541268&pre=web_am_se" target="_bank" id = "ht" title = "海豚浏览器10.0+" ></a>
<a href="http://as.baidu.com/a/item?docid=4548011&pre=web_am_se" target="_bank" id = "lb" title = "猎豹浏览器2.0+" ></a>
</div>
</div>
<div id = "banner" class="clearfix" >
<img class="fl" id="logo" src="http://bcs.duapp.com/poceket/images%2Floading.gif?sign=MBO:7f836d73f4717ff743eee8154ecb1697:PpwAXdmEbWOf7mXflvMDtE%2FROIo%3D">
<h1>口袋广油</h1>
<p>不待长发及腰 只想陪你度过广油每个春秋</p>
</div>
<div style="position:relative;">
<div id = "content">
<div class="current" style="bottom:0;">
<p>“还有10秒!” “时间到了。关灯” “哈哈,挺有趣的嘛。” “当然!” </p>
<p class="statement" >/* #6.6班委日# 最美的爱心 */</p>
<p class="time" >——— 2011年6月6日 晚上</p>
</div>
<div style="bottom:0;">
<p>“啊,雨停了。” “!!!” “这个角度好极了哦!” “哪里?我看看。” </p>
<p class="statement" >/* 心情不好时,记得这里有双彩虹陪伴着你 */</p>
<p class="time" >——— 2013年6月4日 傍晚</p>
</div>
<div style="bottom:0;">
<p>“喂喂,看那个月亮!” “哇,超级月亮。” “很漂亮啊!” “哈哈,二区那边起哄了。”</p>
<p class="statement" >/* 月晕,是光受高空卷层云的冰晶折射,使七色复合光被分散为内红外紫的光环或光弧而产生光圈 */</p>
<p class="time" >——— 2013年6月24日 晚上</p>
</div>
<div style="top:0;">
<p>“呼,总算...来到了。” “嗨,你好。” “我来自...” “嗯,以后我们就一个宿舍了。” </p>
<p class="statement" >/* 感谢,我们相识于此。 */</p>
<p class="time" >——— 2010年9月13日</p>
</div>
</div>
<div id="chain" >
<a class = "actived" ></a>
<a></a>
<a></a>
<a></a>
</div>
</div>
</div>
<div id = "footer" >Powered by 口袋广油</div>
<div id = "fixie" >
<p>咳。检测您当前的浏览器内核有点。。。<strong>经典</strong>!</p>
<p class="lp">建议您使用:<a>chrome</a>,<a>firefox</a>,<a>opera</a>,<a>safari</a>,<a>IE9+</a>浏览本页面。</p>
<p class="lp" style="margin-bottom:45px;">或者如果您正在使用搜狗,360等双核浏览器,可以切换到高速内核访问:<br><img src = "http://bcs.duapp.com/poceket/images%2Fgaosu.jpg?sign=MBO:7f836d73f4717ff743eee8154ecb1697:SsppV14%2FQgJlUhMeZUi77GEH5%2Fo%3D"></p>
<div id = "liantu" >
<p>访问口袋广油app,请用移动设备扫描!</p>
<img src = "http://bcs.duapp.com/poceket/images%2Fliantu.png?sign=MBO:7f836d73f4717ff743eee8154ecb1697:I70dFlxZsHPAGHvE%2BZP1klhmPvs%3D" />
</div>
<p style="position:absolute;bottom:0;left:0;width:100%;">Powered by 口袋广油</p>
</div>
<script>
var h = window.innerHeight,
w = window.innerWidth;
$( "#wrapper" ).css( "height", h+"px");
$( "#bgmask" ).css( "height", h+"px");
var contentH = $( "html" ).height(),
footerH = $( "#footer" ).height(),
space = h - contentH - footerH - 30, //30px上下padding
minSpace = 32,
marginBottom = 110; //最小空隙
if ( space > minSpace ) {
var anchor = $( "#chain a" );
newMarginBottom = marginBottom + (space-minSpace)/(anchor.length-1);
console.log(space+"-"+anchor.length+"-"+(anchor.length-1));
anchor.css( "margin-bottom", newMarginBottom+"px" );
anchor[(anchor.length-1)].removeAttribute( "style" );
}
window.onload = function() {
var widgets = [
$( "#wrapper li" ), //背景
$( "#content div" ), //文字
$( "#chain a" ) //导航轴
],
className = [ "show", "current", "actived" ],
cur = [
$( "#wrapper ."+className[0] ),
$( "#content ."+className[1] ),
$( "#chain ."+className[2] )
],
index = 0,
queue,
time = 5000,
src = [
"http://bcs.duapp.com/poceket/images%2F1.jpg?sign=MBO:7f836d73f4717ff743eee8154ecb1697:BUH9%2FfI9SlIKlx8oiVGAXxbWwNI%3D",
"http://bcs.duapp.com/poceket/images%2F2.jpg?sign=MBO:7f836d73f4717ff743eee8154ecb1697:jQefg7JebRSszKv1lHgkvV4eBZo%3D",
"http://bcs.duapp.com/poceket/images%2F3.jpg?sign=MBO:7f836d73f4717ff743eee8154ecb1697:mZddZDS1zQexyRTJjTBQwu8jxSk%3D",
"http://bcs.duapp.com/poceket/images%2F4.jpg?sign=MBO:7f836d73f4717ff743eee8154ecb1697:pZRx3GH8FB6Qg%2FhFhpLwyGgS4GM%3D"
];
widgets[2].click(
function(){
clearTimeout( queue );
index = widgets[2].index( $( this ) );
turn();
autoTurn();
}
);
function turn(){
for( var i = 0; i < widgets.length; i++ ){
cur[i].removeClass( className[i] );
cur[i] = $( widgets[i][ index ] );
cur[i].addClass( className[i] );
}
}
function autoTurn(){
//console.log( "哈哈" );
queue = setTimeout(
function(){
index = (index < widgets[0].length-1) ? index+1 : 0 ;
turn();
autoTurn();
},
time
);
}
//启动
//autoTurn();
//简易模糊加载
for( var i = 0; i < src.length; i++ ) {
(function(j){
var img = new Image();
img.src = src[j];
img.onload = function() {
$( widgets[0][j] ).addClass( "bg"+(j+1) );
}
})(i);
}
}
</script>
</body>
</html><file_sep>/protected/views/app/take_out.php
<header id="top" >
<a id = "back" href="javascript:history.go(-1);">返回</a>
<div id = "title" class = "span1" >外卖</div>
<a id = "home" href="<?php echo Yii::app()->request->baseUrl; ?>/">首页</a>
</header>
<p id="tips">小U提示:外卖虽然方便,但考虑健康问题,建议同学们还是尽量少点叫外卖哦!o( >_< )o </p>
<div id = "takeout" >
<a class = "list s-open" >
<!--<span class="state close" ><b class=""></b></span>-->
<div class = "info span1" >
<p class = "name">明记</p>
<p class = "intro" >你们的微笑时明记餐饮服务的追求</p>
<p class = "intro">
<span class = "level">
<b class = "complete" ></b><!--
--><b class = "complete" ></b><!--
--><b class = "half" ></b><!--
--><b></b><!--
--><b></b>
</span>共n种菜式
</p>
</div>
</a>
<a class = "list s-close" >
<!--<span class="state close" ><b class=""></b></span>-->
<div class = "info span1" >
<p class = "name">明记</p>
<p class = "intro" >你们的微笑时明记餐饮服务的追求</p>
<p class = "intro">
<span class = "level">
<b class = "complete" ></b><!--
--><b class = "complete" ></b><!--
--><b class = "half" ></b><!--
--><b></b><!--
--><b></b>
</span>共n种菜式
</p>
</div>
</a>
</div>
<script>
var h = window.innerHeight,
div = document.getElementById( "takeout" ),
offset = h-115-4; // 头部高度
div.setAttribute("style", "height:"+offset+"px;");
</script><file_sep>/nbproject/private/private.properties
index.file=index.php
url=http://localhost/pocket/
<file_sep>/protected/views/sutuo/_view.php
<?php
/* @var $this SutuoController */
/* @var $data Sutuo */
?>
<div class="view">
<b><?php echo CHtml::encode($data->getAttributeLabel('id')); ?>:</b>
<?php echo CHtml::link(CHtml::encode($data->id), array('view', 'id'=>$data->id)); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('name')); ?>:</b>
<?php echo CHtml::encode($data->name); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('level')); ?>:</b>
<?php echo CHtml::encode($data->level); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('host')); ?>:</b>
<?php echo CHtml::encode($data->host); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('begin')); ?>:</b>
<?php echo CHtml::encode($data->begin); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('end')); ?>:</b>
<?php echo CHtml::encode($data->end); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('address')); ?>:</b>
<?php echo CHtml::encode($data->address); ?>
<br />
<?php /*
<b><?php echo CHtml::encode($data->getAttributeLabel('principal')); ?>:</b>
<?php echo CHtml::encode($data->principal); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('cornet')); ?>:</b>
<?php echo CHtml::encode($data->cornet); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('module')); ?>:</b>
<?php echo CHtml::encode($data->module); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('score')); ?>:</b>
<?php echo CHtml::encode($data->score); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('brief')); ?>:</b>
<?php echo CHtml::encode($data->brief); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('tag')); ?>:</b>
<?php echo CHtml::encode($data->tag); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('remark')); ?>:</b>
<?php echo CHtml::encode($data->remark); ?>
<br />
*/ ?>
</div><file_sep>/protected/views/app/organizations_p.php
<header id="top" >
<a id = "back" href="javascript:history.go(-1);">返回</a>
<div id = "title" class = "span1" >棋牌协会</div>
<a id = "home" href="<?php echo Yii::app()->request->baseUrl; ?>">首页</a>
</header>
<?php
$ds = DIRECTORY_SEPARATOR;
$brief = Yii::getPathOfAlias('application.data.organization.'.$_GET['id']);
$contents = file_get_contents($brief.$ds.'0.html');
$content_l = explode('$$', $contents);
?>
<section id = "o-post" >
<dl class = "o-info" >
<dt>公告</dt>
<dd><?php echo $content_l[0];?></dd>
</dl>
<ul class = "o-info" >
<li>微博:<?php echo $content_l[1];?></li>
<li>邮箱:<a href = "mailTo:<EMAIL>" ><?php echo $content_l[2];?></a></li>
<li>现任会长:<?php echo $content_l[3];?></li>
<li>主要活动:<?php echo $content_l[4];?></li>
<li>标签:<?php echo $content_l[5];?></li>
</ul>
<dl class = "o-info" >
<dt>简介</dt>
<dd><?php echo $content_l[6];?></dd>
</dl>
<dl class = "o-info" >
<dt>部门构成</dt>
<dd><?php echo $content_l[7];?></dd>
</dl>
</section>
<file_sep>/protected/views/tshops/_view.php
<?php
/* @var $this TshopsController */
/* @var $data Tshops */
?>
<div class="view">
<b><?php echo CHtml::encode($data->getAttributeLabel('id')); ?>:</b>
<?php echo CHtml::link(CHtml::encode($data->id), array('view', 'id'=>$data->id)); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('name')); ?>:</b>
<?php echo CHtml::encode($data->name); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('short')); ?>:</b>
<?php echo CHtml::encode($data->short); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('slogan')); ?>:</b>
<?php echo CHtml::encode($data->slogan); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('meal_time')); ?>:</b>
<?php echo CHtml::encode($data->meal_time); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('speed')); ?>:</b>
<?php echo CHtml::encode($data->speed); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('brief')); ?>:</b>
<?php echo CHtml::encode($data->brief); ?>
<br />
<?php /*
<b><?php echo CHtml::encode($data->getAttributeLabel('remark')); ?>:</b>
<?php echo CHtml::encode($data->remark); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('tels')); ?>:</b>
<?php echo CHtml::encode($data->tels); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('ps')); ?>:</b>
<?php echo CHtml::encode($data->ps); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('count')); ?>:</b>
<?php echo CHtml::encode($data->count); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('grade')); ?>:</b>
<?php echo CHtml::encode($data->grade); ?>
<br />
*/ ?>
</div><file_sep>/protected/views/tshops/admin.php
<?php
/* @var $this TshopsController */
/* @var $model Tshops */
$this->breadcrumbs=array(
'外卖商家信息列表'=>array('index'),
'外卖商家管理列表',
);
?>
<a class="btn btn-primary " href="<?php echo Yii::app()->createUrl('tshops/create')?>">添加新外卖商家</a>
<br>
<br>
<?php
$this->widget('ext.mylib.NGridView',$options);
?>
<file_sep>/protected/views/tshops/_search.php
<?php
/* @var $this TshopsController */
/* @var $model Tshops */
/* @var $form CActiveForm */
?>
<div class="wide form">
<?php $form=$this->beginWidget('CActiveForm', array(
'action'=>Yii::app()->createUrl($this->route),
'method'=>'get',
)); ?>
<div class="row">
<?php echo $form->label($model,'id'); ?>
<?php echo $form->textField($model,'id'); ?>
</div>
<div class="row">
<?php echo $form->label($model,'name'); ?>
<?php echo $form->textField($model,'name',array('size'=>40,'maxlength'=>40)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'short'); ?>
<?php echo $form->textField($model,'short',array('size'=>20,'maxlength'=>20)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'slogan'); ?>
<?php echo $form->textField($model,'slogan',array('size'=>60,'maxlength'=>80)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'meal_time'); ?>
<?php echo $form->textField($model,'meal_time',array('size'=>40,'maxlength'=>40)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'speed'); ?>
<?php echo $form->textField($model,'speed',array('size'=>20,'maxlength'=>20)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'brief'); ?>
<?php echo $form->textArea($model,'brief',array('rows'=>6, 'cols'=>50)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'remark'); ?>
<?php echo $form->textField($model,'remark',array('size'=>60,'maxlength'=>100)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'tels'); ?>
<?php echo $form->textField($model,'tels',array('size'=>60,'maxlength'=>100)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'ps'); ?>
<?php echo $form->textField($model,'ps',array('size'=>60,'maxlength'=>100)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'count'); ?>
<?php echo $form->textField($model,'count'); ?>
</div>
<div class="row">
<?php echo $form->label($model,'grade'); ?>
<?php echo $form->textField($model,'grade'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Search'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- search-form --><file_sep>/protected/views/sutuo/create.php
<?php
/* @var $this SutuoController */
/* @var $model Sutuo */
$this->breadcrumbs=array(
'素拓管理'=>array('admin'),
'添加',
);
$this->menu=array(
array('label'=>'添加素拓管理', 'url'=>Yii::app()->createUrl('sutuo/admin'),),
array('label'=>'添加素拓活动', 'url'=>Yii::app()->createUrl('sutuo/create'),'active'=>true),
);
?>
<?php echo $this->renderPartial('_form', array('model'=>$model)); ?><file_sep>/protected/controllers/app/ActivitiesAction.php
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of GameAction
*
* @author Administrator
*/
class ActivitiesAction extends StageAction{
//put your code here
public $type;
public function run($type=null) {
$this->type = $type;
// var_dump($this->tags);
$this->setCustomTags(array(
'thisweek',
'nextweek',
'future',
),'<onlyone>');
$this->controller->render('activities');
}
public function tagThisweek(){
$thisweek = $this->getWeek();
$date = date('Y-m-d');
if(!isset($this->type))
$condition = "t.`week` like '%$thisweek%'and t.`end`>='$date'";
else $condition = "t.`week` like '%$thisweek%' and t.`module`=$this->type and t.`end`>='$date'";
$criteria = array(
'model'=>'Sutuo',
'criteria'=>array(
'order'=>'t.`end`',
'condition'=>$condition,
),
);
$html = NDataAction::insertDatasByTags($criteria);
if($html=='') $html = '<li>无数据!</li>';
return $html;
}
public function thisweekData($d){
$end = substr($d['end'], '5',6);
$d['end'] = str_replace('-', '/', $end);
return $d;
}
public function tagNextweek(){
$thisweek = $this->getWeek()+1;
$date = date('Y-m-d');
if(!isset($this->type))
$condition = "t.`week` like '%$thisweek%'and t.`end`>='$date'";
else $condition = "t.`week` like '%$thisweek%' and t.`module`=$this->type and t.`end`>='$date'";
$criteria = array(
'model'=>'Sutuo',
'criteria'=>array(
'order'=>'t.`end`',
'condition'=>$condition,
),
);
$html = NDataAction::insertDatasByTags($criteria);
if($html=='') $html = '<li>无数据!</li>';
return $html;
}
public function nextweekData($d){
return $this->thisweekData($d);
}
public function tagFuture(){
$week = $this->getWeek()+2;
$future = $this->getDateByWeek($week);
$date = date('Y-m-d');
if(!isset($this->type))
$condition = "t.`end` > '$future' ";
else $condition = "t.`end`>'$future' and t.`module`=$this->type ";
$criteria = array(
'model'=>'Sutuo',
'criteria'=>array(
'order'=>'t.`end`',
'condition'=>$condition,
),
);
$html = NDataAction::insertDatasByTags($criteria);
if($html=='') $html = '<li>无数据!</li>';
return $html;
}
public function futureData($d){
return $this->thisweekData($d);
}
}
?>
<file_sep>/protected/views/tshops/index.php
<?php
/* @var $this TshopsController */
/* @var $dataProvider CActiveDataProvider */
$this->breadcrumbs=array(
'外卖商家列表',
);
?>
<style>
#takeout a{text-decoration: none;}
#takeout p{line-height: 13px;}
</style>
<div id = "takeout" >
<n:merchant>
<a class = "list s-open pt5" href="$url">
<div class = "info" >
<p class = "name">$short</p>
<p class = "intro" >$slogan</p>
<p class = "intro">
<span class = "level">
<b class = "complete" ></b><!--
--><b class = "complete" ></b><!--
--><b class = "half" ></b><!--
--><b></b><!--
--><b></b>
</span>共$count种菜式
</p>
</div>
</a>
</n:merchant>
</div><file_sep>/protected/controllers/app/ActivitiespAction.php
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of GameAction
*
* @author Administrator
*/
class ActivitiespAction extends StageAction{
//put your code here
public function run() {
// var_dump($this->tags);
$this->setCustomTags(array(
'info',
),'<onlyone>');
$this->setCustomTags(array(
'tags',
),'[]');
$this->controller->render('activities_p');
}
public function tagInfo(){
$criteria = array(
'model'=>'Sutuo',
'all'=>'true',
'criteria'=>array(
'condition'=>"t.`id` = {$_GET['id']}",
),
);
return NDataAction::insertDatasByTags($criteria);
}
public function infoData($d){
$d['end'] = substr($d['begin'], 0,9).' 至 '.substr($d['end'], 0,9);
return $d;
}
public function tagTags(){
$m = $this->getTagContents('tags');
if(!empty($m)){
$html = "";
$model = Sutuo::model()->findByPk($_GET['id']);
$tags = explode('-',$model->tag);
foreach($tags as $t){
$html .= Yii::t('nan',$m[0],array(
'$mtags'=>$t,
));
}
return $html;
}
}
}
?>
<file_sep>/protected/views/app/activities.php
<header id="top" >
<a id = "back" href="javascript:history.go(-1);">返回</a>
<div id = "title" class = "span1" >素拓活动</div>
<a id = "home" href="<?php echo Yii::app()->request->baseUrl; ?>/">首页</a>
</header>
<nav id = "nav" class = "clearfix">
<a class="current" ><span>活动</span></a>
<a href = "{$createUrl(app/apply)}" ><span>可申请</span></a>
<a href = "{$createUrl(app/apply)}" ><span>机构协会</span></a>
</nav>
<div class = "flexbox" style="margin:0 10px 10px;" >
<div class="sort span1 flexbox" >
<a class="span1 selected">全部</a>
<a class="span1" href="{$createUrl(app/activities?type=0)}">学术科技</a>
<a class="span1" href="{$createUrl(app/activities?type=1)}">文化体育</a>
<a class="span1" href="{$createUrl(app/activities?type=2)}">社会实践</a>
</div>
<div class="search flexbox" >
<p class="span1" ><input type="text" /></p>
<a class="icon-search"></a>
</div>
</div>
<!--<ul class = "form-list" >
<li class = "rarr" >
<span>期限</span>
<span class = "form-list-val j_s_val">未过期</span>
<select class = "j_sel" data-key = "limit" >
<option value="2" selected >未过期</option>
<option value="1">已过期</option>
<option value="0">全部</option>
</select>
</li>
<li class = "rarr" >
<span>模块</span>
<span class = "form-list-val j_s_val">全部</span>
<select class = "j_sel" data-key = "type" >
<option value="0" selected >全部</option>
<option value="1">学术科技与专业技能</option>
<option value="2">文化艺术与体育竞技</option>
<option value="3">社会实践与志愿服务</option>
</select>
</li>
<li><a class = "form-btn" >立即筛选</a></li>
</ul>-->
<section id = "chain" >
<div class="chain-nodes ">
<h2>本周<i class="alarm"></i></h2>
<ul>
<n:thisweek>
<li>
<a href = "{$createUrl(app/activities_p?id=$id)}">$name</a>
<span>$end</span>
</li>
</n:thisweek>
</ul>
</div>
<div class="chain-nodes ">
<h2>下周<i class="alarm"></i></h2>
<ul>
<n:nextweek>
<li>
<a href = "{$createUrl(app/activities_p?id=$id)}">$name</a>
<span>$end</span>
</li>
</n:nextweek>
</ul>
</div>
<div class="chain-nodes ">
<h2>未来<i class="alarm"></i></h2>
<ul>
<n:future>
<li>
<a href = "{$createUrl(app/activities_p?id=$id)}">$name</a>
<span>$end</span>
</li>
</n:future>
</ul>
</div>
</section>
<div id = "search-page" >
<div id = "search-header" >
<a class = "larr" ></a>
搜索
</div>
<div id = "search-bar" class = "flexbox">
<p class = "span1" ><input type = "text" /></p>
<a>搜索</a>
</div>
</div>
<script>
//var div = document.getElementsByTagName("ul");
var div = document.querySelector(".chain-nodes:last-child ul"),
//搜索页面相关
search = document.querySelector( ".search" ),
turnBack = document.querySelector( "#search-header .larr" ),
sInput = document.querySelector( "#search-bar input" ),
sPage = document.getElementById( "search-page" );
window.onscroll = function (){
var d = window.innerHeight;
var h = document.body.scrollHeight;
var t = document.body.scrollTop;
var li = div.getElementsByTagName("li")[0].cloneNode();
if( (h-d) == t ){
div.appendChild(li);
$.ajax({
url : "<?php echo Yii::app()->request->baseUrl; ?>/test/web.php?para=说话",
type : "post",
dataType : "json",
data : {
a : "saddsa",
b : 1,
c : [ 1, "haha"],
d : function(){
alert(777);
}
}
});
}else{
console.log(d+"--"+h+"--"+t);
}
}
search.onclick = function() {
//sPage.setAttribute( "style", "z-index : 999;opacity:1;" );
sPage.setAttribute( "style", "display:block;z-index:999;" );
sInput.focus();
document.getElementById("page").setAttribute( "style", "overflow:hidden;height:"+window.innerHeight+"px;" );
//document.getElementsByTagName( "html" )[0].setAttribute( "style", "overflow:hidden;height:"+window.innerHeight+"px;" );
}
turnBack.onclick = function() {
//sPage.setAttribute( "style", "z-index : -99;opacity:0;" );
document.getElementById("page").setAttribute( "style", "" );
sPage.setAttribute( "style", "display:none;z-index:-99;" );
}
function Jlist (){
}
Jlist.prototype = {
init : function(){
this.deal();
this.change();
},
// 绑定提交事件
deal : function(){
var ul = document.getElementsByClassName("form-list"),
len = ul.length;
for( var i = 0; i < len; i++ ){
var btn = ul[i].getElementsByClassName("form-btn");
btn[0].onclick = function(){
var sel = this.parentNode.parentNode.getElementsByClassName("j_sel"),
val = [];
for( var i = 0; i < sel.length; i++ ){
val.push( sel[i].getAttribute( "data-key" ) +"="+sel[i].value );
}
console.log( val.join("&") +"---"+ window.location.href);
window.location.href += "?"+val.join("&");
};
}
btn = null;
},
// 选项更改事件
change : function(){
var sel = document.getElementsByClassName("j_sel"),
span = document.getElementsByClassName("j_s_val");
if( sel.length == span.length ){
for ( var i = 0; i < sel.length; i++){
(function(j){
sel[j].onchange = function(){
span[j].innerText = this.options[this.selectedIndex].text;
}
})(i);
}
} else {
console.log("错误;select和span数目不一致!!");
}
}
}
var mylist = new Jlist();
mylist.init();
</script><file_sep>/protected/views/app/activities_p.php
<n:info>
<header id="top" >
<a id = "back" href="javascript:history.go(-1);">返回</a>
<div id = "title" class = "span1" >$name活动详情</div>
<a id = "home" href="<?php echo Yii::app()->request->baseUrl; ?>">首页</a>
</header>
<section>
<h1 class = "type1">$name</h1>
<a id = "author" class = "rarr" >口袋广油开发团队</a>
<ul id = "content" >
<li>
<div class="span1"><span>时间:</span>$end</div>
<div class="span1"><span>性质:</span>$level</div>
</li>
<li>
<div class="span1"><span>对象:</span>$object</div>
<div class="span1"><span>学分:</span>$score</div>
</li>
<li>
<div><span>地点:</span>$address</div></li>
<li>
<div class = "clearfix">
<span style = "float:left;">标签:</span>
[n:tags]
<i>$mtags</i>
[/n:tags]
</div>
</li>
<li>
<div>
<span>活动描述:</span>
<div class = "detail">
$brief
</div>
</li>
<li>
<div>
<span>联系方式:</span>
<div class = "detail">$cornet</div>
</div>
</li>
<li>
<div>
<span>备注:</span>
<div class = "detail">$remark</div>
</div>
</li>
</ul>
</section>
</n:info>
<script>
(function(){
var tags = document.getElementsByTagName("i"),
color = [
"#99CCFF",
[ "#FFFF66", "#000" ],
"#666666",
"#999999",
"#99CC33",
"#FF9900",
[ "#CCFF66", "#000" ],
"#990033",
"#CC99CC",
"#CC3399",
"#000000",
"#CC0033",
"#003399"
];
for( var i = 0; i < tags.length; i++ ) {
var random = Math.floor( color.length * Math.random() ),
style = "";
style = ( typeof color[ random ] === "string" )? "background-color:" +color[ random ]: "background-color:" +color[ random ][0] +";color:" +color[ random ][1];
tags[i].setAttribute( "style", style );
console.log( random );
}
})();
</script>
<file_sep>/js/lib.js
var $ = {};
if(!$){
$ = {};
}
else if(typeof $ != 'object'){
throw new Error('$ already exists and is not an object!');
}
$.trim = function(str) {
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
/* 判断标签是否含有指定的类名 */
$.hasClass = function(obj, value){
if(obj && obj.nodeType===1 && (' ' + obj.className + ' ').replace(/[\n\t\r]/g, ' ').indexOf(' ' + value + ' ')>-1){
return true;
}
return false;
};
/* 添加类名 */
$.addClass = function(obj, value){
if(value && typeof(value)==='string'){
var cs = value.split(/\s+/);
if(obj && obj.nodeType===1){
if(!obj.className && cs.length===1){
obj.className = value;
}
else{
var dc = ' ' + obj.className + ' ';
for(var i=0, l=cs.length; i<l; i++){
if(!~dc.indexOf(' ' + cs[i] + ' ')){
dc += cs[i] + ' ';
}
}
obj.className = $.trim(dc);
}
}
}
};
/* 移除类名 */
$.removeClass = function(obj, value){
if((value && typeof(value)==='string') || value===undefined){
var cs = (value || '').split(/\s+/);
if(obj && obj.nodeType===1 && obj.className){
if(value){
var dc = (' ' + obj.className + ' ').replace(/[\n\t\r]/g, ' ');
for(var i=0, l=cs.length; i<l; i++){
dc = dc.replace(' ' + cs[i] + ' ', ' ');
}
obj.className = $.trim(dc);
}
else{
obj.className = '';
}
}
}
};
/* ajax */
$.xhr = new XMLHttpRequest();
/*
* // 该函数IE7以下不适用
*
* op参数 :{
* * url : String
* type : [ "get" | "post" ]
* dataType : [ "text" | "json" ]
* data : [ String | Object ]
* success : Function()
* }
*
*/
$.ajax = function( op ){
var xhr = this.xhr,
dataType = op.dataType,
type = op.type;
if( typeof op.url === "undefined" ) return false;
if( typeof dataType === "undefined" ){
dataType = "text";
} else if( dataType.toLowerCase() === "json" ) {
op.data = JSON.stringify( op.data );
}
if ( type.toLowerCase() === "post" && !(typeof type === "undefined") ) {
xhr.open( type, op.url, true );
xhr.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
xhr.send( op.data );
} else {
type = "get";
xhr.open( type, op.url, true );
xhr.send();
}
xhr.onreadystatechange = function (){
if ( xhr.readyState==4 && xhr.status==200 ) {
if( typeof op.success == "function" ) {
op.success( xhr.responseText );
}
}
}
}
| 6b0c91d42a5596db5a471211b304c7548da684ce | [
"JavaScript",
"PHP",
"INI"
] | 43 | PHP | pocketu/pocket | 18535291cff1de1b566a24d04d69fcc793190fb3 | 3f8fae957ed3f112ad26458e94d99a0b548ce53e |
refs/heads/master | <repo_name>scalpovich/lara-framework<file_sep>/app/Http/Controllers/UserController.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Users\Biodata;
use App\Users\Role;
use App\Users\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Intervention\Image\Facades\Image;
class UserController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
$this->middleware('can:manage-user', ['except' => ['profile', 'update', 'changePassword', 'updatePassword']]);
}
public function profile($username = null)
{
$user = Auth::user();
if ($username == null)
$profile = $user->load('biodata');
else
$profile = User::with('biodata')
->where('username', $username)->first();
if ($profile)
return view('user.profile', compact('profile', 'user'));
else
return abort('404');
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
* @internal param User $user
* @internal param int $id
*/
public function update(Request $request)
{
$user = Auth::user();
//update table user
$this->validate($request, User::getRules(['email' => $user->id, 'username' => $user->id]));
$user->update($request->all());
//update table biodata
$this->validate($request, Biodata::getRules());
if ($request->file('avatar-file') && $request->file('avatar-file')->isValid()) {
$img = Image::make($request->file('avatar-file'));
$img->resize(200, 200, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$img->resizeCanvas(200, 200);
$img->save("images/user/$user->id.jpg");
$user->biodata->avatar = "/images/user/$user->id.jpg";
} elseif ($request->file('avatar'))
$user->biodata->avatar = $request->file('avatar');
$user->biodata->update(array_merge([
'birthday' => Carbon::create($request->input('bday_yy'), $request->input('bday_mm'), $request->input('bday_dd'))], $request->only([
'nama',
'no_telp',
'jenis_kelamin',
'bio'
])));
flash('Profil kamu berhasil diubah!', 'Selesai');
return back();
}
public function changePassword()
{
$user = Auth::user();
return view('user.password', compact('user'));
}
public function updatePassword(Request $request)
{
$this->validate($request, ['password_new' => '<PASSWORD>|min:8', 'password' => '<PASSWORD>']);
$user = Auth::user();
if (!Hash::check($request->input('password'), $user->getAuthPassword())) {
flash("Password yang anda masukkan salah!", 'Peringatan', 'danger');
} else if (!Hash::check($request->input('password_new'), $user->getAuthPassword())) {
flash("Password kamu sudah diubah");
$user->password = <PASSWORD>($request->input('password_new'));
$user->save();
} else
flash('Maaf, password yang kamu masukkan sama dengan sebelumnya!', 'Gagal!', 'info');
return back();
}
//ADMIN
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$user = Auth::user();
return view('user.index', compact('user'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
}
public function admin()
{
$user = Auth::user();
return view('user.admins', compact('user'));
}
/**
* Jadikan sebagai role
*
* @param User $user
* @param $role
* @return \Illuminate\Http\Response
* @internal param Request $request
* @internal param int $id
*/
public function attachRole(User $user, $role)
{
$admin = Auth::user();
if (!$role = Role::getId($role))
flash('Role tidak ditemukan!');
else if (!$user->roles()->find($role) && $role >= $admin->roles[0]->id) {
$user->roles()->attach($role);
flash('Berhasil!');
} else
flash('Anda tidak punya wewenang!', 'Peringatan', 'danger');
return back();
}
/**
* Pecat role user
*
* @param User $user
* @param $role
* @return \Illuminate\Http\Response
* @internal param Request $request
* @internal param int $id
*/
public function detachRole(User $user, $role)
{
$admin = Auth::user();
if (!$role = Role::getId($role))
flash('Role tidak ditemukan!');
else if ($user->roles()->find($role) && $role > $admin->roles[0]->id &&
(!$user->hasRole('webmaster') || $admin->hasRole('webmaster'))
) {
$user->roles()->detach($role);
flash('Berhasil!');
} else
flash('Anda tidak punya wewenang!', 'Peringatan', 'danger');
return back();
}
/**
* Ban user
*
* @param User $user
* @return \Illuminate\Http\Response
* @internal param int $id
*/
public function destroy(User $user)
{
if (!$user->roles()->find(Role::getId('admin')) && !$user->roles()->find(Role::getId('webmaster'))) {
$user->updateStatus(-1);
flash('User berhasil di blokir');
} else
flash('Admin tidak bisa di blokir! Anda tidak punya wewenang!', 'Peringatan!', 'danger');
return back();
}
/**
* Unban user
*
* @param User $user
* @return \Illuminate\Http\Response
* @internal param User $user
* @internal param int $id
*/
public function unDestroy(User $user)
{
if ($user->status == -1)
$user->updateStatus(1);
return back();
}
//API
/**
* @param Request $request
* @param string $role
* @return mixed
*/
public function api(Request $request, $role = 'all')
{
$filters = explode(' ', trim($request->get('filter')));
$users = User::with('biodata', 'roles')
->join('biodatas', 'biodatas.id', '=', 'users.id')
->select('username', 'email', 'users.id', 'users.created_at', 'biodatas.nama', 'status')
->when($request->get('sort'), function ($query) use ($request) {
$sort = explode('|', $request->get('sort'));
return $query->orderBy($sort[0], $sort[1]);
})->when($role == 'all', function ($query) {
return $query->join('role_user', function ($join) {
$join->on('role_user.user_id', '=', 'users.id')
->where('role_user.role_id', '=', Role::getId('user'));
});
})->when($role != 'all', function ($query) use ($role) {
return $query->join('role_user', function ($join) use ($role) {
$join->on('role_user.user_id', '=', 'users.id')
->where('role_user.role_id', '=', Role::getId($role));
});
})->when($request->get('filter'), function ($query) use ($filters) {
foreach ($filters as $like) {
$query->where(function ($query) use ($like) {
$query->where('biodatas.nama', 'like', "%$like%")
->orWhere('users.username', 'like', "%$like%")
->orWhere('users.email', 'like', "%$like%");
});
}
return $query;
})
// ->toSql();
->paginate($request->get('per_page', 15));
// dd($users);
return $users;
}
}
<file_sep>/database/migrations/2016_08_26_202525_create_alamats_table.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAlamatsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::create('alamats', function (Blueprint $table) {
$table->increments('id');
$table->string('negara', 4)->default('id');
$table->string('nama_alamat', 40);
$table->string('provinsi', 2);
$table->string('kota', 4);
$table->string('kecamatan', 7);
$table->string('alamat');
$table->string('nama_penerima', 40);
$table->string('no_telp', 20);
$table->string('kode_pos', 10);
$table->text('keterangan');
$table->integer('defaulted_to_user_id')->unsigned()->nullable()->unique();
$table->foreign('defaulted_to_user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::drop('alamats');
}
}
<file_sep>/app/Statusable.php
<?php
namespace App;
trait Statusable
{
/**
* @return mixed
*/
public function getStatus()
{
return self::$status_list[$this->status];
}
/**
* @param string $id_status
* @return bool
*/
public function updateStatus($id_status = 'next')
{
if ($id_status == 'next') {
if ($this->status < max(array_keys(self::$status_list)))
$this->status++;
else
return false;
} else if ($id_status == 'fail') {
$this->status *= -1;
} else {
if (self::$status_list[$id_status] != null)
$this->status = $id_status;
else
return false;
}
return $this->save();
}
/**
* @param $stat
* @return bool
*/
public function isStatus($stat)
{
return $stat == self::$status_list[$this->status];
}
public static function statusId($string)
{
return array_search($string, self::$status_list);
}
}<file_sep>/app/Http/Controllers/MenuController.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Menu;
use App\Users\Role;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class MenuController extends Controller
{
/**
* Create a new controller instance.
*
*/
public function __construct()
{
$this->middleware('auth');
$this->middleware('can:access-menu');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$menus = Menu::getMenus('sidebar-admin');
$targets = Menu::select('module_target')->distinct()->get();
$user = Auth::user();
return view('menu.index', compact('menus', 'targets', 'user'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$user = Auth::user();
return view('menu.create', compact('user'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, Menu::getRules());
$menu = Menu::create($request->all());
$this->attachRole($request, $menu);
return redirect('admin/menu');
}
/**
* @param $request
* @param Menu $menu
*/
private function attachRole($request, Menu $menu)
{
$to_attach = $request->only(Role::getNames());
$menu->roles()->detach();
foreach ($to_attach as $key => $value)
if ($value != null)
$menu->roles()->attach($value);
}
/**
* Show the form for editing the specified resource.
*
* @param Menu $menu
* @return \Illuminate\Http\Response
*/
public function edit(Menu $menu)
{
$user = Auth::user();
return view('menu.edit', compact('menu', 'user'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param Menu $menu
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Menu $menu)
{
$this->validate($request, Menu::getRules());
$menu->update($request->all());
$this->attachRole($request, $menu);
return redirect('admin/menu');
}
/**
* Remove the specified resource from storage.
*
* @param Menu $menu
* @return \Illuminate\Http\Response
*/
public function destroy(Menu $menu)
{
$menu->delete();
return redirect('admin/menu');
}
public function menuList($module)
{
$menus = Menu::getMenus($module);
return view('menu.editlist', compact('menus'));
}
}
<file_sep>/app/Users/Alamat.php
<?php
namespace App\Users;
use App\Http\Utilities\Region;
use App\Validator;
use Illuminate\Database\Eloquent\Model;
class Alamat extends Model
{
use Validator;
private static $rules = [
'nama_alamat' => 'required|max:40',
'alamat' => 'required',
'no_telp' => 'required',
'nama_penerima' => 'required'
];
protected $fillable = [
'nama_alamat', 'nama_penerima', 'no_telp', 'negara', 'provinsi', 'kota', 'kecamatan', 'alamat', 'kode_pos', 'keterangan'
];
protected $appends = array('district', 'city', 'province');
public function getDistrictAttribute()
{
return Region::district($this->kecamatan);
}
public function getCityAttribute()
{
return Region::city($this->kota);
}
public function getProvinceAttribute()
{
return Region::province($this->provinsi);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
<file_sep>/app/Http/Utilities/Region.php
<?php
namespace App\Http\Utilities;
class Region
{
use DataRegion;
public static function countries()
{
return static::$countries;
}
public static function json_countries()
{
return json_encode(
array_map(function ($key, $value) {
return ['label' => $key, 'value' => $value];
}, static::$countries));
}
public static function provinces()
{
$p = [];
foreach (static::$provinces as $array) {
$p[$array['label']] = $array['value'];
}
return $p;
}
public static function json_provinces()
{
return json_encode(static::$provinces);
}
public static function cities($p_id = 0)
{
$r = [];
foreach (static::$cities as $array) {
if ($array['p_id'] == $p_id)
$r[$array['label']] = $array['value'];
}
return $r;
}
public static function json_cities($p_id = 0)
{
$r = [];
foreach (static::$cities as $array) {
if ($array['p_id'] == $p_id)
$r[] = $array;
}
return json_encode($r);
}
public static function districts($k_id = 0)
{
$r = [];
foreach (static::$districts as $array) {
if ($array['k_id'] == $k_id)
$r[$array['label']] = $array['value'];
}
return $r;
}
public static function json_districts($k_id = 0)
{
$r = [];
foreach (static::$districts as $array) {
if ($array['k_id'] == $k_id)
$r[] = $array;
}
return json_encode($r);
}
public static function district($district_id)
{
$key = array_search($district_id, array_column(static::$districts, 'value'), true);
if ($key !== false)
return static::$districts[$key]['label'];
return false;
}
public static function city($city_id)
{
$key = array_search($city_id, array_column(static::$cities, 'value'), true);
if ($key !== false)
return static::$cities[$key]['label'];
return false;
}
public static function province($province_id)
{
$key = array_search($province_id, array_column(static::$provinces, 'value'), true);
if ($key !== false)
return static::$provinces[$key]['label'];
return false;
}
public static function country($country_id)
{
$key = array_search($country_id, static::$countries, true);
return $key !== null ? $key : false;
}
}<file_sep>/database/seeds/SettingTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class SettingTableSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run() {
$settings = [
[
'module' => 'global',
'name' => 'app_title',
'placeholder' => 'e.g. LaraFrame',
'label' => 'Nama Aplikasi',
'type' => 'string',
'string' => 'LaraFrame'
],
[
'module' => 'global',
'name' => 'app_motto',
'placeholder' => 'e.g. Best App Framework',
'label' => 'Motto Aplikasi',
'type' => 'string',
'string' => 'Best App Framework'
],
[
'module' => 'template',
'name' => 'tmp_skin',
'placeholder' => 'blue / red / green / black / purple / yellow',
'label' => 'Skin Color',
'type' => 'string',
'string' => 'blue'
],
[
'module' => 'template',
'name' => 'tmp_color',
'placeholder' => 'primary / danger / info / default',
'label' => 'Modal Colors',
'type' => 'string',
'string' => 'primary'
],
[
'module' => 'json',
'name' => 'banners',
'placeholder' => '[]',
'label' => 'Banners JSON',
'type' => 'text',
'boot' => false,
'text' => "[
{
label: 'Carousel Home',
name: 'carousel',
width: 1500,
height: 500,
variants: [1, 2, 3, 4, 5, 6],
location: 'images/banner/home/'
},
{
label: 'Mini Banner Home',
name: 'mini',
width: 470,
height: 250,
variants: [1, 2, 3],
location: 'images/banner/'
},
{
label: 'Logo APP',
name: 'logo',
width: null,
height: null,
variants: null,
location: 'images/'
}
]"
]
];
foreach ($settings as $setting) {
factory(\App\Setting::class)->create($setting);
}
}
}
<file_sep>/app/Validator.php
<?php
namespace App;
trait Validator
{
private $errors;
public static function getRules(array $unique = null)
{
if($unique){
$rules = [];
foreach ($unique as $key => $rule){
$rules[$key] = self::$rules[$key] . "," . $rule;
}
return array_merge(self::$rules, $rules);
}
return self::$rules;
}
public function validate($request)
{
$v = Validator::make($request, static::rules);
if ($v->fails()) {
$this->errors = $v->errors;
return false;
}
return true;
}
public function errors()
{
return $this->errors;
}
}<file_sep>/database/seeds/MenuTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class MenuTableSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run() {
$menus = [
[
'module_target' => 'sidebar-admin',
'position' => '0',
'body' => 'Main Navigation',
'type' => 'separator'
],
[
'module_target' => 'sidebar-admin',
'position' => '1',
'icon' => 'home',
'name' => 'dashboard',
'uri' => 'admin',
'title' => 'Go to Dashboard',
'body' => 'Dashboard'
],
[
'module_target' => 'sidebar-admin',
'position' => '5.1',
'icon' => 'group',
'name' => 'user',
'uri' => 'admin/user',
'title' => 'User Management',
'body' => 'Users'
],
[
'module_target' => 'sidebar-admin',
'position' => '9',
'body' => 'Settings',
'type' => 'separator'
],
[
'module_target' => 'sidebar-admin',
'position' => '9.1',
'name' => 'setting',
'icon' => 'gear',
'uri' => '',
'title' => 'Pengaturan Website',
'body' => 'Pengaturan',
'type' => 'parent'
],
[
'module_target' => 'sidebar-admin',
'position' => '9.2',
'name' => 'menu',
'icon' => 'bars',
'uri' => 'admin/menu',
'title' => 'Pengaturan Menu',
'body' => 'Menus'
],
[
'module_target' => 'sidebar-admin',
'position' => '9.3',
'icon' => 'key',
'name' => 'permission',
'uri' => 'admin/permission',
'title' => 'Roles & Permissions',
'body' => 'Permissions'
],
[
'module_target' => 'sidebar-admin',
'position' => '9.1-1',
'name' => 'setting',
'icon' => '',
'uri' => 'admin/setting/global/update',
'title' => 'Pengaturan Global',
'body' => 'Global'
]
];
for ($i = 0; $i < count($menus); $i++) {
$menus[$i] = factory(\App\Menu::class)->create($menus[$i]);
}
$menus[0]->roles()->attach(3);
$menus[1]->roles()->attach(3);
$menus[2]->roles()->attach(2);
$menus[3]->roles()->attach(2);
$menus[4]->roles()->attach(2);
$menus[5]->roles()->attach(1);
$menus[6]->roles()->attach(1);
$menus[7]->roles()->attach(1);
}
}
<file_sep>/app/Users/Biodata.php
<?php
namespace App\Users;
use App\Validator;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
class Biodata extends Model
{
use Validator;
protected static $rules = [
'nama' => 'required|max:200',
'no_telp' => 'required|max:20',
'bday_dd' => 'max:2',
'bday_mm' => 'max:2',
'bday_yy' => 'max:4',
'jenis_kelamin' => 'max:1',
'avatar' => 'max:200'
];
protected $appends = ['age'];
protected $dates = ['birthday'];
protected $fillable = [
'nama', 'no_telp', 'birthday', 'jenis_kelamin', 'bio', 'avatar'
];
public function getAgeAttribute()
{
return $this->birthday->diffInYears();
}
public function user()
{
return $this->belongsTo(User::class, 'id');
}
}<file_sep>/app/Users/User.php
<?php
namespace App\Users;
use App\Menu;
use App\Statusable;
use App\Validator;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Validator;
use Statusable;
use HasRoles;
protected static $rules = [
'username' => 'required|unique:users,username',
'email' => 'required|unique:users,email',
];
protected static $status_list = [
0 => 'recently created',
1 => 'completed',
2 => 'verified',
-1 => 'banned'
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'username', 'email', 'password', '<PASSWORD>_id'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
//Relations
public function alamats()
{
return $this->hasMany(Alamat::class);
}
public function alamat()
{
return $this->hasOne(Alamat::class, 'defaulted_to_user_id');
}
public function biodata()
{
return $this->hasOne(Biodata::class, 'id');
}
//Operations
public function menus($module_target = null)
{
return Menu::when($module_target, function ($query) use ($module_target) {
return $query->where('module_target', $module_target);
})->whereHas('roles', function ($query) {
$query->whereIn('id', $this->roles()->lists('id'));
})->orderBy('position')->get();
}
public function setDefaultAlamat($id)
{
if ($this->alamat && $id != $this->alamat->id && $alamat = $this->alamats()->find($id)) {
$this->alamat()->dissociate();
$this->alamat->save();
return $this->alamat()->save($alamat);
}
return false;
}
public function addAlamat($alamat)
{
if (is_array($alamat)) {
$alamat = $this->alamats()->create($alamat);
} else {
$alamat = $this->alamats()->save($alamat);
}
if ($this->alamat == null) {
$this->alamat()->save($alamat);
}
return $alamat;
}
public function completeData($array)
{
$this->kelas = $array['kelas'];
$this->sekolah = $array['sekolah'];
$this->grade()->associate($array['grade_id']);
$this->wilayah()->associate($array['wilayah_id']);
$this->status = 1;
$this->save();
}
}<file_sep>/readme.md
#LaraFrame is a laravel quickstart.
Using <a href="https://laravel.com">laravel</a>, <a href="https://getbootstrap.com">bootstrap</a>, <a href="https://vuejs.org">vueJS</a> and an admin template (for now its <a href="https://almsaeedstudio.com">admin LTE</a>), we create a base for creating web apps.
### The features on LaraFrame are:
+ User with dynamic roles and permission.
+ Menu management for sidebar and also customizable for other components
+ Menu access for each roles are managable
+ User Management
+ Dynamic settings and easily customizable
### Prerequisite:
+ Environment for <a href="https://laravel.com/docs/5.2/#server-requirements">laravel 5.2 </a> (PHP >= 5.5.9, ..)
+ PHP <a href="https://getcomposer.org">Composer</a> installed
+ Also <a href="https://nodejs.org/en/download">npm latest version</a> (npm v3.8.x and node 6.x.x) *optional
### Installation:
1. Prepare a database, can be mysql, sqlite, etc.
2. Create `/.env` file and also `/config/database.php` file
3. do composer install
```
composer install
```
4. For security, generate key using
```
php artisan key:generate
```
5. Edit .env and config/database.php based on your database setting.
6. Use php artisan migrate to create database tables and also `--seed` for the dummy data.
```
php artisan migrate --seed
```
7. load the javascript node libraries using npm install
```
npm install
```
this is optional. if you don't really use node for development and only use plain javascript you may skip these.
8. Serve your lara-frame on http://localhost:8000
```
php artisan serve
```
9. Username and password for each roles are:
+ Webmaster : <EMAIL> / password
+ Admin : <EMAIL> / password
<file_sep>/app/Http/Controllers/AdminController.php
<?php
namespace App\Http\Controllers;
use App\Setting;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Auth;
use Intervention\Image\Facades\Image;
class AdminController extends Controller
{
public function __construct()
{
$this->middleware('can:view-dashboard');
}
public function index()
{
$user = Auth::user();
$banners = Setting::where('name', 'banners')->first();
return view('home', compact('user', 'banners'));
}
public function uploadImage(Request $request)
{
$this->authorize('change-banner');
/* * Todo
* Buat file uploader yang otomatis resize, rename, watermark, sesuai dengan setting yang diupload pengguna.
* */
if ($request->file('image')->isValid()) {
$img = Image::make($request->file('image'));
$img->resize($request->input('width', 300), $request->input('height', null), function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
if ($img->save($request->input('path', 'images/uploads'). '/' .$request->input('name'))) {
flash('Upload sukses!', 'Berhasil!');
} else
flash('Maaf, image gagal diupload.', 'Upload gagal!', 'info');
} else
flash('Maaf, image yang diupload tidak sesuai', 'Upload gagal!', 'info');
return back();
}
}
<file_sep>/app/Http/Controllers/UtilitiesController.php
<?php
namespace App\Http\Controllers;
use App\Http\Utilities\Region;
use Illuminate\Http\Request;
use App\Http\Requests;
class UtilitiesController extends Controller
{
public function getCities($p_id)
{
return Region::json_cities($p_id);
}
public function getDistricts($k_id)
{
return Region::json_districts($k_id);
}
}
<file_sep>/database/factories/ModelFactory.php
<?php
$factory->define(App\Users\Alamat::class, function (Faker\Generator $faker) {
return [
'negara' => 'id',
'provinsi' => '35',
'kota' => '3507',
'kecamatan' => '3507020',
'alamat' => $faker->address,
'nama_alamat' => $faker->words(2, true),
'nama_penerima' => $faker->name,
'no_telp' => $faker->phoneNumber,
'kode_pos' => $faker->postcode,
'keterangan' => $faker->paragraph
];
});
$factory->define(App\Users\Biodata::class, function (Faker\Generator $faker) {
return [
'nama' => $faker->name,
'no_telp' => $faker->phoneNumber,
'birthday' => $faker->date('Y-m-d', 'now'),
'jenis_kelamin' => $faker->randomElement(['l', 'p']),
'bio' => $faker->paragraph,
'avatar' => 'https://avatars1.githubusercontent.com/u/' . $faker->numberBetween(1, 52233) . '?v=3&s=80',
];
});
$factory->define(\App\Users\User::class, function (Faker\Generator $faker) {
return [
'username' => $faker->userName,
'email' => $faker->safeEmail,
'password' => <PASSWORD>('<PASSWORD>'),
];
});
$factory->define(App\Users\Permission::class, function () {
return [];
});
$factory->define(App\Users\Role::class, function () {
return [];
});
$factory->define(App\Menu::class, function () {
return [];
});
$factory->define(App\Setting::class, function () {
return [];
});<file_sep>/app/Http/Controllers/RoleController.php
<?php
namespace App\Http\Controllers;
use App\Users\Role;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Auth;
class RoleController extends Controller
{
public function __construct()
{
$this->middleware('auth');
$this->middleware('can:access-permission');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$roles = Role::all();
$user = Auth::user();
return view('role.index', compact('roles', 'user'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$user = Auth::user();
return view('role.create', compact('user'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, Role::getRules());
Role::create($request->all());
return redirect('permission/all/edit');
}
/**
* Show the form for editing the specified resource.
*
* @param Role $role
* @return \Illuminate\Http\Response
* @internal param int $id
*/
public function edit(Role $role)
{
$user = Auth::user();
return view('role.edit', compact('role', 'user'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param Role $role
* @return \Illuminate\Http\Response
* @internal param int $id
*/
public function update(Request $request, Role $role)
{
$this->validate($request, Role::getRules());
$role->update($request->all());
return redirect('admin/permission/all/edit');
}
/**
* Remove the specified resource from storage.
*
* @param Role $role
* @return \Illuminate\Http\Response
* @throws \Exception
* @internal param int $id
*/
public function destroy(Role $role)
{
$role->delete();
return redirect('admin/permission/all/edit');
}
}
<file_sep>/database/migrations/2016_08_23_003542_create_menus_table.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMenusTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('menus', function (Blueprint $table) {
$table->increments('id');
$table->string('module_target', 40);
$table->string('position', 8);
$table->string('icon', 25);
$table->string('uri');
$table->string('title', 50);
$table->string('name', 40);
$table->string('body', 40);
$table->string('type', 15)->default('default');
$table->unique(['position', 'module_target']);
$table->timestamps();
});
Schema::create('menu_role', function (Blueprint $table) {
$table->integer('menu_id')->unsigned();
$table->integer('role_id')->unsigned();
$table->foreign('menu_id')
->references('id')
->on('menus')
->onDelete('cascade');
$table->foreign('role_id')
->references('id')
->on('roles')
->onDelete('cascade');
$table->primary(['menu_id', 'role_id']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('menu_role');
Schema::drop('menus');
}
}
<file_sep>/app/Setting.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Setting extends Model
{
use Validator;
protected static $rules = [
'name' => 'required|max:40',
'label' => 'required|max:40',
'type' => 'required|max:40',
'module' => 'required|max:20',
];
protected $fillable = ['name', 'label', 'module', 'type', 'placeholder', 'boot'];
private $validation = [
'number' => 'integer',
'text' => 'text',
'string' => 'text',
'date' => 'date'
];
protected $appends = ['value'];
protected $hidden = ['number', 'text', 'string', 'date'];
public function getValueAttribute()
{
switch ($this->type) {
case 'number':
return $this->number;
case 'text':
return $this->text;
case 'string':
return $this->string;
case 'date':
return $this->date;
default:
return false;
}
}
public function setValue($value)
{
switch ($this->type) {
case 'number':
$this->number = $value;
break;
case 'text':
$this->text = $value;
break;
case 'string':
$this->string = $value;
break;
case 'date':
$this->date = $value;
break;
default :
return false;
}
return $this->save();
}
public function validationType()
{
return $this->validation[$this->type];
}
}<file_sep>/app/Menu.php
<?php
namespace App;
use App\Users\Role;
use Illuminate\Database\Eloquent\Model;
class Menu extends Model
{
use Validator;
protected static $rules = [
'name' => 'required',
'module_target' => 'required|max:40',
'body' => 'required|max:40',
'position' => 'required|max:8',
'type' => 'required|in:default,separator,parent',
];
protected $fillable = ['module_target', 'position', 'icon', 'uri', 'title', 'body', 'type', 'name'];
public static function getMenus($module_target)
{
return Menu::where('module_target', $module_target)
->orderBy('position')->get();
}
public static function getTargets()
{
return Menu::select('module_target')->get();
}
public function roles()
{
return $this->belongsToMany(Role::class);
}
}<file_sep>/app/Providers/AppServiceProvider.php
<?php
namespace App\Providers;
use App\Setting;
use Illuminate\Support\ServiceProvider;
use Schema;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
if (Schema::hasTable('settings')) {
$settings = Setting::where('boot', true)->get();
foreach ($settings as $setting) {
define(strtoupper($setting->name), $setting->value);
}
}
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
<file_sep>/database/seeds/RoleTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class RoleTableSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run() {
$roles = [
['name' => 'webmaster', 'label' => 'Webmaster'],
['name' => 'admin', 'label' => 'Administrator'],
['name' => 'user', 'label' => 'User']
];
foreach ($roles as $role) {
factory(\App\Users\Role::class)->create($role);
}
$permissions = [
['name' => 'view-dashboard', 'label' => 'Access Dashboard'],
['name' => 'access-menu', 'label' => 'Access All Menus'],
['name' => 'access-setting', 'label' => 'Access All Settings'],
['name' => 'update-setting-global', 'label' => 'Update Only Global Settings'],
['name' => 'access-permission', 'label' => 'Access All Permissions'],
['name' => 'access-role', 'label' => 'Access All Roles'],
['name' => 'manage-user', 'label' => 'Manage Users'],
['name' => 'change-banner', 'label' => 'Change Banner'],
];
for ($i = 0; $i < count($permissions); $i++) {
$permissions[$i] = factory(\App\Users\Permission::class)->create($permissions[$i]);
}
$permissions[0]->roles()->attach(3);
$permissions[1]->roles()->attach(1);
$permissions[2]->roles()->attach(1);
$permissions[3]->roles()->attach(2);
$permissions[4]->roles()->attach(1);
$permissions[5]->roles()->attach(1);
$permissions[6]->roles()->attach(2);
$permissions[7]->roles()->attach(2);
}
}
<file_sep>/app/Users/Role.php
<?php
namespace App\Users;
use App\Menu;
use App\Validator;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
use Validator;
protected static $rules = [
'name' => 'required|max:40',
'label' => 'required|max:40',
];
protected $fillable = ['label', 'name'];
public static function getNames()
{
$roles = self::select('name')->get();
$r = [];
foreach ($roles as $role) {
$r[] = $role->name;
}
return $r;
}
public function givePermissionTo(Permission $permission)
{
return $this->permissions()->save($permission);
}
public function permissions()
{
return $this->belongsToMany(Permission::class);
}
public function menus()
{
return $this->belongsToMany(Menu::class);
}
public function users()
{
return $this->belongsToMany(User::class);
}
public static function getId($string)
{
$get = self::where('name', $string)->first();
return $get ? $get->id : false;
}
}
<file_sep>/app/Http/Controllers/AlamatController.php
<?php
namespace App\Http\Controllers;
use App\Users\Alamat;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Auth;
class AlamatController extends Controller
{
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$user = Auth::user();
$this->validate($request, Alamat::getRules());
$user->addAlamat($request->all());
return back();
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$user = Auth::user();
if (!$alamat = $user->alamats()->find($id))
return abort(404);
$this->validate($request, Alamat::getRules());
$alamat->update($request->all());
if ($request->input('set_default'))
$user->setDefaultAlamat($alamat->id);
return back();
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep>/app/Users/Permission.php
<?php
namespace App\Users;
use App\Validator;
use Illuminate\Database\Eloquent\Model;
class Permission extends Model
{
use Validator;
protected static $rules = [
'name' => 'required|max:40',
'label' => 'required|max:40',
];
protected $fillable = ['label', 'name'];
public function roles()
{
return $this->belongsToMany(Role::class);
}
}
<file_sep>/app/Helpers.php
<?php
function flash($message, $title = 'Perhatian', $level = 'success', $important = false)
{
$options = [
'message' => $message,
'level' => $level,
'title' => $title,
'duration' => $important ? 0 : 3000
];
foreach ($options as $key => $value)
session()->flash('flash_'.$key, $value);
}<file_sep>/app/Http/Controllers/PermissionController.php
<?php
namespace App\Http\Controllers;
use App\Users\Permission;
use App\Users\Role;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Auth;
class PermissionController extends Controller
{
public function __construct()
{
$this->middleware('auth');
$this->middleware('can:access-permission');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$roles = Role::all();
$user = Auth::user();
$permissions = Permission::all();
$editable = false;
return view('permission.index', compact('roles', 'permissions', 'user', 'editable'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$user = Auth::user();
return view('permission.create', compact('user'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, Permission::getRules());
Permission::create($request->all());
return redirect('admin/permission/all/edit');
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$user = Auth::user();
if ($id == "all") {
$roles = Role::all();
$permissions = Permission::all();
$editable = true;
return view('permission.index', compact('roles', 'permissions', 'editable', 'user'));
} else {
$permission = Permission::find($id);
return view('permission.edit', compact('permission', 'user'));
}
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param Permission $permission
* @return \Illuminate\Http\Response
* @internal param int $id
*/
public function update(Request $request, Permission $permission)
{
$this->validate($request, Permission::getRules());
$permission->update($request->all());
return redirect('admin/permission/all/edit');
}
/**
* Remove the specified resource from storage.
*
* @param Permission $permission
* @return \Illuminate\Http\Response
* @throws \Exception
* @internal param int $id
*/
public function destroy(Permission $permission)
{
$permission->delete();
return redirect('admin/permission/all/edit');
}
public function detachRole(Permission $permission, Role $role)
{
$permission->roles()->detach($role->id);
return redirect('admin/permission/all/edit');
}
public function attachRole(Permission $permission, Role $role)
{
$permission->roles()->attach($role->id);
return redirect('admin/permission/all/edit');
}
}
<file_sep>/database/seeds/UserTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class UserTableSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run() {
$maul = factory(\App\Users\User::class)->create(
['username' => 'webmaster', 'email' => '<EMAIL>']
);
$maul->biodata()->save(factory(\App\Users\Biodata::class)->make());
$maul->addAlamat(factory(\App\Users\Alamat::class)->make());
$maul->roles()->attach(1);
$maul->roles()->attach(2);
$maul->roles()->attach(3);
$admin = factory(\App\Users\User::class)->create(
['username' => 'admin', 'email' => '<EMAIL>']
);
$admin->biodata()->save(factory(\App\Users\Biodata::class)->make());
$admin->addAlamat(factory(\App\Users\Alamat::class)->make());
$admin->roles()->attach(2);
$admin->roles()->attach(3);
factory(\App\Users\User::class, 5)->create()->each(function ($u) {
$u->biodata()->save(factory(\App\Users\Biodata::class)->make());
$u->addAlamat(factory(\App\Users\Alamat::class)->make());
$u->roles()->attach(3);
});
}
}
<file_sep>/app/Http/Controllers/SettingController.php
<?php
namespace App\Http\Controllers;
use App\Setting;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Auth;
class SettingController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
$this->middleware('can:access-setting', ['except' => ['updateValue', 'editValue']]);
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$user = Auth::user();
$settings = Setting::all();
return view('setting.index', compact('settings', 'user'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$user = Auth::user();
return view('setting.create', compact('user'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, Setting::getRules());
Setting::create($request->all());
return redirect('admin/setting');
}
/**
* Show the form for editing the specified resource.
*
* @param $setting
* @return \Illuminate\Http\Response
* @internal param int $id
*/
public function edit(Setting $setting)
{
$user = Auth::user();
return view('setting.edit', compact('setting', 'user'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param Setting $setting
* @return \Illuminate\Http\Response
* @internal param int $id
*/
public function update(Request $request, Setting $setting)
{
$this->validate($request, Setting::getRules());
$setting->update($request->all());
return redirect('admin/setting');
}
/**
* Remove the specified resource from storage.
*
* @param Setting $setting
* @return \Illuminate\Http\Response
* @throws \Exception
* @internal param int $id
*/
public function destroy(Setting $setting)
{
$setting->delete();
return redirect('admin/setting');
}
public function editValue($module)
{
$user = Auth::user();
if (!$user->can('access-setting'))
$this->authorize('update-setting-' . $module);
$settings = Setting::where('module', $module)->get();
return view('setting.edit-value', compact('settings', 'all_setting', 'user'));
}
public function modules()
{
$user = Auth::user();
$modules = Setting::select('module')->distinct()->get();
return view('setting.list_module', compact('modules', 'user'));
}
public function updateValue(Request $request, $module)
{
$user = Auth::user();
if (!$user->can('access-setting'))
$this->authorize('update-setting-' . $module);
$all = array_diff_key($request->all(), ['_token' => '', '_method' => '']);
foreach ($all as $id => $value) {
$setting = Setting::find($id);
$this->validate($request, [
$id => $setting->validationType()
]);
if($setting->setValue($value)) {
flash("Setting $setting->label tidak memiliki tipe yang benar!!");
return back();
}
}
return redirect('admin/setting/' . $request->segment(3) . '/update');
}
}
<file_sep>/app/Users/HasRoles.php
<?php
namespace App\Users;
trait HasRoles
{
public function hasRole($roles)
{
if (is_string($roles)) {
return $this->roles->contains('name', $roles);
}
return !!$roles->intersect($this->roles)->count();
}
public function assignRole($role)
{
return $this->roles()->save(
Role::whereName($role)->firstOrFail()
);
}
public function roles()
{
return $this->belongsToMany(Role::class);
}
}<file_sep>/app/Http/routes.php
<?php
//General Routes
Route::group(['as' => 'pages.'], function () {
Route::get('/', 'PagesController@home')
->name('home');
Route::get('help', 'PagesController@help')
->name('help');
Route::get('about', 'PagesController@contact')
->name('contact');
});
Route::auth();
//USER Routes
Route::get('profile/{username?}', 'UserController@profile')->name('user.profile');
Route::post('profile', 'UserController@update')->name('user.update');
Route::get('password/change', 'UserController@changePassword')->name('user.change-password');
Route::post('password/change', 'UserController@updatePassword')->name('user.update-password');
Route::resource('alamat', 'AlamatController', ['except' => ['index', 'show', 'create', 'edit']]);
//ADMIN Routes
Route::group(['prefix' => 'admin'], function () {
Route::get('/', 'AdminController@index')->name('dashboard');
Route::post('/', 'AdminController@uploadImage')->name('upload');
Route::group(['prefix' => 'setting', 'as' => 'setting.'], function () {
Route::get('modules', 'SettingController@modules')
->name('list_module');
Route::get('{module}/update', 'SettingController@editValue')
->name('edit_value');
Route::patch('{module}/update', 'SettingController@updateValue')
->name('update_value');
});
Route::group(['prefix' => 'permission', 'as' => 'permission.'], function () {
Route::post('{permission}/role/{role}', 'PermissionController@attachRole')
->name('attach');
Route::delete('{permission}/role/{role}', 'PermissionController@detachRole')
->name('detach');
});
Route::get('admin', 'UserController@admin');
Route::group(['as' => 'user.', 'prefix' => 'user'], function () {
Route::put('{user}', 'UserController@unDestroy')->name('un-destroy');
Route::put('{user}/role/{role}', 'UserController@attachRole')->name('attach-role');
Route::delete('{user}/role/{role}', 'UserController@detachRole')->name('detach-role');
});
Route::resource('setting', 'SettingController', ['except' => ['show']]);
Route::resource('user', 'UserController', ['except' => ['show', 'update', 'edit']]);
Route::resource('role', 'RoleController', ['except' => ['show']]);
Route::resource('permission', 'PermissionController', ['except' => ['show']]);
Route::resource('menu', 'MenuController', ['except' => ['show']]);
});
/**
* stereotype for routes:
* {controller_name; unique_feature;}/{variable: id; username; etc;}/{action; component;}
*
* e.g.:
* -> user/1/edit (action)
* -> permission/1/role/1 (component)
**/
//API Routes
Route::group(['prefix' => 'api', 'as' => 'api.'], function () {
Route::group(['prefix' => 'region', 'as' => 'region.'], function () {
Route::get('cities/{p_id}', 'UtilitiesController@getCities');
Route::get('districts/{k_id}', 'UtilitiesController@getDistricts');
});
Route::get('users/{role?}', 'UserController@api')->name('users');
Route::get('menu/menu_list/{module}', 'MenuController@menuList')->name('menus');
});
//Development Routes
Route::get('trial', function () {
$user = Auth::user();
return view('trial', compact('user'));
});
Route::get('loginusing/{id}', function ($id) {
Auth::loginUsingId($id);
return redirect('admin');
}); | 5b44357e52db0056d3dff9d46499312ff802f277 | [
"Markdown",
"PHP"
] | 30 | PHP | scalpovich/lara-framework | 9482c6c14317bf8e80cbbad48e96c0c5973ee81c | aec33a4f292c4bfa255fd2924771783375e21cc6 |
refs/heads/main | <repo_name>gilbendavid/LawGeekMovieApp<file_sep>/src/app/components/search/search.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from 'src/app/services/data.service';
import { MovieStore } from '../../state/moviesStore';
import { Movie } from '../../models/movie';
import { Router } from '@angular/router';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
isSearchServerError: boolean = false;
searchServerError : string = "";
constructor(
private data: DataService,
private router: Router,
public movieStore : MovieStore
) { }
get store() {
return this.movieStore.movies;
}
ngOnInit() {
this.data.cleanSearches()
}
async searchAction(value : string){
this.isSearchServerError = false;
let res = await this.data.fetchOmdbapi(value);
if(res.Response === "False"){
this.isSearchServerError = true;
this.searchServerError = res.Error;
}
else{
res.Search.forEach(movie => {
this.store.push(movie)
});
this.router.navigate(['movies']);
}
}
}
<file_sep>/src/app/services/data.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { MovieStore } from '../state/moviesStore';
import { Movie } from '../models/movie';
const apiUrl = 'http://www.omdbapi.com/?apikey=ed440c27';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http : HttpClient,
public movieStore : MovieStore) {}
get store() {
return this.movieStore.movies;
}
cleanSearches(){
this.movieStore.movies = [];
}
async fetchOmdbapi(searchValue: string): Promise<any> {
let searchUrl = `${apiUrl}&s=${searchValue}`
let res = await this.http.get<any>(searchUrl).toPromise();
return res;
}
async fetchOmdbapiByMovieId(imdbID: string): Promise<any> {
let searchUrl = `${apiUrl}&i=${imdbID}&plot=full`
let res = await this.http.get<any>(searchUrl).toPromise();
return res;
}
getAllTitles(): string[] {
return this.store.map(m => m.Title);
}
getAllReleasedYears(): string[] {
return this.store.map(m => m.Year);
}
getMoviesTitelsByReleasedYear(year : string): string[] {
return this.store
.filter(m => m.Year === year)
.map(m => m.Title);
}
getMovie(title: string): Movie {
return this.store.find(m => m.Title === title);
}
getMovieByIndex(index: number): Movie {
return this.store[index];
}
getMovieCount(): number {
return this.store.length;
}
}
<file_sep>/src/app/guards/empty-list.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, Router, UrlTree } from '@angular/router';
import { DataService } from '../services/data.service';
import { MovieStore } from '../state/moviesStore';
@Injectable({
providedIn: 'root'
})
export class EmptyListsGuard implements CanActivate {
constructor(
public data: DataService,
private router: Router,
public movieStore : MovieStore)
{}
get store() {
return this.movieStore.movies;
}
canActivate(): boolean | UrlTree {
const listCount = this.store.length
if (listCount > 0) return true;
return this.router.createUrlTree(['search']);
}
}
<file_sep>/src/app/components/movie-list/movie-list.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { DataService } from 'src/app/services/data.service';
import { MovieStore } from 'src/app/state/moviesStore';
@Component({
selector: 'app-movie-list',
templateUrl: './movie-list.component.html',
styleUrls: ['./movie-list.component.css']
})
export class MovieListComponent implements OnInit {
titles: string[] = [];
releasedYear: string[] = [];
filterReleasedYear: string;
constructor(
public data: DataService,
private router: Router,
public movieStore : MovieStore)
{}
get store() {
return this.movieStore.movies;
}
ngOnInit() {
this.titles = this.data.getAllTitles();
this.releasedYear = this.data.getAllReleasedYears();
}
selectMovieIndex(index: number) {
this.router.navigate(['movies', index]);
}
filterResults(){
if(this.filterReleasedYear === ""){
this.titles = this.data.getAllTitles();
}
else{
this.titles = this.data.getMoviesTitelsByReleasedYear(this.filterReleasedYear);
}
}
}
<file_sep>/src/app/state/moviesStore.ts
import { Movie } from '../models/movie';
export class MovieStore {
movies : Movie[] = [];
constructor() { }
} | b2476ffdd423293758a7e3a023e0e2c20963eafb | [
"TypeScript"
] | 5 | TypeScript | gilbendavid/LawGeekMovieApp | ec3675281026365234bbd1d694a2b79eba246f6a | 1d3face95882d4bf469566909cfdb9e8a3858baa |
refs/heads/master | <file_sep><!doctype html>
<html class="no-js" lang="en">
<head>
<script src="https://browser.sentry-cdn.com/5.6.3/bundle.min.js" integrity="<KEY>" crossorigin="anonymous">
</script>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Cryptrix19</title>
<meta name="description" content=" alvis123">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="shortcut icon" href="favicon.ico">
<link rel="stylesheet" type="text/css" href="_assets/normalize.css">
<link rel="stylesheet" type="text/css" href="_assets/wiresphere.css">
<link rel="stylesheet" type="text/css" href="_assets/font-awesome-4.5.0/css/font-awesome.css">
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Lato:400,300,700,900,100">
<link href="https://fonts.googleapis.com/css?family=PT+Sans+Narrow:700&display=swap" rel="stylesheet" type="text/css">
<link type="text/css" href="demo.css?v=1.0.0.0" rel="stylesheet" />
<link
href="https://www.jqueryscript.net/css/jquerysctipttop.css"
rel="stylesheet"
type="text/css"
/>
<link
type="text/css"
rel="stylesheet"
/>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
</script>
</head>
<style>
::placeholder { /* Firefox, Chrome, Opera */
color: black;
}
</style>
<body>
<div class="preloader" id="preloader">
<svg style="" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 257.7 223.2" xml:space="preserve">
<img src="_pics/SJCElogo.webp" class="center">
</svg>
</div>
<div class="stage">
<div class="backgroundStack" id="backgroundStack">
<div class="backgroundStack-solidColor" id="backgroundStack-solidColor"></div>
<div class="backgroundStack-pic" id="backgroundStack-pic"></div>
<canvas class="backgroundStack-gradient" id="backgroundStack-gradient"></canvas>
<div class="backgroundStack-3d" id="backgroundStack-3d"></div>
<div class="backgroundStack-noise" id="backgroundStack-noise"></div>
</div>
<div class="stage-logo responsive">
<img src="_pics/layer.webp" height="100" width="100" alt="">
<img src="_pics/SJCElogo.webp" height="100" width="150" align="right" alt="">
<h1 style="text-align: center">St.Joseph's College Of Engineering</h1>
<h2 style="text-align: center">(St.Joseph's Group of Institutions)</h2>
</div>
<div class="stage-header">
<h1><br><br><br>CRYPTRIX 2K19</h1>
<h2 id="stage-header-tagline" style="font-size: 2.5vw">
<span>Department of CSE</span>
<span>Cash prize:Rs.30,000</span>
<span>Beat The Competition</span>
<span>Gain Technical<br> Knowledge</span>
<span>Prize Certificates</span>
</h2>
</div>
<div id="redCountdown" class="redCountdown"></div>
<nav class="stage-nav" id="stage-nav">
<ul>
<li><a class="nice-link" style="pointer-events: none" href="#" data-page="about"><div class="hover"><span></span><span></span><span></span><span></span></div><span>Event Is Over! SEE YOU NEXT YEAR</span></a></li>
<li><a class="nice-link" href="#" data-page="contact"><div class="hover"><span></span><span></span><span></span><span></span></div><span><strike>Register</strike></span></a></li>
<!--<li><a class="nice-link" style="pointer-events: none" data-page="contact"><div class="hover"><span></span><span></span><span></span><span></span></div><span><strike>Register</strike></span></a></li>-->
</ul>
</nav>
<div class="content-close" id="content-close"><a class="nice-link" href="#"><div class="hover"><span></span><span></span><span></span><span></span></div><span><i class="fa fa-angle-left"></i></span></a></div>
<div class="content" id="content">
<div class="wrapper">
<h2 class="content-title" id="content-title">About us</h2>
<div class="content-content content-content--about" id="content-content--about">
<div class="content-textwrapper">
<p style="font-size:4vw;">LIST OF EVENTS</p>
<p style="color: aqua;font-size: 38px;"><strong>BIND AND BLIND</strong></p>
<img src="_pics/bind.webp" class="responsive" alt="">
<p><span style="color: yellow;font-size: 32px;">Preliminary Round:</span><br>
A technical term will be split into several parts. Each part shall have an illustrative clue through which the term must be identified by linking all the clues similar to a Connection game. <br><br>
<span style="color: yellow;font-size: 32px;">Finals:</span><br>Participants will be given a program with errors. The challenge is to debug the program and type the code in the TEXT EDITOR with their MONITOR SWITCHED OFF.<br><br>
<span style="color: yellow;font-size: 32px;">Rules:</span><br>
• Each team should have no more than 2 members.<br>
• No Internet usage.<br><br>
<span style="color: yellow;font-size: 32px;">Contact </span><br>
Shunmathy: 9500430998<br>Ashwanthika: 7550159016</p><br><br>
<p style="color: aqua;font-size: 38px;"><strong>BREAK THE ENIGMA</strong></p>
<img src="_pics/break.webp" class="responsive" alt="">
<p><span style="color: yellow;font-size: 32px;">Preliminary Round:</span><br>
A paper pen test where problems must be solved in a particular order to find the “ENIGMA” (KEY) to the next round. The key will be easy to decrypt at first, but then it scales up its complexity as you solve more. Questions can be expected from basic computer science concepts and subjects.<br><br>
<span style="color: yellow;font-size: 32px;">Finals Description:</span><br> Teams who reach the final round will be given 5 URLs that
Teams will be given URL’s that are encrypted. The Algorithm that has been used for encryption will be provided. The teams must decrypt the URL, which would lead to a programming question that is to be solved. The easiest URL to decrypt will have the toughest program and vice versa. (Internet Usage will be allowed)<br><br>
<span style="color: yellow;font-size: 32px;">Rules:</span><br>
• Every team will have no more than 2 members.<br><br>
<span style="color: yellow;font-size: 32px;">Contact </span><br>
Sreeram: 9566357258<br><NAME>:7402296507</p><br><br>
<p style="color: aqua;font-size: 38px;"><strong>CODE QUEST</strong></p>
<img src="_pics/code.webp" class="responsive" alt="">
<p><span style="color: yellow;font-size: 32px;">Preliminary Round</span><br>
Technical questions will be given in the form of a maze. Solving the questions creates the path for the maze.<br><br>
<span style="color: yellow;font-size: 32px;">Finals Description:</span><br>Teams should Solve the given problem by coding. Then they must OBFUSCATE their code. This code will be distributed among other teams. Teams that DE-OBFUSCATE the correct logic will be given points.<br><br>
<span style="color: yellow;font-size: 32px;">Rules:</span><br>
• Each team should strictly have no more than two members.<br>
• No Internet access. <br><br>
<span style="color: yellow;font-size: 32px;">Contact</span><br>
Jagajeet: 8148174147<br>Trisha:9176263007</p><br><br>
<p style="color: aqua;font-size: 45px;"><strong>MYSTERIO</strong></p>
<img src="_pics/mysterio.webp" class="responsive" alt="">
<p><span style="color: yellow;font-size: 32px;">Preliminary Round:</span><br>
Each team is provided with a set of questions. For each correct answer the team will be granted a Gem.<br><br>
<span style="color: yellow;font-size: 32px;">Finals Description:</span><br> One participant should solve a program to gain the key that unlocks the web designing task for the another participant, one after another. The other participant should design the web design.
<br>
<span style="color: yellow;font-size: 32px;">Rules:</span><br>
• Teams should strictly have 2 members only.<br>
• Members can solve only their particular domain during the finals.
<br><br>
<span style="color: yellow;font-size: 32px;">Contact </span><br>
<NAME>: 9677193223<br><NAME>: 7010337956</p><br><br>
<p style="color: aqua;font-size: 38px;"><strong>SCRAP YARD WARS</strong></p>
<img src="_pics/scrap.webp" class="responsive" alt="">
<p><span style="color: yellow;font-size: 32px;">Preliminary Round:</span><br>A pen and paper MCQ Quiz on Computer components and PC building will be conducted .<br><br>
<span style="color: yellow;font-size: 32px;">Finals Description:</span><br> The Requirements of a Customer, his/her Budget and the Price list of all the components will be specified. The auction will be organized to purchase PC components. The challenge is to build the best Spec PC within the budget.<br><br>
<span style="color: yellow;font-size: 32px;">Rules:</span><br>
• Every team will have no more than 2 members.<br>
<span style="color: yellow;font-size: 32px;">Contact</span><br>
Vaibhav: 9677046657<br>Surya: 9176076911</p><br><br>
</div>
<div class="stage-logo" style="align-content: center">
<br/><br/>
<h1><span style="font-size:4vw;"> General Rules</span></h1>
<h2>
<br/><span style="color: yellow;font-size:2vw;font-family:'Times New Roman', Times, serif'"> Formal dress code is expected. <br> Avoid Jeans and T-Shirt.</span>
</h2>
<h1><span style="font-size:4vw;"> Contact Us</span>
<br/><span style="color: aqua;font-size:2vw;"> ORGANIZERS</span>
<br> <NAME><br>
<span style="color: aqua"> 7373728393</span>
<br> <NAME><br>
<span style="color: aqua"> 9443499270<br></span>
<br><span style="color: aqua;font-size:2vw;"> CO-ORDINATORS</span>
<br> <NAME><br>
<span style="color: aqua"> 9444448925</span>
<br> KOUSHIK T<br>
<span style="color: aqua"> 9176273446</span>
<br/>
<br><span style="color: aqua;font-size:2vw;"> TECHNICAL TEAM</span>
<br/>
<br> <a href="https://www.linkedin.com/in/alvisf/" style="color: aliceblue"><NAME></a>
<br> <a href="https://www.linkedin.com/in/augustin-dennis-b46b8118b/" style="color: aliceblue"><NAME></a>
<br> DANIEL
</h1>
</div>
<br/>
</div>
<div class="content-content content-content--contact" id="content-content--contact">
<div id=alvisdis class="answer_list" >
<form autocomplete="off" id="alvissubmit">
<div class="container">
<h1>Register</h1>
<p>NOTE:ONE TIME REGISTRATION LETS YOU PARTICIPATE IN ALL FIVE OF OUR EXCITING EVENTS.</p>
<p style="color: red">*PARTICIPANTS SHOULD BRING THEIR COLLEGE ID CARDS AND WILL BE ADMITTED INSIDE THE CAMPUS ONLY IF FORMAL DRESS CODE IS FOLLOWED.</p>
<hr>
<label for="alvis6"><b>Name</b></label>
<input type="text" placeholder="Enter Name" name="alvis6" id="name" required style="color: #333">
<label for="lunch1"><b>Gender</b></label>
<select name="my_html_select_box" class="dropdown-menu" id="sex" style="color: #333;width: 100%;padding: 12px; background-color: rgb(230, 255, 255)">
<option value="MALE">Male</option>
<option value="FEMALE">Female</option>
<option value="OTHERS">Others</option>
</select>
<label for="alvis1"><b>Name of University/College</b></label>
<input type="text" placeholder="Enter name of University/College" id="college" name="alvis1" x required style="color: #333">
<label for="alvis2"><b>Register number/Roll number</b></label>
<input type="text" placeholder="Enter Register number/Roll Number" id="regno" name="alvis2" required style="color: #333">
<label for="alvis3"><b>Contact Number</b></label>
<input pattern="[0-9]{10}" type="text" placeholder="Enter your Contact Number" id="phone" name="alvis3" required style="color: #333" >
<label for="alvis4"><b>Email</b></label>
<input type="email" placeholder="Enter Email" id="email" name="alvis4" required style="color: #333">
<label for="lunch"><b>Lunch Preference</b></label>
<select id="food" name="my_html_select_box" class="dropdown-menu" style="color: #333;width: 100%;padding: 15px;background-color: rgb(230, 255, 255)">
<option value="0">Non-Veg </option>
<option value="1">Veg</option>
</select>
<hr>
<p style="text-decoration: line-through;">Human verification: Click Register button twice</p>
<button type="submit" class="registerbtn" style="margin-top: 0%">Register</button>
</div>
</form>
</div>
<div class="stage-logo">
<br/><br/>
<h1><span style="font-size:4vw;"> Contact Us</span>
<br/><span style="color: aqua;font-size:2vw;"> ORGANIZERS</span>
<br> <NAME><br>
<span style="color: aqua"> 7373728393</span>
<br> <NAME><br>
<span style="color: aqua"> 9443499270<br></span>
<br><span style="color: aqua;font-size:2vw;"> CO-ORDINATORS</span>
<br> <NAME><br>
<span style="color: aqua"> 9444448925</span>
<br> KOUSHIK T<br>
<span style="color: aqua"> 9176273446</span>
<br/>
<br><span style="color: aqua;font-size:2vw;"> TECHNICAL TEAM</span>
<br/>
<br> <a href="https://www.linkedin.com/in/alvisf/" style="color: aliceblue"><NAME></a>
<br> <a href="https://www.linkedin.com/in/augustin-dennis-b46b8118b/" style="color: aliceblue"><NAME></a>
<br> DANIEL
</h1>
</div>
<br/>
<div class="contact-map" id="contact-map" style="display:none;"></div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="_assets/jquery-2.2.4.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=<KEY>"></script>
<script src="config.js"></script>
<script src="_assets/three.min.js"></script>
<script src="_assets/three.canvas-renderer.min.js"></script>
<script src="_assets/three.projector.min.js"></script>
<script src="_assets/wiresphere.3danim.js"></script>
<script src="_assets/wiresphere.js"></script>
</div>
<script src="https://www.gstatic.com/firebasejs/6.4.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.1.0/firebase-database.js"></script>
<script src="alvis.js"></script>
</body>
</html>
<file_sep>"use strict";
jQuery(function($) {
$.fn.Wiresphere3DAnim = function(Config) {
var It = $(this);
var Settings = {
particleColor: 0xffffff,
particleOpacity: .5,
particleSize: 5,
particlesAmmount: 750,
lineColor: 0xffffff,
lineOpacity: 0.5,
backlineOpacity: 0.05,
moveSpeed: 0.07,
cameraXMoveMax: 1.5,
cameraYMoveMax: 0.75,
cameraXMoveElastic: 0.02,
cameraYMoveElastic: 0.02
}
Settings = $.extend(true, Settings, Config);
var mouseX = 0,
mouseY = 0,
windowHalfX = $(this).innerWidth() / 2,
windowHalfY = $(this).innerHeight() / 2,
camera, scene, renderer;
init();
animate();
var line;
function init() {
var container, color = 0xffffff,
particles, particle;
container = It[0];
camera = new THREE.PerspectiveCamera(75, $(It).innerWidth() / $(It).innerHeight(), 1, 10000);
camera.position.z = 100;
camera.position.x = 2000;
scene = new THREE.Scene();
renderer = new THREE.CanvasRenderer({
alpha: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setClearColor(0xffffff, 0);
renderer.setSize($(It).innerWidth(), $(It).innerHeight());
container.appendChild(renderer.domElement);
var PI2 = Math.PI * 2;
var geometry = new THREE.Geometry();
for (var i = 0; i < Settings.particlesAmmount; i++) {
var material = new THREE.SpriteCanvasMaterial({
color: Settings.particleColor,
opacity: Math.random() * 0.5,
program: function(context) {
context.beginPath();
context.arc(0, 0, 0.2, 0, PI2, true);
context.fill();
}
});
particle = new THREE.Sprite(material);
particle.position.x = Math.random() * 2 - 1;
particle.position.y = Math.random() * 2 - 1;
particle.position.z = Math.random() * 2 - 1;
if (Math.random() > 0.5) {
particle.position.xT = true;
} else {
particle.position.xT = false;
}
if (Math.random() > 0.5) {
particle.position.yT = true;
} else {
particle.position.yT = false;
}
if (Math.random() > 0.5) {
particle.position.zT = true;
} else {
particle.position.zT = false;
}
particle.position.normalize();
particle.position.multiplyScalar(Math.random() * 10 + 500);
particle.scale.x = particle.scale.y = Settings.particleSize;
scene.add(particle);
geometry.vertices.push(particle.position);
}
line = new THREE.Line(geometry, new THREE.LineBasicMaterial({
color: Settings.lineColor,
opacity: 0
}));
scene.add(line);
var Cgeometry, Cmaterial, Cmesh;
Cgeometry = new THREE.IcosahedronGeometry(50, 1);
Cmaterial = new THREE.MeshBasicMaterial({
color: Settings.lineColor,
opacity: Settings.lineOpacity,
wireframe: true,
wireframeLinewidth: 1.5,
side: THREE.FrontSide
});
Cmesh = new THREE.Mesh(Cgeometry, Cmaterial);
scene.add(Cmesh);
Cmaterial = new THREE.MeshBasicMaterial({
color: Settings.lineColor,
opacity: Settings.backlineOpacity,
wireframe: true,
wireframeLinewidth: 1,
side: THREE.BackSide
});
Cmesh = new THREE.Mesh(Cgeometry, Cmaterial);
scene.add(Cmesh);
document.addEventListener('mousemove', onDocumentMouseMove, false);
document.addEventListener('touchstart', onDocumentTouchStart, false);
document.addEventListener('touchmove', onDocumentTouchMove, false);
window.addEventListener('resize', onWindowResize, false);
}
function onWindowResize() {
windowHalfX = $(this).innerWidth() / 2;
windowHalfY = $(this).innerHeight() / 2;
camera.aspect = $(It).innerWidth() / $(It).innerHeight();
camera.updateProjectionMatrix();
renderer.setSize($(It).innerWidth(), $(It).innerHeight());
}
function onDocumentMouseMove(event) {
mouseX = (event.clientX - windowHalfX) * 0.05;
mouseY = (event.clientY - windowHalfY) * 0.2;
}
function onDocumentTouchStart(event) {
if (event.touches.length > 1) {
mouseX = (event.touches[0].pageX - windowHalfX) * 0.7;
mouseY = (event.touches[0].pageY - windowHalfY) * 0.7;
}
}
function onDocumentTouchMove(event) {
if (event.touches.length == 1) {
mouseX = event.touches[0].pageX - windowHalfX;
mouseY = event.touches[0].pageY - windowHalfY;
}
}
function animate() {
if (Settings.moveSpeed > 0) {
for (var i = 0; i < Settings.particlesAmmount; i++) {
if (line.geometry.vertices[i].xT) {
line.geometry.vertices[i].x -= Settings.moveSpeed;
} else {
line.geometry.vertices[i].x += Settings.moveSpeed;
}
if (line.geometry.vertices[i].yT) {
line.geometry.vertices[i].y -= Settings.moveSpeed;
} else {
line.geometry.vertices[i].y += Settings.moveSpeed;
}
if (line.geometry.vertices[i].zT) {
line.geometry.vertices[i].z -= Settings.moveSpeed;
} else {
line.geometry.vertices[i].z += Settings.moveSpeed;
}
if (line.geometry.vertices[i].x < -500) {
line.geometry.vertices[i].xT = false;
}
if (line.geometry.vertices[i].y < -500) {
line.geometry.vertices[i].yT = false;
}
if (line.geometry.vertices[i].z < -500) {
line.geometry.vertices[i].zT = false;
}
if (line.geometry.vertices[i].x > 500) {
line.geometry.vertices[i].xT = true;
}
if (line.geometry.vertices[i].y > 500) {
line.geometry.vertices[i].yT = true;
}
if (line.geometry.vertices[i].z > 500) {
line.geometry.vertices[i].zT = true;
}
}
}
requestAnimationFrame(animate);
render();
}
function render() {
camera.position.x += (mouseX * Settings.cameraXMoveMax - camera.position.x) * Settings.cameraXMoveElastic;
camera.position.y += (-mouseY * Settings.cameraYMoveMax - camera.position.y) * Settings.cameraYMoveElastic;
camera.lookAt(scene.position);
renderer.render(scene, camera);
}
}
});<file_sep>import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
// Extend HttpServlet class
public class MailServlet extends HttpServlet {
private final String userName="";
private final String password="";
private String toAddress;
private String subject;
private String message;
public void init() throws ServletException {
toAddress = "";
subject = "Testing Java mail";
message = "Mail is sent successfully";
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
Properties properties = new Properties();
properties.put("mail.smtps.user",userName);
properties.put("mail.smtps.host", "smtp.gmail.com");
properties.put("mail.smtps.port", "465");
properties.put("mail.smtps.starttls.enable","true");
properties.put("mail.smtps.auth", "true");
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName,password);
}
});
//session.setDebug(true);
// creates a new e-mail message
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
msg.setSubject(subject);
msg.setText(message);
// sends the email
Transport transport = session.getTransport("smtps");
transport.connect("smtp.gmail.com",userName,password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
System.out.println("message sent successfully");
} catch(MessagingException e) {
System.out.println("Exception caught\n"+e.getMessage());
}
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
public void destroy() {
// do nothing.
}
}
<file_sep>"use strict";
// Wiresphere config file
// Do not delete anything from this file!
var WiresphereConfig = {
Background: {
SolidBg: {
Color: "#003d4f" // Solid background color
},
Picture: {
Enabled: false, // Background picture true/false
Opacity: "0.07" // Background picture opacity
},
Gradient: {
Enabled: true, // Background animated gradient true/false
StopAColor: "0,204,255", // Background animated gradient Stop A
StopBColor: "0,204,255", // Background animated gradient Stop B
Opacity: 0.2 // Background animated gradient opacity
},
Sphere3D: {
lineColor: 0xffffff, // Color of sphere outline
lineOpacity: 0.5, // Opacity of front face of sphere
backlineOpacity: 0.05, // Opacity of backface of sphere
particleColor: 0xffd700, // Color of particles
particleOpacity: 0.5, // Opacity of particles
particleSize: 10, // Size of particles
particlesAmmount: 750, // Ammount of particles
moveSpeed: 0.07, // Speed of particles
cameraXMoveMax: 1.5, // Mouse movement max rotation
cameraYMoveMax: 0.75, // Mouse movement max rotation
cameraXMoveElastic: 0.02, // Mouse movement smoothness
cameraYMoveElastic: 0.02 // Mouse movement smoothness
},
Noise: {
Enabled: true, // Background noise true/false
Opacity: "0.05" // Background noise opacity
}
},
Colors: {
JSOverride: true, // Set to false if you want to tweak CSS
Tagline: {
// Tagline
FirstLine: "#fff", // Color of first line of tagline
SecondLine: "#fff" // Color of second line of tagline
},
Buttons: {
// Buttons
Outline: "#fff", // Color of buttons outline
Text: "#fff", // Color of buttons text
TextHover: "rgba(255,255,255,0.5)" // Color of buttons text on hover
},
SideContent: {
// Side content
Background: "#000", // Background of side content
Text: "#FFF", // Text color of side content
ContactIcons: "#DDD" // Color of contact icons
}
},
Map: {
Longtitude: -73.946, // X Map location
Latitude: 40.674, // X Map location
Style: [
// X Map style - refer to Google Maps for more details
{
stylers: [{ saturation: -100 }, { lightness: 62 }, { gamma: 0.47 }]
},
{
elementType: "labels.text",
stylers: [{ color: "#ffffff" }, { visibility: "simplified" }]
},
{
elementType: "labels.icon",
stylers: [{ gamma: 2.17 }]
}
]
}
};
<file_sep># Cryptrix
2019 St.Joseph's college of engineering Symposium
### Checkout : https://flamboyant-ramanujan-fa1e84.netlify.app/
## Task
A Registration website which is reactive to the cursor. Hosted with GitHub hosting site. Used firebase to act as a database.
## Technology Stack
This consist of only the web page builds with JavaScript, HTML and CSS.
The microservice will send email confirmation made in Spring JAVA.
Firebase FireStone for the database.
## Advantages
Does not need a server
## Lessons Learnt
- Create a serverless application.
- How to use NoSQL in realtime
- Deploying application

| baa8f70e2670f4e6caaae4ff27dc872b98bcfde8 | [
"JavaScript",
"Java",
"HTML",
"Markdown"
] | 5 | HTML | alvisf/cryptrixv2 | 550ee8ba0dec125a623426945d96ed7a34dad7a8 | 8b5dd70b55e3498f680b49b4cde8f3af72392b14 |
refs/heads/master | <file_sep>source 'https://rubygems.org'
gem 'activerecord', '~> 4.1.1'
gem 'rake'
gem 'pg', :platform => [:ruby, :mswin, :mingw]
gem 'rspec'
group :test, :development do
gem 'database_cleaner'
end
<file_sep>require 'spec_helper'
describe SimpleTree do
describe "Initialization" do
it "is set up correctly" do
pending "fart"
end
end
describe "Roots" do
it "has a set of root nodes" do
pending "fart"
end
end
describe "Down the tree" do
it "retrieves its descendents" do
pending "fart"
end
end
describe "Back up the tree" do
it "retrieves its ancestors" do
pending "fart"
end
end
describe "Modifying the tree" do
it "adds a new child" do
pending "fart"
end
it "updates a child" do
pending "fart"
end
it "deletes a child" do
pending "fart"
end
end
end
<file_sep>require 'active_record'
require "active_support/concern"
require "active_support/core_ext/module/attribute_accessors"
module SimpleTree
extend ActiveSupport::Concern
module ClassMethods
end
module InstanceMethods
end
end
| 1f13add9230f01d7dcf7773cb16365efb281d2bd | [
"Ruby"
] | 3 | Ruby | dhoss/acts_as_sane_tree | 894f590e466d99bda01b30c5e850c05df9b18553 | e2890c7716cd6e7b6aff318d9ab97e3767ce2405 |
refs/heads/master | <repo_name>yezitang/ys<file_sep>/index.php
<?php
echo 'ys';
?> | 0b7a2cfbfbbc1cbd2b8b3ca11be475ad3c64f595 | [
"PHP"
] | 1 | PHP | yezitang/ys | 2c22ad585159bb1b2f1a74b706203604d598c1c8 | 7b08219fb687bb13a1f9b1ded06947c5261dc209 |
refs/heads/master | <file_sep># TweetSentiment
Leverages NLTK's Naive Bayes classifier to perform sentiment analysis on tweets. This is part of a larger project involving sentiment analysis run on tweets pertaining to the 2016 presidential election.
<file_sep>import tweet_classifier
#training_file = './trainingandtestdata/testdata.manual.2009.06.14.csv'
training_file = './trainingandtestdata/training.1600000.processed.noemoticon.csv'
classifier = tweet_classifier.TweetClassifier(training_file)
print('Initializing Tweet Classifier. . .')
classifier.trainClassifier()
tweet = ' '
while(tweet != 'end'):
tweet = input(
'Enter Tweet to be classified (enter \'end\' to end script execution): ')
print(classifier.classifyTweet(tweet))
# print(classifier.showMostInformative())
<file_sep>'''
This code borrows liberally (very liberally) from <NAME>'
Twitter-aware tokenizer, full code available here:
http://sentiment.christopherpotts.net/code-data/happyfuntokenizing.py
'''
import re
import htmlentitydefs
regex_strings = (
# HTML tags
r"""<[^>]+>""",
# Twitter username:
r"""(?:@[\w_]+)"""
# Twitter hashtags:
r"""(?:\#+[\w_]+[\w\'_\-]*[\w_]+)""",
# Other word types:
r"""
# Words with apostrophes or dashes
(?:[a-z][a-z'\-_]+[a-z])
|
# Numbers, including fractions and decimals
(?:[+\-]?\d+[,/.:-]\d+[+\-]?)
|
# Words without apostrophes or dashes
(?:[\w_]+)
|
# Ellipsis dots
(?:\.(?:\s*\.){1,})
|
# Everything else that is not whitespace
(?:\S)
"""
)
neg_regex = (
r"""
(?:
^(?:never|no|nothing|nowhere|noone|none|not|
havent|hasnt|hadnt|cant|couldnt|shouldnt|
wont|wouldnt|dont|doesnt|didnt|isnt|arent|aint
)$
)
|
n't"""
)
word_regex = re.compile(r"""(%s)""" % "|".join(
regex_strings), re.VERBOSE | re.I | re.UNICODE)
# For regularizing HTML entities to Unicode:
html_entity_digit_re = re.compile(r"&#\d+;")
html_entity_alpha_re = re.compile(r"&\w+;")
amp = "&"
# Generate a list containing all of the
# stop words included in stopwords.txt
def readStopWords():
stop_words = []
fp = open('stopwords.txt', 'r')
line = fp.readline()
while line:
word = line.strip()
stop_words.append(word)
line = fp.readline()
fp.close()
return stop_words
class Tokenizer:
def __init__(self, preserve_case=False):
self.preserve_case = preserve_case
def tokenize(self, s):
# Attempt to ensure unicode
try:
s = unicode(s)
except UnicodeDecodeError:
s = str(s).encode('string_escape')
s = unicode(s)
# Fix HTML character entities
s = self.htmlToUnicode(s)
# Tokenize
words = word_regex.findall(s)
# Alter case
words = [x.lower() for x in words]
# Remove stop words
stop_words = readStopWords()
words = [x for x in words if x not in stop_words]
return words
def htmlToUnicode(self, s):
# Replace all HTML entities with their
# corresponding unicode characters
html_ents = set(html_entity_digit_re.findall(s))
if len(html_ents) > 0:
for ent in html_ents:
ent_num = ent[2:-1]
try:
ent_num = int(ent_num)
s = s.replace(ent, unichr(ent_num))
except:
pass
html_ents = set(html_entity_alpha_re.findall(s))
html_ents = filter((lambda x: x != amp), html_ents)
for ent in html_ents:
ent_name = ent[1:-1]
try:
s = s.replace(ent, unichr(htmlentitydefs.
name2codepoint[ent_name]))
except:
pass
s = s.replace(amp, " and ")
return s
<file_sep>import csv
import tokenizer
import nltk.classify
from nltk.classify import NaiveBayesClassifier as nbc
from nltk.probability import FreqDist
class TweetClassifier:
def __init__(self, training_file, training_features=None,
classifier=None):
self.training_file = training_file
self.tok = tokenizer.Tokenizer()
# readTweets tokenizes training data and returns a list of tuples,
# the first element of which containins the contents of each tweet
# (represented as a list of strings) and the second element of which
# is a string representing the sentiment of the associated tweet
def readTweets(self):
tweets = []
with open(self.training_file, 'rb') as csvfile:
tweet_reader = csv.reader(csvfile, delimiter=',', quotechar='|')
for row in tweet_reader:
if '0' in row[0]:
tweets.append((self.tok.tokenize(row[5]), 'negative'))
elif '2' in row[0]:
tweets.append((self.tok.tokenize(row[5]), 'neutral'))
elif '4' in row[0]:
tweets.append((self.tok.tokenize(row[5]), 'positive'))
return tweets
# getTweetContents returns a list of all of tokens found in the
# tweets read in using readTweets
def getTrainingTweetContents(self, tweets):
all_tokens = []
for (words, sentiment) in tweets:
all_tokens.extend(words)
return all_tokens
def getTestingTweetContents(self, tweets):
all_tokens = []
for words in tweets:
all_tokens.extend(words)
# print(words)
return all_tokens
# getFeatures takes the list of tokens found in the tweets
# previously read in and returns a collection associating each
# token with the frequency of its occurance amongst the corpus of tweets
def getFeatures(self, words):
word_list = FreqDist(words)
# for entry in word_list:
# print(entry)
word_features = word_list.keys()
# for entry in word_features:
# print(entry)
return word_features
# extractTrainingFeatures returns a dictionary indicating which words in
# word_feats are also in document
def extractTrFeatures(self, document):
document_words = set(document)
# for word in document_words:
# print(word)
features = {}
for word in self.training_features:
features['contains(%s)' % word] = (word in document_words)
return features
def trainClassifier(self):
tweets = self.readTweets()
self.training_features = self.getFeatures(
self.getTrainingTweetContents(tweets))
print('Constructing training_set. . .')
training_set = nltk.classify.apply_features(self.extractTrFeatures,
tweets)
print('Training Classifier. . .')
self.classifier = nbc.train(training_set)
def classifyTweet(self, tweet):
tokenized_tweet = self.tok.tokenize(tweet)
return self.classifier.classify((self.extractTrFeatures(
(tokenized_tweet))))
def showMostInformative(self):
return self.classifier.show_most_informative_features(10)
| e9f22f4c10b2cbc776dbe845139dd3c0fae5d424 | [
"Markdown",
"Python"
] | 4 | Markdown | keatalay/TweetSentiment | 4a73394b0399d120c4480263ecce9d422e6fb225 | ea063fa228aac3ed65cfd4243e30354aaa9e78a9 |
refs/heads/master | <file_sep>#!/bin/bash
# Check Privilege
# Make sure only root can run our script
echo "正在检查权限 Checking Privilege ..."
if [ "$(id -u)" != "0" ]; then
echo "失败: 请用Root身份运行此脚本. 是不是忘了sudo?" 1>&2
echo "Fail: This script must be run as root. perhaps forget sudo?" 1>&2
exit 1
fi
echo "成功 Success"
echo ""
echo "正在将自启动脚本复制到/etc/systemd/system/ss-bash.service"
echo "Creating systemd service /etc/systemd/system/ss-bash.service"
cat << EOF > /etc/systemd/system/ss-bash.service
[Unit]
Description=ss-bash
Documentation=https://github.com/hellofwy/ss-bash/wiki
After=network.target
[Service]
User=root
Type=forking
WorkingDirectory=$(pwd)
ExecStart=$(pwd)/ssadmin.sh start
ExecStop=$(pwd)/ssadmin.sh stop
[Install]
WantedBy=multi-user.target
EOF
if [ $? -eq 0 ]; then
echo "成功 Success"
echo ""
echo "请用以下命令运行Shadowssocks"
echo "Use the following commands to start Shadowsocks"
echo "sudo systemctl daemon-reload"
echo "sudo systemctl start ss-bash.service"
echo ""
echo "请用以下命令启动Shadowssocks自启动服务"
echo "Use the following command to run Shadowsocks as service"
echo "sudo systemctl enable ss-bash.service"
fi
<file_sep>ss-bash
=======
Shadowsocks流量管理脚本
* 目前只支持python版Shadowsocks
* 目前只支持统计ipv4流量
[英文版](https://github.com/hellofwy/ss-bash/tree/en)请见`en`分支,感谢[@Yaoshicn](https://github.com/Yaoshicn)的贡献。
[使用说明][User Manual]
[User Manual]: https://github.com/hellofwy/ss-bash/wiki
| 7cc2cf1851d5a4cdb61ae25ec307f7b1615886dc | [
"Markdown",
"Shell"
] | 2 | Shell | Ghost-Assassin/ss-bash | 37a7b48561a1ce0d2ca01136f69553aca29db664 | 15bc401d76e4fb4a5348b296311c62583669ebab |
refs/heads/main | <file_sep>f = open("files/vegetables.txt","a+")
f.write("\nokra")
f.seek(0)
print(f.read())
f.close()
# with open("./files/vegetables.txt","r") as f:
# content = f.read()
# print(content)<file_sep>import pandas as pd
import numpy as np
df1 = pd.DataFrame([[1,2,3],[10,20,30]], columns=['Price','Age','Value'], index=['First','Second'])
df2 = pd.DataFrame([{"Name":"jean","Surname":"cedric"},{"Name":"Jacobs"}])
# numpy array
n = np.arange(27)
n.reshape(3, 9) # n.reshape(3,3,3)
np.asarray([1,2,3])<file_sep>import cv2
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
# img=cv2.imread("photo.jpg")
img=cv2.imread("news.jpg")
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces=face_cascade.detectMutliScale(gray_img,scaleFactor=1.1, minNeighbors=5)
for x, y, w, h in faces:
img=cv2.rectangle(img, (x,y), (x+w,y+h),(0,255,0),3)
print(type(faces))
print(faces)
resized=cv2.resize(img, (int(img.shape[1]/3), int(img.shape[0])/3))
cv2.imshow("Galaxy", resized)
cv2.waitKey(0)
cv2.destroyAllWindows()<file_sep>#making a basic Bokeh line graph
from bokeh.plotting import figure
from bokeh.io import output_file, show
import pandas
df = pandas.read_csv("data.csv")
#prepare some data
x=df["x"]
y=df["y"]
#prepare the output file
output_file("line.html")
#create a figure object
f=figure()
#create a line plot
f.line(x,y)
#write the plot in the figure object
show(f)
<file_sep>import requests
from bs4 import BeautifulSoup
r=requests.get("http://pythonhow.com/example.com")
c=r.content
soup = BeautifulSoup(c,'html.parser')
print(soup.prettify())
all=soup.find_all("div", {"class":"cities"})
names=[]
for tag in all:
names.append(tag.find("h1").text)
<file_sep>from pandas_datareader import data
import datetime
from bokeh.plotting import figure, show, output_file
from bokeh.embed import components
from bokeh.resources import CDN
def inc_dec(c, o):
if c > o :
value="Increase"
elif c < o:
value="Decrease"
else:
value="Equal"
return value
start = datetime.datetime(2020,3,1)
end = datetime.datetime(2020,3,10)
df = data.DataReader(name="AAPL", data_source="google", start=start,end=end) #AAPL is the stock symbol for a company(AAPL=apple,GOOG=google
df["Status"] = [inc_dec(c,o) for c,o in zip(df.Close, df.Open)]
df["Middle"] = (df.Open + df.Close)/2
df["Height"] = abs(df.Open - df.Close)
p=figure(x_axis_type="datetime", width=1000, height=300, sizing_mode="scale_width")
p.title.text = "Candlestick Chart"
p.grid.grid_line_alpha = 0.3
hours_12 = 12*60*60*1000
p.segment(df.index, df.High, df.index, df.Low, color="Black")
p.rect(df.index[df.Status =="Increase"], df.Middle[df.Status=="Increase"], hours_12, df.Height[df.Status=="Increase"], fill_color="#CCFFFF",
line_color="black")
p.rect(df.index[df.Status == "Decrease"], df.Middle[df.Status=="Decrease"], hours_12, df.Height[df.Status=="Decrease"], fill_color="#FF3333",
line_color="black")
script1, div1 = components(p) # components will generate the html, css of your figure
cdn_js = CDN.js_files
cdn_css = CDN.css_files
# output_file("CS.html")
# show(p)
<file_sep>import datetime
import time
import os
import pandas
'''
mynow = datetime.datetime.now()
print("the date and time is: ", mynow)
mynumber = 10
mytext = "Hello"
print(mynumber, mytext)
'''
# datatype
x = 10
y = "10"
z = 10.1
student_grade = [12, 23, 67]
sum1 = x + x
sum2 = y + y
print(sum1, sum2)
print(type(x), type(y), type(z), type(student_grade))
# function
def mean(value):
if isinstance(value, dict):
the_mean = sum(value.values()) / len(value)
else:
the_mean = sum(value) / len(value)
return the_mean
print(type(mean), type(sum))
# List comprehension
temps = [221, 234, 340,-9999, 230]
#new_temps = [temp/10 for temp in temps if temp != -9999]
new_temps = [temp/10 if temp != -9999 else 0 for temp in temps]
print(new_temps)
# more about functions
def area(a, b=3):
return a*b
def mean_improve(*args):
print(type(args))
print(args)
return sum(args)/len(args)
def mean_improve2(**kwargs):
print(kwargs)
print(type(kwargs))
return sum(kwargs.values())/len(kwargs)
print(mean_improve(1,2,4))
print(mean_improve2(a=1,b=2,c=3))
# module
while True:
if os.path.exists("files/vegetables.txt"):
with open("files/vegetables.txt") as f:
print(f.read())
time.sleep(10)
else:
with open("files/vegetables.txt","w") as f:
f.write("macabo")
while True:
if os.path.exists("files/temps_today.csv"):
data = panda.read_csv("files/temps_today.csv")
print(data.mean())
else:
print("File not found")
time.sleep(10)<file_sep>from tkinter import *
import backend, sys
window = Tk()
window.wm_title("BookStore")
def get_selected_row(event):
global selected_tuple
index = list1.curselection()[0]
selected_tuple = list1.get(index)
title_text.set(selected_tuple[1])
author_text.set(selected_tuple[2])
year_text.set(selected_tuple[3])
isbn_text.set(selected_tuple[4])
def delete_book():
id = selected_tuple[0]
backend.delete(id)
view_books()
def update_book():
backend.update(selected_tuple[0], title_text.get(), author_text.get(), year_text.get(), isbn_text.get())
view_books()
def view_books():
all_books = backend.view()
list1.delete(0,END)
for book in all_books:
list1.insert(END, book)
def search_book():
list1.delete(0, END)
result = backend.search(title_text.get(), author_text.get(), year_text.get(), isbn_text.get())
if result:
for book in result:
list1.insert(END, book)
else:
list1.insert(END, "NO RESULT")
def add_book():
backend.insert(title_text.get(), author_text.get(), year_text.get(), isbn_text.get())
list1.delete(0,END)
list1.insert(END, (title_text.get(), author_text.get(), year_text.get(), isbn_text.get()))
title_text.set('')
author_text.set('')
year_text.set('')
isbn_text.set('')
def close_window():
sys.exit()
l1=Label(window, text="Title")
l1.grid(row=0, column=0)
l2=Label(window, text="Author")
l2.grid(row=0, column=2)
l3=Label(window, text="Year")
l3.grid(row=1, column=0)
l4=Label(window, text="ISBN")
l4.grid(row=1, column=2)
title_text=StringVar()
e1=Entry(window, textvariable=title_text)
e1.grid(row=0, column=1)
author_text=StringVar()
e2=Entry(window, textvariable=author_text)
e2.grid(row=0, column=3)
year_text=StringVar()
e3=Entry(window, textvariable=year_text)
e3.grid(row=1, column=1)
isbn_text=StringVar()
e4=Entry(window, textvariable=isbn_text)
e4.grid(row=1, column=3)
list1 = Listbox(window, height=6, width=35)
list1.grid(row=2, column=0, rowspan=6, columnspan=2)
sb1=Scrollbar(window)
sb1.grid(row=2, column=2, rowspan=6)
list1.configure(yscrollcommand=sb1.set)
sb1.configure(command=list1.yview)
list1.bind("<<ListboxSelect>>", get_selected_row)
b1=Button(window, text="View All", width=12, command=view_books)
b1.grid(row=2, column=3)
b2=Button(window, text="Search Entry", width=12, command=search_book)
b2.grid(row=3, column=3)
b3=Button(window, text="Add Entry", width=12, command=add_book)
b3.grid(row=4, column=3)
b4=Button(window, text="Update Book", width=12, command=update_book)
b4.grid(row=5, column=3)
b5=Button(window, text="Delete Book", width=12,command=delete_book)
b5.grid(row=6, column=3)
b6=Button(window, text="Close", width=12, command=window.destroy)
b6.grid(row=7, column=3)
window.mainloop()
<file_sep>from tkinter import *
window = Tk() # create an instance of the window GUI
def km_to_miles():
# print(e1_value.get())
miles = float(e1_value.get())*1.6
t1.insert(END, miles)
b1 = Button(window, text="Execute", command=km_to_miles)
b1.grid(row=0, column=0, rowspan=2)
e1_value = StringVar()
e1=Entry(window, textvariable=e1_value)
e1.grid(row=2, column=0)
t1=Text(window, width=20, height=4)
t1.grid(row=2, column=1)
window.mainloop() | 92510524c697e3f47ae5b23c202b37183d8e7025 | [
"Python"
] | 9 | Python | tcloud1105/python_projects_1 | d66848d4ea6cc32cef5b624fb973a314d4ecb516 | 88ee4ea31ed5cdb43c35f58806d89fdf78128959 |
refs/heads/master | <repo_name>GigabyteDX/NpcNameChange<file_sep>/src/com/gigabytedx/namechange/Main.java
package com.gigabytedx.namechange;
import java.util.HashMap;
import java.util.logging.Logger;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import com.gigabytedx.rename.commands.SetNpcName;
import com.gigabytedx.rename.events.Interact;
public class Main extends JavaPlugin{
public HashMap<Player, String> nameSetting = new HashMap<>();
public void onEnable() {
PluginDescriptionFile pdfFile = getDescription();
Logger logger = getLogger();
registerEvents();
registerCommands();
logger.info(pdfFile.getName() + " has been enabled (V." + pdfFile.getVersion() + ")");
}
private void registerCommands() {
getCommand("setnpcname").setExecutor(new SetNpcName(this));
}
private void registerEvents() {
PluginManager pm = getServer().getPluginManager();
pm.registerEvents(new Interact(this), this);
}
public void onDisable() {
PluginDescriptionFile pdfFile = getDescription();
Logger logger = getLogger();
logger.info(pdfFile.getName() + " has been disabled (V." + pdfFile.getVersion() + ")");
}
}
| 36183bfc75edfb4caf3e76eb9ee9a16a632d097c | [
"Java"
] | 1 | Java | GigabyteDX/NpcNameChange | 10f1a73b78b4fb0df67eec2e69c9472109a47fdd | de9d9215538a265f089ac8b863c6b0874d84fa4b |
refs/heads/master | <repo_name>wsnacj/kazmath<file_sep>/src/kazmathxx.h
/*
Copyright (c) 2008, <NAME>.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef KAZMATHXX_H_INCLUDED
#define KAZMATHXX_H_INCLUDED
#include "kazmath.h"
namespace kazmathxx {
/**
* \Brief - A public class that inherits kmVec3
* and provides basic C++ operators to make it
* behave like a built in type. There are no other methods
* aside from the standard +, +=, -, -=, *, *=, /, /=
* assignment operator, copy constructor and default constructor
* \Detailed -
* Usage:
* Vec3 myVec1(1.0f, 0.0f, 0.0f);
* Vec3 myVec2(0.0f, 2.0f, 0.0f);
* Vec3 cross = myVec1 * myVec2;
* kmVec3Normalize(&cross);
* Vec3 add = myVec1 + myVec2;
* Vec3 scale = myVec1 * 10.0f;
* scale = 5.0f * myVec1; //TODO!
* float s = kmVec3Dot(&myVec1, &myVec2);
*/
struct Vec3 : public kmVec3 {
Vec3() {
this->x = this->y = this->z = 0.0f;
}
Vec3(const kmVec3& v) {
this->x = v.x;
this->y = v.y;
this->z = v.z;
}
const Vec3& operator=(const kmVec3& v) {
this->x = v.x;
this->y = v.y;
this->z = v.z;
return *this;
}
const Vec3 operator+(const kmVec3& v) const {
Vec3 result;
kmVec3Fill(&result, x + v.x, y + v.y, z + v.z);
return result;
}
const Vec3& operator+=(const kmVec3& v) {
this->x = this->x + v.x;
this->y = this->y + v.y;
this->z = this->z + v.z;
return *this;
}
const Vec3 operator-(const kmVec3& v) const {
Vec3 result;
kmVec3Fill(&result, x - v.x, y - v.y, z - v.z);
return result;
}
const Vec3& operator-=(const kmVec3& v) {
this->x = this->x - v.x;
this->y = this->y - v.y;
this->z = this->z - v.z;
return *this;
}
const Vec3 operator/(const kmScalar s) const {
Vec3 result;
kmScalar l = 1.0f / s;
kmVec3Fill(&result, x * l, y * l, z * l);
return result;
}
const Vec3& operator/=(const kmScalar s) {
float l = 1.0f / s;
this->x = this->x * l;
this->y = this->y * l;
this->z = this->z * l;
return *this;
}
/**
* Multiplication by a scalar
*/
const Vec3 operator*(const kmScalar s) const {
Vec3 result;
kmVec3Fill(&result, x * s, y * s, z * s);
return result;
}
/**
* I've decided to make multiplication of 2 vectors to
* mean the cross product
*/
const Vec3 operator*(const kmVec3& v) const {
kmVec3 result;
result.x = (y * v.z) - (z * v.y);
result.y = (z * v.x) - (x * v.z);
result.z = (x * v.y) - (y * v.x);
return result;
}
/**
* Cross product then assign the result
*/
const Vec3& operator*=(const kmVec3& v) {
kmVec3 result;
result.x = (y * v.z) - (z * v.y);
result.y = (z * v.x) - (x * v.z);
result.z = (x * v.y) - (y * v.x);
this->x = result.x;
this->y = result.y;
this->z = result.z;
return *this;
}
const Vec3& operator*=(const float s) {
this->x = this->x * s;
this->y = this->y * s;
this->z = this->z * s;
return *this;
}
};
struct Vec2 : public kmVec2 {
Vec2() {
this->x = this->y = 0.0f;
}
Vec2(const kmVec2& v) {
this->x = v.x;
this->y = v.y;
}
const Vec2& operator=(const kmVec2& v) {
this->x = v.x;
this->y = v.y;
return *this;
}
const Vec2 operator+(const kmVec2& v) const {
Vec2 result;
kmVec2Fill(&result, x + v.x, y + v.y);
return result;
}
const Vec2& operator+=(const kmVec2& v) {
this->x = this->x + v.x;
this->y = this->y + v.y;
return *this;
}
const Vec2 operator-(const kmVec2& v) const {
Vec2 result;
kmVec2Fill(&result, x - v.x, y - v.y);
return result;
}
const Vec2& operator-=(const kmVec2& v) {
this->x = this->x - v.x;
this->y = this->y - v.y;
return *this;
}
const Vec2 operator/(const kmScalar s) const {
Vec2 result;
kmScalar l = 1.0f / s;
kmVec2Fill(&result, x * l, y * l);
return result;
}
const Vec2& operator/=(const kmScalar s) {
float l = 1.0f / s;
this->x = this->x * l;
this->y = this->y * l;
return *this;
}
/**
* Multiplication by a scalar
*/
const Vec2 operator*(const kmScalar s) const {
Vec2 result;
kmVec2Fill(&result, x * s, y * s);
return result;
}
const Vec2& operator*=(const float s) {
this->x = this->x * s;
this->y = this->y * s;
return *this;
}
};
struct Mat4 : public kmMat4 {
Mat4() {
for (int i = 0; i < 16; ++i) {
this->mat[i] = 0.0f;
}
}
Mat4(const kmMat4& m) {
for (int i = 0; i < 16; ++i) {
this->mat[i] = m.mat[i];
}
}
const Mat4& operator=(const kmMat4& m) {
for (int i = 0; i < 16; ++i) {
this->mat[i] = m.mat[i];
}
return *this;
}
};
struct Mat3 : public kmMat3 {
Mat3() {
for (int i = 0; i < 9; ++i) {
this->mat[i] = 0.0f;
}
}
Mat3(const kmMat3& m) {
for (int i = 0; i < 9; ++i) {
this->mat[i] = m.mat[i];
}
}
const Mat3& operator=(const kmMat3& m) {
for (int i = 0; i < 9; ++i) {
this->mat[i] = m.mat[i];
}
return *this;
}
};
/**
* Describes a plane, publicly inherits kmPlane but implements
* object oriented methods for C++
*/
struct Plane : public kmPlane {
Plane() {
this->a = 0.0f;
this->b = 0.0f;
this->c = 0.0f;
this->d = 0.0f;
}
Plane(const kmPlane& p) {
this->a = p.a;
this->b = p.b;
this->c = p.c;
this->d = p.d;
}
const Plane& operator=(const kmPlane& p) {
this->a = p.a;
this->b = p.b;
this->c = p.c;
this->d = p.d;
return *this;
}
};
struct Quaternion : public kmQuaternion {
Quaternion() {
this->w = 0.0f;
this->x = 0.0f;
this->y = 0.0f;
this->z = 0.0f;
}
Quaternion(const kmQuaternion q) {
this->w = q.w;
this->x = q.x;
this->y = q.y;
this->z = q.z;
}
const Quaternion& operator=(const kmQuaternion& q) {
this->w = q.w;
this->x = q.x;
this->y = q.y;
this->z = q.z;
return *this;
}
};
}
#endif // KAZMATHXX_H_INCLUDED
<file_sep>/CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
PROJECT(Kazmath)
SET(CMAKE_C_FLAGS "-std=c99")
SET(CMAKE_INSTALL_PREFIX, "/usr")
ADD_SUBDIRECTORY(src bin)
<file_sep>/src/CMakeLists.txt
SET(KAZMATH_HEADERS
vec2.h
vec3.h
vec4.h
mat4.h
mat3.h
plane.h
utility.h
quaternion.h
aabb.h
kazmath.h
)
SET(GL_UTILS_HEADERS
GL/mat4stack.h
GL/matrix.h
)
SET(KAZMATH_SRCS
mat4.c
mat3.c
plane.c
vec4.c
quaternion.c
vec2.c
vec3.c
utility.c
aabb.c
GL/mat4stack.c
GL/matrix.c
)
#ADD_LIBRARY(Kazmath STATIC ${KAZMATH_SRCS})
#INSTALL(TARGETS Kazmath ARCHIVE DESTINATION lib)
ADD_LIBRARY(Kazmath STATIC ${KAZMATH_SRCS})
INSTALL(TARGETS Kazmath ARCHIVE DESTINATION lib)
#ADD_LIBRARY(KazmathGL STATIC ${GL_UTILS_SRCS})
#INSTALL(TARGETS KazmathGL ARCHIVE DESTINATION lib)
INSTALL(FILES ${KAZMATH_HEADERS} DESTINATION include/kazmath)
INSTALL(FILES ${GL_UTILS_HEADERS} DESTINATION include/kazmath/GL)
<file_sep>/test-apps/CUnitTest/testMat3.c
#include <stdio.h>
#include <string.h>
#include <CUnit/Basic.h>
#include <kazmath/mat3.h>
void print_matrix3(const kmMat3* mat)
{
const int max = 3;
printf("\n\n");
for(int i = 0; i < max; i++)
{
printf("|");
for(int j = 0; j < max; j++)
{
if(j > 0)
{
printf("\t");
}
printf("%f",mat->mat[i + max*j]);
}
printf("|\n");
}
printf("\n");
}
void testMat3Inverse1(void)
{
kmMat3 mat;
CU_ASSERT(NULL != kmMat3Identity(&mat));
print_matrix3(&mat);
printf("\nDeterminant of Identity matrix is: %f\n", kmMat3Determinant(&mat));
kmMat3 adj;
CU_ASSERT(NULL != kmMat3Adjugate(&adj, &mat));
print_matrix3(&adj);
CU_ASSERT(NULL != kmMat3Inverse(&mat, kmMat3Determinant(&mat), &mat));
print_matrix3(&mat);
CU_ASSERT(kmMat3IsIdentity(&mat));
}
void testMat3Transpose(void)
{
kmMat3 mat;
float temp[] = { 0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f };
memcpy(mat.mat, temp, sizeof(float) * 9);
print_matrix3(&mat);
kmMat3 transpose;
float temp2[] = {8.0f, 7.0f, 6.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f, 0.0f};
memcpy(transpose.mat, temp2, sizeof(float) * 9);
print_matrix3(&transpose);
kmMat3 result;
CU_ASSERT(NULL != kmMat3Transpose(&result, &mat));
print_matrix3(&result);
CU_ASSERT(kmMat3AreEqual(&transpose, &result));
}
int addMat3Tests(CU_pSuite suite)
{
/* add the tests to the suite */
if ((NULL == CU_add_test(suite, "kmMat3Inverse Identity - test", testMat3Inverse1)))
{
CU_cleanup_registry();
return CU_get_error();
}
if ((NULL == CU_add_test(suite, "kmMat3Transpose - test", testMat3Transpose)))
{
CU_cleanup_registry();
return CU_get_error();
}
return CU_get_error();
}
| 4450480a009bf39a5991a4902cae5a9c559d669e | [
"C",
"CMake",
"C++"
] | 4 | C++ | wsnacj/kazmath | 4a496e623cef94751896da1c3c8ae4fd22655f7c | 24a6dee0eb20180e3a401ae8789920ffcd33425f |
refs/heads/master | <repo_name>ar500/CityInfo<file_sep>/CityInfo.API/Controllers/CitiesController.cs
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using CityInfo.API.Models;
using CityInfo.API.Services;
using Microsoft.AspNetCore.Mvc;
namespace CityInfo.API.Controllers
{
[Route("api/cities")] // Set route at controller level
public class CitiesController : Controller
{
// TODO: Use AutoMapper for this.
private readonly ICityInfoRepository _cityInfoRepository;
public CitiesController(ICityInfoRepository cityInfoRepository)
{
_cityInfoRepository = cityInfoRepository;
}
[HttpGet] // Provide separate methods here.
public IActionResult GetCities()
{
var cityEntities = _cityInfoRepository.GetCities();
var results = Mapper.Map<IEnumerable<CityWithoutPointsOfInterestDto>>(cityEntities); // use automapper to create the mapping....
return Ok(results);
}
[HttpGet("{id}")]
public IActionResult GetCityById(int id, bool includePointsOfInterest = false)
{
var returnCity = _cityInfoRepository.GetCity(id, includePointsOfInterest);
if (returnCity == null)
{
return NotFound();
}
if (includePointsOfInterest)
{
var resultDto = Mapper.Map<CityDto>(returnCity);
return Ok(resultDto);
}
else
{
var resultDto = Mapper.Map<CityWithoutPointsOfInterestDto>(returnCity);
return Ok(resultDto);
}
}
}
}
<file_sep>/CityInfo.API/Controllers/PointsOfInterestController.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using AutoMapper;
using CityInfo.API.Entities;
using CityInfo.API.Models;
using CityInfo.API.Services;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace CityInfo.API.Controllers
{
[Route("api/cities")]
public class PointsOfInterestController : Controller
{
private readonly ILogger<PointsOfInterestController> _logger;
private readonly IMailService _mailService;
private readonly ICityInfoRepository _cityInfoRepository;
public PointsOfInterestController(ILogger<PointsOfInterestController> logger, IMailService mailService, ICityInfoRepository cityInfoRepository)
{
_logger = logger;
_mailService = mailService;
_cityInfoRepository = cityInfoRepository;
}
[HttpGet("{cityId}/pointsofinterest")]
public IActionResult GetPointsOfInterest(int cityId)
{
try
{
if (!_cityInfoRepository.CityExists(cityId))
{
_logger.LogInformation($"The city {cityId} wasn't found when accessing points of interest.");
return NotFound();
}
var pointsOfInterestForCity = _cityInfoRepository.GetPointsOfInterest(cityId);
var resultsList = Mapper.Map<IEnumerable<PointOfInterestDto>>(pointsOfInterestForCity);
return Ok(resultsList);
}
catch (Exception ex)
{
_logger.LogCritical($"Exception while getting points of interest for city with id {cityId}.", ex);
return StatusCode(500, "A problem happened while handling your request.");
}
}
[HttpGet("{cityId}/pointsofinterest/{id}", Name = "GetPointOfInterest")]
public IActionResult GetPointOfInterest(int cityId, int id)
{
if (!_cityInfoRepository.CityExists(cityId))
{
return NotFound();
}
var pointOfInterestEntity = _cityInfoRepository.GetPointOfInterest(cityId, id);
if (pointOfInterestEntity == null)
{
return NotFound();
}
var pointOfInterestResult = Mapper.Map<PointOfInterestDto>(pointOfInterestEntity);
return Ok(pointOfInterestResult);
}
[HttpPost("{cityId}/pointsofinterest")]
public IActionResult CreatePointOfInterest(int cityId,
[FromBody] PointOfInterestForCreationDto pointOfInterest)
{
if (pointOfInterest == null)
{
return BadRequest();
}
if (pointOfInterest.Description == pointOfInterest.Name)
{
ModelState.AddModelError("Description", "The provided description should be different from the name.");
}
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (!_cityInfoRepository.CityExists(cityId))
{
return NotFound();
}
var mappedPointOfInterest = Mapper.Map<PointOfInterest>(pointOfInterest);
_cityInfoRepository.AddPointOfInterestForCity(cityId, mappedPointOfInterest);
if (!_cityInfoRepository.Save())
{
_logger.LogError("Changes were not saved to the database.");
return StatusCode(500, "A problem happened while handling your request");
}
var createdPointOfInterestForReturn = Mapper.Map<PointOfInterestDto>(mappedPointOfInterest);
return CreatedAtRoute("GetPointOfInterest", new
{cityId = cityId, id = createdPointOfInterestForReturn.Id}, createdPointOfInterestForReturn);
}
[HttpPut("{cityId}/pointsofinterest/{id}")] // You must update the entire resource here.
public IActionResult UpdatePointOfInterest(int cityId, int id,
[FromBody] PointOfInterestForUpdateDto pointOfInterest)
{
if (pointOfInterest == null)
{
Debug.WriteLine("no poi in body");
return BadRequest();
}
if (pointOfInterest.Description == pointOfInterest.Name)
{
ModelState.AddModelError("Description", "The provided description should be different from the name.");
}
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (!_cityInfoRepository.CityExists(cityId))
{
Debug.WriteLine("no city");
return NotFound();
}
var pointOfInterestFromRepo = _cityInfoRepository.GetPointOfInterest(cityId, id);
if (pointOfInterestFromRepo == null)
{
Debug.WriteLine("no poi from repo");
return NotFound();
}
Mapper.Map(pointOfInterest, pointOfInterestFromRepo); // This effectively puts the entity that is being tracked by our context into a modified state.
if (!_cityInfoRepository.Save())
{
_logger.LogError("Unable to save changes to an updated point of interest.");
return StatusCode(500, "A problem happened while handling your request.");
}
return NoContent(); //request completed, but nothing to return. typical for updates.
}
[HttpPatch("{cityId}/pointsofinterest/{id}")] // partial updates
public IActionResult PartiallyUpdatePointOfInterest(int cityId, int id,
[FromBody] JsonPatchDocument<PointOfInterestForUpdateDto> patchDoc)
{
if (patchDoc == null)
{
return BadRequest();
}
if (!_cityInfoRepository.CityExists(cityId))
{
return NotFound();
}
var pointOfInterestEntity = _cityInfoRepository.GetPointOfInterest(cityId, id);
if (pointOfInterestEntity == null)
{
return NotFound();
}
var pointOfInterestToPatch = Mapper.Map<PointOfInterestForUpdateDto>(pointOfInterestEntity);
patchDoc.ApplyTo(pointOfInterestToPatch, ModelState);
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (pointOfInterestToPatch.Description == pointOfInterestToPatch.Name)
{
ModelState.AddModelError("Description", "The provided name and description should differ.");
}
TryValidateModel(pointOfInterestToPatch); // You have to validate the internal model here. The ModelState is validating the JsonPatchDocument.
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Mapper.Map(pointOfInterestToPatch, pointOfInterestEntity);
if (!_cityInfoRepository.Save())
{
_logger.LogError("Unable to save changes to an updated point of interest.");
return StatusCode(500, "A problem happened while handling your request.");
}
return NoContent(); //request completed, but nothing to return. typical for updates.
}
[HttpDelete("{cityId}/pointsofinterest/{id}")]
public IActionResult DeletePointOfInterest(int cityId, int id)
{
if (!_cityInfoRepository.CityExists(cityId))
{
return NotFound();
}
var pointOfInterestFromRepo = _cityInfoRepository.GetPointOfInterest(cityId, id);
if (pointOfInterestFromRepo == null)
{
return NotFound();
}
_cityInfoRepository.DeletePointOfInterest(pointOfInterestFromRepo);
_mailService.Send("Point of interest deleted",
$"Point of interest {pointOfInterestFromRepo.Name} with id {pointOfInterestFromRepo.Id} was deleted.");
if (!_cityInfoRepository.Save())
{
_logger.LogError("Unable to save changes to an updated point of interest.");
return StatusCode(500, "A problem happened while handling your request.");
}
return NoContent();
}
}
}
| e67cf309fecaa2e322090c1810896e8e155b2a28 | [
"C#"
] | 2 | C# | ar500/CityInfo | 37baf62c07b7aff0052b94af84180ef136147f66 | 152a80fd2ba50e32400fc6ae4aa15a545d5958fc |
refs/heads/main | <file_sep>import com.thoughtworks.gauge.Step;
import com.thoughtworks.gauge.Table;
import com.thoughtworks.gauge.TableRow;
import io.appium.java_client.MobileElement;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashSet;
import static org.junit.Assert.assertEquals;
/**
* @author <NAME>
* @version 1.0
* @since 2021-07-02
*/
public class StepImplementation extends BaseTest {
WebDriverWait wait = new WebDriverWait(appiumDriver, 60);
@Step("<x> saniye beklenildi.")
public void waitForSecond(int x) throws InterruptedException {
Thread.sleep(1000 * x);
System.out.println(x + "saniye beklenildi.");
}
@Step("<id> li elemente tikla")
public void clickById(String id) {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(id))).click();
System.out.println("Elemente tiklandi");
}
@Step("<id> li elemente <key> degerini gir")
public void sendKeysById(String id, String key) {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(id))).sendKeys(key);
System.out.println("Send Keys yazıldı.");
}
@Step("<xpath> xpath li elemente tikla")
public void clickByXpath(String xpath) {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath))).click();
System.out.println("Elemente tiklandi");
}
@Step("<check> Ucus listesini kontrol et")
public void checkList(String check){
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(check)));
Assert.assertEquals("SORT AND FILTER", appiumDriver.findElementById(check).getText());
}
}
| 727c84d0e42f1af0d9f2ecdd7196fdf9babae062 | [
"Java"
] | 1 | Java | naymanburak/ThyMobilOtomasyon | 1e05873f82cd81500ab6bcd37c994bfd37bf0aa5 | 509591457b645b1b24f9bc37e280d844595f018f |
refs/heads/master | <file_sep>require 'test_helper'
class OrderMailerTest < ActionMailer::TestCase
fixtures :orders
fixtures :line_items
test "received" do
order = orders(:one)
line_item = line_items(:one)
order.line_items << line_item
mail = OrderMailer.received(order)
assert_equal 'Pragmatic store order confirmation', mail.subject
assert_equal [order.email], mail.to
assert_equal ['<EMAIL>'], mail.from
assert_match /1 x #{line_item.product.title}/, mail.body.encoded
end
test "shipped" do
order = orders(:one)
line_item = line_items(:one)
order.line_items << line_item
mail = OrderMailer.shipped(orders(:one))
assert_equal 'Pragmatic store order shipped', mail.subject
assert_equal [orders(:one).email], mail.to
assert_equal ['<EMAIL>'], mail.from
assert_match /<td>1×<\/td>\s*<td>#{line_item.product.title}<\/td>/, mail.body.encoded
end
end
<file_sep>class ErrorMailer < ApplicationMailer
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
# en.error_mailer.invalid_cart_id.subject
#
def invalid_cart_id(cart_id)
@cart_id = cart_id
mail to: '<EMAIL>', subject: 'Attempt to access invalid cart'
end
end
<file_sep>require 'test_helper'
class CartTest < ActiveSupport::TestCase
fixtures :products
test "add products" do
cart = Cart.new
LineItem.delete_all
cart.add_product(products(:one)).save!
cart.add_product(products(:ruby)).save!
cart.add_product(products(:ruby)).save!
assert_equal 2, cart.line_items.count
total_price = products(:one).price + 2 * products(:ruby).price
assert_equal total_price, cart.total_price
end
end
<file_sep>class Cart < ApplicationRecord
has_many :line_items, dependent: :destroy
def add_product(product)
item = line_items.find_by(product_id: product.id) || line_items.build(product_id: product.id, price: product.price)
item.quantity += 1 if item.persisted?
item
end
def total_price
line_items.to_a.sum { |item| item.total_price }
end
end
<file_sep>module OrdersHelper
def prepare_pay_types_options
options = PayType.pluck(:title, :id)
return options if I18n.locale == :en
options.map { |pair| t(".#{pair[0].parameterize(separator: '_')}") }
end
end
<file_sep>class ReplacePayTypeWithPayTypeIdInOrdersTable < ActiveRecord::Migration[5.1]
def change
rename_column :orders, :pay_type, :pay_type_id
end
end
<file_sep>require 'test_helper'
class ErrorMailerTest < ActionMailer::TestCase
test "invalid_cart_id" do
mail = ErrorMailer.invalid_cart_id('x')
assert_equal "Attempt to access invalid cart", mail.subject
assert_equal ["<EMAIL>"], mail.to
assert_equal ["<EMAIL>"], mail.from
assert_match "Somebody try to access to invalid cart id: x", mail.body.encoded
end
end
<file_sep># Preview all emails at http://localhost:3000/rails/mailers/error_mailer
class ErrorMailerPreview < ActionMailer::Preview
# Preview this email at http://localhost:3000/rails/mailers/error_mailer/invalid_cart_id
def invalid_cart_id
ErrorMailer.invalid_cart_id
end
end
<file_sep>require 'test_helper'
class UserStoriesTest < ActionDispatch::IntegrationTest
fixtures :products
fixtures :orders
fixtures :pay_types
fixtures :users
include ActiveJob::TestHelper
# A user goes to the index page. They select a product, adding it to their
# cart, and check out, filling in their details on the checkout form. When
# they submit, an order is created containing their information, along with a
# single line item corresponding to the product they added to their cart.
test "buying a product" do
# remember initial state
start_order_count = Order.count
ruby_book = products(:ruby)
# user goes to index page
get '/'
assert_response :success
assert_select 'h1', 'Your Pragmatic Catalog'
# user click add product button that uses AJAX
post '/line_items', params: { product_id: ruby_book.id }, xhr: true
assert_response :success
cart = Cart.find(session[:cart_id])
assert_equal 1, cart.line_items.count
assert_equal ruby_book, cart.line_items.first.product
# user go to 'check out' page
get '/orders/new'
assert_response :success
assert_select 'legend', 'Please Enter Your Details'
# user fills form and send create order request
perform_enqueued_jobs do
post '/orders', params: {
order: {
name: 'Denis',
address: 'Address',
email: '<EMAIL>',
pay_type_id: pay_types(:one).id
}
}
follow_redirect!
assert_response :success
assert_select 'h1', 'Your Pragmatic Catalog'
cart = Cart.find(session[:cart_id])
assert_equal 0, cart.line_items.count
assert_equal start_order_count + 1, Order.count
order = Order.last
assert_equal 'Denis', order.name
assert_equal 'Address', order.address
assert_equal '<EMAIL>', order.email
assert_equal pay_types(:one), order.pay_type
assert_equal 1, order.line_items.count
assert_equal ruby_book, order.line_items.first.product
mail = ActionMailer::Base.deliveries.last
assert_equal ["<EMAIL>"], mail.to
assert_equal '<NAME> <<EMAIL>>', mail[:from].value
assert_equal "Pragmatic store order confirmation", mail.subject
end
end
# An seller goes to the orders page. They see orders that customer made.
# They click ship.
test "ship order" do
order = orders(:one)
# user goes to orders page
get '/orders'
assert_response :success
assert_select 'h1', 'Orders'
assert_select ".order_row_#{order.id}", 1
# user click ship order
perform_enqueued_jobs do
post "/orders/#{order.id}/ship"
follow_redirect!
assert_response :success
assert_select 'h1', 'Orders'
assert_select ".order_row_#{order.id}", 1
assert_select '#notice', "Order ##{order.id} was successfully shipped!"
assert_select ".order_row_#{order.id} td", 'Shipped'
mail = ActionMailer::Base.deliveries.last
assert_equal [order.email], mail.to
assert_equal '<NAME> <<EMAIL>>', mail[:from].value
assert_equal "Pragmatic store order shipped", mail.subject
end
end
# User try to access invalid cart. They go to /carts/x page, where x is not user's cart id
test "invalid cart access" do
perform_enqueued_jobs do
get '/carts/x'
follow_redirect!
assert_response :success
assert_select 'h1', 'Your Pragmatic Catalog'
assert_select '#notice', "Invalid cart"
mail = ActionMailer::Base.deliveries.last
assert_equal ['<EMAIL>'], mail.to
assert_equal '<EMAIL>', mail[:from].value
assert_equal "Attempt to access invalid cart", mail.subject
end
end
end
<file_sep>module ApplicationHelper
def hidden_div_if(condition, attrs = {}, &block)
attrs['style'] = 'display: none' if condition
content_tag('div', attrs, &block)
end
end
| 0d5d6b086a3b69276a8b20f2933b83b6fa71dbf0 | [
"Ruby"
] | 10 | Ruby | robot-den/depot_5 | 1be239a78a3beb40a76e248d9ad4f94b09e5b7de | a53fa72e65a7176a68b5941ca1ae25681a605066 |
refs/heads/master | <file_sep>package ihsusta.java;
import java.util.Arrays;
/**
* 顺序线性表java描述
* @param <T>
*/
public class SequenceList<T> {
private final int DEFAULT_SIZE = 16;
private int capacity; // 数据长度
private Object[] elementData; // 元素数据
private int size = 0; // 当前长度
// 以默认数组长度创建空顺序线性表
public SequenceList() {
capacity = DEFAULT_SIZE;
elementData = new Object[capacity];
}
// 以一个初始化元素创建顺序线性表
public SequenceList(T element) {
this();
elementData[0] = element;
size++;
}
/**
* 以指定长度的数据来创建顺序线性表
*
* @param element 指定顺序线性表中第一个元素
* @param initSize 指定顺序线性表底层数组的长度
*/
public SequenceList(T element, int initSize) {
capacity = 1;
while (capacity < initSize) {
capacity <<= 1;
}
elementData = new Object[capacity];
elementData[0] = element;
size++;
}
// 获取顺序线性表的大小
public int length() {
return size;
}
// 获取顺序线性表中索引为i处的元素
public T get(int i) {
if (i < 0 || i >= size) {
throw new IndexOutOfBoundsException("线性表索引越界");
}
return cast(elementData[i]);
}
// 查找顺序线性表中指定元素的索引
public int locate(T element) {
for (int i = 0; i < size; i++) {
if (elementData[i].equals(element)) {
return i;
}
}
return -1;
}
// 向顺序线性表的指定位置插入一个元素
public void insert(T element, int index) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException("线性表索引越界");
}
ensureCapacity(size + 1);
System.arraycopy(elementData, index, elementData, index + 1, size - index);
elementData[index] = element;
size++;
}
// 线性顺序表添加一个元素
public void add(T element) {
insert(element, size);
}
// 适配容量
private void ensureCapacity(int minCapatity) {
if (capacity < minCapatity) {
while (capacity < minCapatity) {
capacity <<= 1;
}
elementData = Arrays.copyOf(elementData, capacity);
}
}
// 删除指定索引位置的元素 先判断索引是否有效 将索引位置元素删除 将删除元素之后的所有元素复制到删除元素的位置
// 并将最后元素置为null 返回删除的元素
public T delete(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("线性表索引越界");
}
T oldValue = cast(elementData[index]);
int delIndex = size - index - 1;
if (index > 0) {
System.arraycopy(elementData, index + 1, elementData, index, delIndex);
}
// 将最后一个元素清空
elementData[--size] = null;
return oldValue;
}
// 删除并返回线性表最后一个元素
public T pop() {
return delete(size - 1);
}
// 判断线性表是否为空
public boolean isEmpty() {
return size == 0;
}
// 清空线性表
public void clear() {
// for 循环
// ||
// Arrays.fill(elementData,null);
for (Object element : elementData) {
element = null;
}
size = 0;
}
// 重写toString
@Override
public String toString() {
if(size == 0){
return "[]";
}
StringBuilder sb = new StringBuilder("[");
for (Object element :elementData){
sb.append(element.toString()).append(",");
}
return sb.deleteCharAt(sb.lastIndexOf(",")).append("]").toString();
}
@SuppressWarnings("unchecked")
private static <T> T cast(Object obj) {
return (T) obj;
}
}
| 83b756af02796352a970a957a687b229cdda82d7 | [
"Java"
] | 1 | Java | atsushinee/structure | 9f0a2efbb52165c89d11d81c52a7eb534959e98d | dba36a21114694610c4725c43202e5ed902540e5 |
refs/heads/master | <repo_name>Suraj0712/AlgoExpert<file_sep>/1_arrays_easy_two_number_sum.cpp
/*Question
Write a function that takes in a non-empty array of dIstInct Integers and an Integer representing a target sum.
If any two numbers In the Input array sum up to the target sum, the function should return them In an array,
In any order. If no two numbers sum up to the target sum, the function should return an empty array.
Note that the target sum has to be obtained by summing two different Integers In the array;
you can't add a single Integer to Itself To obtain the target sum.
You can assume that there wIll be at most one pair of numbers summing up to the target sum.
*/
// Test case {"array": [3, 5, -4, 8, 11, 1, -1, 6], "targetSum": 10}
// Approach 1 => Time = O(n^2) | Space = O(1)
// Find all the possible pairs and check there sum
#include <vector>
using namespace std;
vector<int> twoNumberSum(vector<int> array, int targetSum)
{
for(auto i: array)
{
for(auto j: array)
{
if(i+j == targetSum and i!=j)
{
return {i,j};
}
}
}
return {};
}
// Approach 2 => Time = O(nlog(n)) | Space = O(1)
// Sort the array and then use two pointers to find the sum
#include <vector>
using namespace std;
vector<int> twoNumberSum(vector<int> array, int targetSum) {
sort(array.begin(),array.end());
int lower = 0, higher = array.size()-1;
while(lower<higher)
{
if(array[lower] + array[higher] == targetSum)
{
return {array[lower] , array[higher]};
}
else if(array[lower] + array[higher] < targetSum)
{
lower++;
}
else
{
higher--;
}
}
return {};
}
// Approach 3 => Time = O(n) | Space = O(n)
// Create a unordered set of number and before inserting the number to array check whether sum-num already present in the set
#include <vector>
using namespace std;
vector<int> twoNumberSum(vector<int> array, int targetSum)
{
unordered_set<int> s;
auto it = s.begin();
for(auto i: array)
{
it = s.find(targetSum - i);
if(it == s.end())
{
s.insert(i);
}
else
{
return {i, targetSum - i};
}
}
return {};
}<file_sep>/8_array_medium_longest_peak.cpp
/*Question
Write a function that takes In an array of Integers and returns the length of the longest peak in the array. peak Is defined as adjacent Integers In the array that are strictly Increasing until they reach a top (the highest value In the peak), at which point they become strictly decreasing. At least three Integers are required to form a peak. For example, the Integers 1, 4, 10, 2 forms a peak, but the Integers 4,0,10 don't, and neither do the Integers 1,2,2,0 simIlarly, the Integers 1, 2, 3 don't form a peak because there aren't any strictly decreasing Integers atter the 3.
*/
// Test case {{"array": [1, 2, 3, 3, 4, 0, 10, 6, 5, -1, -3, 2, 3]}
// Approach 1 => Time = O(n) | Space = O(1)
// traverse the array and whenever you encounter the peak check for the both sides for its span.
using namespace std;
int findLeftLen(vector<int> array, int i)
{
int left =0;
while(i>=1 and array[i]>array[i-1])
{
left++;
i--;
}
return left;
}
int findRightLen(vector<int> array, int i)
{
int right =0;
while(i<array.size()-1 and array[i]>array[i+1])
{
right++;
i++;
}
return right;
}
int longestPeak(vector<int> array)
{
if(array.size()<2)
{
return 0;
}
int cur =0;
int peak_length = 0;
for(int i=1; i<array.size()-1; i++)
{
cout<<i<<"\n";
if(array[i-1]<array[i] and array[i]>array[i+1])
{
cur = findRightLen(array, i) + findLeftLen(array, i)+1;
if(cur>peak_length)
{
peak_length = cur;
}
cout<<"Peak: "<<array[i]<<"left: "<<findLeftLen(array, i)<<"right: "<<findRightLen(array, i)<<" current:"<<cur<<"\n";
i = i + findRightLen(array, i);
}
}
return peak_length;
}
<file_sep>/7_array_medium_spiral_traverse.cpp
/*Question
Write a function that takes In an n x m two-dimensional array (that can be sguare-shaped when n = m) and returns a one, dimensional array of all the array's elements in spiral order.
Spiral order starts at the top left comer of the two-dimensional array, goes to the right, a. proceeds In a spiral pattern all the way until every element has been vislt..
*/
// Test case {"array": [[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]]}
// Approach 1 => Time = O(n) | Space = O(n)
// write a function which which returns the perimeter of array (Four for loops for 4 directions). and when the remaining element are in linear shape just traverse them
using namespace std;
vector<int> spiralTraverse(vector<vector<int>> array)
{
// Write your code here.
if(array.size() == 0)
{
return {};
}
vector<int> result = {};
int start_row = 0;
int end_row = array.size() - 1;
int start_col = 0;
int end_col = array[0].size() - 1;
while(start_row <= end_row and start_col <= end_col)
{
for(int col = start_col; col<=end_col ; col++)
{
result.push_back(array[start_row][col]);
}
for(int row = start_row + 1; row<=end_row; row++)
{
result.push_back(array[row][end_col]);
}
for(int col = end_col - 1; col >= start_col; col--)
{
if(start_row == end_row)
{
break;
}
result.push_back(array[end_row][col]);
}
for(int row = end_row - 1; row > start_row; row--)
{
if(start_col == end_col)
{
break;
}
result.push_back(array[row][start_col]);
}
start_row++;
end_row--;
start_col++;
end_col--;
}
return result;
}
<file_sep>/smartpointer.cpp
// WHne using vector its best practise to declare the tentative size beforehead
// insert vs emplace
// when you use insert -> the object is created and then its copy is pushed to containier
// in emplace-> we dont have to construct object explicitely and no need to copy
// so n emplace the object is directly created in place in the container based on the value
// Smart pointer
// we use the smart pointer so we can not have a memory leak
// smart pointer is a template wrapper and we wrap the pointer in the class so we dont have to delete it explicitely
// the smart pointer is automatically deleted whne the distructor is invoked
// following is the basic working of the smart pointers
// #include <iostream>
// using namespace std;
// template <class T>
// class SmartPointer
// {
// private:
// T* ptr_;
// public:
// SmartPointer(T* ptr = nullptr)
// {
// ptr_ = ptr;
// }
// ~SmartPointer()
// {
// delete ptr_;
// ptr_ = nullptr;
// }
// T& operator*()
// {
// return *ptr_;
// }
// };
// int main()
// {
// SmartPointer<int> P(new int(5));
// cout<<*P;
// *P=7;
// cout<<*P;
// return 0;
// }
// Unique Pointer
// #include <iostream>
// #include <memory>
// using namespace std;
// class Check
// {
// private:
// int x_;
// int y_;
// public:
// Check(int x=0, int y=0):x_{x}, y_{y}{}
// int get_x()
// {
// return x_;
// }
// };
// int main()
// {
// unique_ptr<Check> p = make_unique<Check>(12,20);
// Check * obj_adr = p.get();
// // cout<<obj_adr;
// // cout<<p->get_x();
// unique_ptr<Check> p2 = move(p);
// Check * adr = p2.release();
// return 0;
// }
// Shared pointer
// in the shared pointer we also maintain the log of how many sharepointer objects are pointing to our pointer
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class KidsData
{
private:
int age;
string name;
public:
KidsData(int a=0, string n="")
{
age =a;
name =n;
}
int getAge()
{
return this->age;
}
string getname()
{
return this->name;
}
~KidsData()
{
}
};
int main()
{
vector<KidsData*> v;
KidsData* k1_adr = new KidsData(3,"wan");
KidsData* k2_adr = new KidsData(4,"sur");
KidsData* k3_adr = new KidsData(5,"sah");
KidsData* k4_adr = new KidsData(6,"ulk");
KidsData* k5_adr = new KidsData(7,"sha");
v.push_back(k1_adr);v.push_back(k2_adr);v.push_back(k3_adr);v.push_back(k4_adr);v.push_back(k5_adr);
for(auto it: v)
{
cout<<it->getAge()<<"\n";
}
auto it = v.begin();
advance(it,3);
v.erase(it);
for(auto it: v)
{
cout<<it->getAge()<<"\n";
}
return 0;
}<file_sep>/11_string_palindrome_check.cpp
/*Question
Write a function that takes in a non-empty string and thatreturns a boolean representing whether the string is a palindrome. A palindrome is defined as a string that's written the same forward and backward. note that single-character string are pamindromes.
*/
// {"string": "abcdcba"}
// Approach 1 => Time = O(n) | Space = O(1)
// handle the edge cases bychecking the length of string. based on the string length iterate and and compair the mirroring character.
using namespace std;
bool isPalindrome(string str)
{
if(str.size()<2)
{
return true;
}
int st = str.size()/2 - 1;
if(str.size()%2 == 0)
{
int count =1;
for(int i=st; i>=0; i--)
{
if(str[i] != str[st+count]){return false;}
count++;
}
}
else
{
int count =2;
for(int i=st; i>=0; i--)
{
if(str[i] != str[st+count]){return false;}
count++;
}
}
return true;
}
<file_sep>/10_string_easy_caesar_cipher_encryptor.cpp
/*Question
Given a non-empty string of lowercase letters and a non-negative integer representing a key , write a function that returns a new string obtained by shifting every letter in the input string by k positions in the alphabet where k is the key.
*/
// {"string": "xyz", "key": 2}
// Approach 1 => Time = O(n) | Space = O(n)
// create a circular array of size 26 and to get the element after the nth place [(current pose + key) % 26]
using namespace std;
string caesarCypherEncryptor(string str, int key)
{
for(int i=0; i<str.size(); i++)
{
str[i] = (char) ((str[i]-97+key)%26)+97;
}
return str;
}
<file_sep>/5_array_medium_move_element_to_end.cpp
/* Question
You're glven an array of Integers and an Integer.
\Write a function that moves all Instances of that Integer In the array to the end of the array and returns the array.
The function should perform ells In place (I.e., a should mutate the Input array) and doesn't need to maintain the order of the other Integers. */
// Test case {"array": [2, 1, 2, 2, 2, 3, 4, 2], "toMove": 2}
// Solution 1 t=>O(n), s=>O(1)
#include <vector>
using namespace std;
vector<int> moveElementToEnd(vector<int> array, int toMove)
{
// Count the occurances of the number
int count = 0;
for(auto i: array)
{
if(i == toMove)
{
count++;
}
}
// move all the element which are not equal to given element forward
int slow = 0, fast = 0;
for(int i=0 ; i<array.size() ; i++)
{
if(array[i] != toMove)
{
array[slow] = array[fast];
slow++;
}
fast++;
}
// replace the remaining element with given
for(int i=array.size() - count ; i<array.size() ; i++)
{
array[i] = toMove;
}
return array;
}
//Solution 2 t=>O(n), s=>O(1) (only one pass)
#include <vector>
using namespace std;
vector<int> moveElementToEnd(vector<int> array, int toMove) {
// Write your code here.
int left = 0, right = array.size()-1,temp;
while(left < right)
{
if(array[left] == toMove and array[right] !=toMove)
{
temp = array[left];
array[left] = array[right];
array[right] = temp;
left++;
right--;
}
if(array[left] != toMove)
{
left++;
}
if(array[right] == toMove)
{
right--;
}
}
return array;
}
<file_sep>/2_arrays_easy_valid_subsequence.cpp
/* Question
Given two non-empty arrays of Integers, wrIte a function that determines whether
the second array Is a subsequence of the first one.
A subsequence of an array Is a set of numbers that aren't necessarily adjacent
In the array but that are In the same order as they appear In the array.
For instance, the numbers [1, 3, 4] form a subsequence of the array [1, 2, 3, 4]
and so do the numbers [2, 4]. Note that a single number In an array and the array Itself are exare both valid subsequences of the array.
*/
// Test case {"array": [5, 1, 22, 25, 6, -1, 8, 10], "sequence": [1, 6, -1, 10]}
// Approach 1 => Time = O(n) | Space = O(1)
// Keep variable index which points to the element in the sequence. iterate through array and if element match with the element in the sequence then update the variable. finally based on the variables value return the result
using namespace std;
bool isValidSubsequence(vector<int> array, vector<int> sequence)
{
int index =0;
for(auto i: array)
{
if(i == sequence[index])
{
index++;
cout<<index<<" ";
}
}
if(index == sequence.size())
{
return true;
}
return false;
}
<file_sep>/4_arrays_medium_smallest_difference.cpp
/* Question
Wrlte a function that takes In two norkempty arrays of Integers,
finds the pair of numbers (one from each array/ whose absolute difference Is closest to zero,
and returns an array containing these two numbers, with the number from Me first array in the 11 rst posItion.
You can assume that there wIll only be one pair of numbers with the smallest Mfference. */
// Test case {"arrayOne": [-1, 5, 10, 20, 3], "arrayTwo": [26, 134, 135, 15, 17]}
// Solution 1 t=>O((n+m)^2), s=>O(1)
#include <vector>
using namespace std;
vector<int> smallestDifference(vector<int> arrayOne, vector<int> arrayTwo)
{
int first_idx, second_idx, diff = INT_MAX;
for(int i=0; i<arrayOne.size(); i++)
{
for(int j=0; j<arrayTwo.size(); j++)
{
if(diff > abs(arrayOne[i] - arrayTwo[j]))
{
diff = abs(arrayOne[i] - arrayTwo[j]);
first_idx = i;
second_idx = j;
}
}
}
// Write your code here.
return {arrayOne[first_idx] ,arrayTwo[second_idx]};
}
//Solution 2 t=>O(nlog(n) + mlog(m)), s=>O(1)
#include <vector>
using namespace std;
vector<int> smallestDifference(vector<int> arrayOne, vector<int> arrayTwo)
{
sort(arrayOne.begin(), arrayOne.end());
sort(arrayTwo.begin(), arrayTwo.end());
vector<int> ret_vector, temp;
int current = INT_MAX, best_diff = INT_MAX, first=0, second=0;
int firstnum =arrayOne[first] , secondnum = arrayTwo[second];
while(first < arrayOne.size() and second < arrayTwo.size())
{
firstnum = arrayOne[first];
secondnum = arrayTwo[second];
if(firstnum < secondnum)
{
current = arrayTwo[second] - arrayOne[first];
first++;
}
else if(firstnum > secondnum)
{
current = arrayOne[first] - arrayTwo[second];
second++;
}
else
{
return {firstnum , secondnum};
}
if(best_diff > current)
{
best_diff = current;
ret_vector = {firstnum , secondnum};
}
}
return ret_vector;
}
<file_sep>/learning_lad_practice.cpp
// Lecture no: 01
// Programmer (Writes the program) -> Program (instructions for computer) -> computer
// instruction is written in the language and c++ is one of them
// -> c++ created by <NAME> (1979)
// -> c++ inspired by the simula67(object oriented programming) and C
// -> c with classes renamed to c++ in 1983
// Lecture no: 02
// -> general purpose programming (can be used to create variety of applications)
// -> middle level language (its human readable and also has features of assembly lang.)
// -> compiled language (the whole code is converted into binary before running)
// in c++ you can do
// 1. procedural programming (like c ... sequencial program)
// 2. object oriented programming (class and objects are used for running the prog)
// 3. generic programming (template and user defined types)
// 4. functional programming (mathematical fucntions)
// -> c++ is efficient, reliable, fast language and its really good language to learn oop
// -> c++ used for game developement, writting other programming language, browsers, compilers, operating systems, engineering applications
// Lecture no: 03
// -> c++ source code - written in c++ source file is save as .cpp file .C, .cxx, .cp, .cc
// -> .hpp file is header file and used for declaration and .cpp for implementation
// -> c++ standard library (built in feature provided to do repetative task std::cin)
// -> you can also create your own library and share it with other programmer so they dont have to write same code again and its called as external library.
// **THE BUILD PROCESS
// 1. Pre Processor
// -> its macro # processing program
// -> it removes the comments, newlines, and clean up the code
// -> based on the macro it add the required part in to the programs
// -> like adding library, definig the variables, and conditional compiling
// -> includes the contents of the header file
// -> if saved the file will have .ii extension and not in machine level language
// 2. Compilation
// -> lots of compilers are available for the c++ and i prefer GCC (GNU compiler collection)
// ---> GNU will convert the pre processed code into assembly code
// ---> while converting it will check whether your program follow all the grammer of c++
// ---> if it is then it will create file with .s extension else give you the compilation error
// ---> Assembly code then converted into Object code with .obj or .o extension
// ---> every sorce file will have its corresponding object code
// 3. Linker
// -> so .o file is not a executable file
// -> linked will take all object files and linke them together it will also add the parts from the header files we added already and will create a executable file
// 4. Loader
// -> This program will load the executable files into th emain memory and keep it ready for cpu to execute
// -> loader will also load other libraries required to run the program
// 5. Execution
// -> then the program is executed in the cpu and you will get the output
// -> The error created by the program during this time is called as runtime error
// Lecture no: 04/05
// IDE installation
// Lecture no: 06
/*
#include <iostream> //#include is pre processor which adds the iostream lib file, we need this to add cin, cout
using namespace std; // all the librsry features available in c++ are placed under standard namespace so here you are saying to your computer that you are using pogram element declared in the standard namesapce
// main fucntion its here your c++ prog start executing
//functions are declared as <return type> <fucntion name> <(arguments)> {return statement}
int main()
{
cout<<"revising time";
return 0;
}
// Lecture no: 07
// constant = entity whoes value doesnt change
// variable = name given to memory address is called as a variable
// datatype = the amount of space we need to allocate to the variable
// int, float, double, bool, void, char, there are also type modifier which used along datatype like short, long, signed, unsigned
// keyword = words who have already defined meaning inside programs language if, for, int. you can not use them as a variable name
// Mycodeschool: Momories involved in the code execution
// code text memory
// global variable space
// stack frame
// heap
// Lecture no: 08
// once we define some variable the compiler will assign some memory to that particular variable,
and if you dont declare them then they will take the garbage value stored at that location
// before using variable you should define the variable
//initialization is the process of assigning the value to the variable
//declaration is when you declare the properties of variable you want to store
//defining is when you assigne the memory to the variable
// in c++ declaration and defination happen for variable at same time]
// for function its happens differently
#include <iostream>
int main()
{
int no_of_player;
int a,b,c,d=90,f,g,h=20,hj; //defining multiple variable at once
short int s; // 2 bytes allocated
long int asdas; // 8 bytes allocated
float average_age;
char sex;
bool is_he_injured;
no_of_player = 9; average_age = 21.24; sex = 'M'; is_he_injured = false;
std::cout<<"no of player playing are: "<<no_of_player
<<" there average age is: "<<average_age<<" all are: "<<sex<<" and none of them are injured: "<<is_he_injured;
return 0;
}
// Lecture no: 09, 10, 11
// cout is object of ostream class and stands for console output
// << this is stream insertion operation
// cin is the object of the istream class
// >> this is stream extraction operator
// comment are the description of what particular block of code, statement in code is doing in human readable format to get good understanding of the code
// [// -> single line comment, /* <> * / multiple line comment ]
// comments doesnot affect the performance of the program
#include <iostream>
int main()
{
std::cout<<"cout is object of o stream class"<<std::endl<<"endl and cout is defiend in standard namespace \n";
int data_from_exttration_operator, multi_vaar;
std::cin>>data_from_exttration_operator>>multi_vaar;
return 0;
}
// Lecture no: 12,13,14
// arithmatic operators available in c++
// short hand operator
#include <iostream>
using namespace std;
int main()
{
int num1=12, num2=6;
cout<<num1<<" + "<<num2<<" = "<<num1+num2<<std::endl;
cout<<num1<<" - "<<num2<<" = "<<num1-num2<<"\n";
cout<<num1<<" * "<<num2<<" = "<<num1*num2<<std::endl;
cout<<num1<<" % "<<num2<<" = "<<num1%num2<<endl;
int short_hand_opr = 10;
std::cout<<short_hand_opr++<<endl; // postfix operator operation first increment later
std::cout<<++short_hand_opr<<endl; // prefix increment first operation later
short_hand_opr+=3; // same as short_hand_opr = short_hand_opr +3;
std::cout<<short_hand_opr<<endl;
return 0;
}
// Lecture no: 15,16
// conditional statement if - elseif - else, nested if else
// if conditions fail it will gofor else if till the time its not fail if noting matched then it will execute the else block
#include <iostream>
using namespace std;
int main()
{
int age = 5;
if(age==5)
{
if(age==7)
{
std::cout<<"its 7";
}
else if(age==9)
{
std::cout<<"its 7";
}
else
{
cout<<"from nested else \n";
}
cout<<"age is 5 \n";
}
else if(age== 10)
{
cout<<"age is 10 \n";
}
else
{
cout<<"age not 10,5";
}
return 0;
}
//Lecture 17, 18
// comparision operator, logical operator, ternary operator
#include <iostream>
using namespace std;
int main()
{
int date = 15;
if (date> 15){cout<<"later part in month \n";}
if (date>= 15){cout<<"later part in month inclusive\n";}
if (date< 15){cout<<"earlier part in month\n";}
if (date<= 15){cout<<"earlier part in month inclusive\n";}
if (date!= 15){cout<<"not equals 15\n";}
if (date== 15){cout<<"equal 15\n";}
if (date<20 && date>10){cout<<"between 10 nad 2\n";}
if (date>20 || date<10){cout<<"between 10 nad 20\n";}
if (!date){cout<<"not zero \n";}
// replacement of if and else ocndition ? <if true> : <else>
date>10 ?cout<<"greater than 10" : cout<<"less than 10";
}
// Lecture 19, 20, 21
// loops for, while <- entry control do while<- exit control
// for while there should be valid exit condition
#include <iostream>
int main()
{
int counter = 0;
while (counter <10)
{
std::cout<<"Value of counter: "<<counter<<std::endl;
counter++;
for (int i =0; i<counter; i++)
{
for(int j=0; j<i; j++)
{
std::cout<<"*";
}
std::cout<<"\n";
}
std::cout<<"\n";
}
do
{
std::cout<<"from do while loop: "<<counter<<" \n";
counter++;
}
while(counter<19);
return 0;
}
// Lecture 22, 23
// Array is nothing but collection of the simillar elements
// Arry indx start from 0 and the name off the variable where we store the array is the address of the first element of array
// Multiple dimention array is array inside another array however in the memory its stored in consecutive way
#include <iostream>
using namespace std;
int main()
{
int array_of_marks[] = {2,3,4,65};
std::cout<<"first element of the array: "<<array_of_marks[1]<<endl;
float arry_filled_by_for[10];
for(int i=0; i<10;i++)
{
arry_filled_by_for[i] = 100.0/i+1;
}
std::cout<<"Printing the elements of the array: ";
for(int i=0; i<10;i++)
{
cout<<arry_filled_by_for[i]<<" ";
}
int multi_dia_array[2][3][3][4];
int two_d_array[3][2] = {{2,3},{4,5},{6,7}};
cout<<two_d_array<<endl;
cout<<two_d_array[0][0];
}
// Lecture 24, 25
// fucntion is nothing but collection of code with specific tasks
// its gives the good readibility, organisation and reusability
// fucn is defined as <return type> <fucntion name> (<parameter taken by fucntion>)
// function prototyping is nothing but declaring the fucntion body, defination is when you write the fucntionality of the fucntion
// while declaring the fuction you can only give the datatype
// if your function is returning the value then you have to mentioed that in the return type
#include <iostream>
using namespace std;
void welcomeToFunctions();
void functionThatsTakesTheparameter(int, int);
int fucntionThatReturnsTheValues(int);
int main()
{
welcomeToFunctions();
functionThatsTakesTheparameter(3,4);
int c =fucntionThatReturnsTheValues(11);
cout<<"values from the func: "<<c;
return 0;
}
void welcomeToFunctions()
{
cout<<"calling the fucntion \n";
}
void functionThatsTakesTheparameter(int a, int b)
{
cout<<"Result is: "<<a+b<<endl;
}
int fucntionThatReturnsTheValues(int a)
{
int z = a*a;
return z;
}
// Lecture 26
// default values in function parameters
// generally when you call c++ fucntion compilers try to find the fucntion with exact same signature
// default values while DECLARATION allows and its on RIGHTMOST SIDE int declaration us to use the same fucntion and in case if the parameter is not available it will use the default declared value.
// while assigning default values start from right side as while call fucntion will only use the values 4 the left to right myfunction(2, ,3) is not allowed
#include <iostream>
using namespace std;
int callingDefValFucn(int a = 4, int b = 5, int c=89 );
int main()
{
int c =callingDefValFucn(2,3);
cout<<"Value of the default parameter is: "<<c<<"\n";
c =callingDefValFucn();
cout<<"Value of the default parameter is: "<<c<<"\n";
}
int callingDefValFucn(int a, int b, int c )
{
int return_int = a+b+c;
return return_int;
}
// Lecture 27
// inline function: while program execution the control is shifted back and forth between main and fucntion and sometimes
if yo have very small function its advised to use to declare that function as a inline function as it will not switch the control between main and other function and will reduce the overheads
// frequently using this keyword is not recommended as it will increase the size of the executable
#include <iostream>
using namespace std;
inline void inlineFunctionCall(int c);
int main()
{
inlineFunctionCall(2);
}
void inlineFunctionCall(int c)
{
cout<<"value is: "<<c;
}
// Lecture 28
// Varible scope: the region where the varible is available
// variables are defined in 3 locations4
// ->inside the function (LOcal scope)
// ->while defining the function (LOcal scope) (formal parameters)
// ->outside the function (Global scope)
// dafault value of the global var is set to zero as its declarded in the global memory on other hand local variables will take the garbage value as they are declared in the stack
#include <iostream>
using namespace std;
void display();
void noabFunc();
int a = 9;
int b;
int main()
{
int global_var = 17;
int a=2, b =34;
cout<<"from main function --> a ="<<a<<"| b ="<<b<<"\n";
display();
noabFunc();
return 0;
}
void display()
{
int a = 90, b=89;
cout<<"from display function --> a ="<<a<<"| b ="<<b<<"\n";
}
void noabFunc()
{
cout<<"from noabFunc function --> a ="<<a<<"| b ="<<b<<"\n";
}
// Lecture 29
// break statement: to terminate the execution of loop and terminate the case in the switch statement
// break only terminates the current loop and outer loop is not affected
// continue statement: its just skip the execution of current loop an forces the loop to go to next iteration
#include <iostream>
using namespace std;
int main()
{
for(int i=0; i<10; i++)
{
if (i==3)
{
break; // when the i=3 the loop will terminate itself
}
for (int j=0; j<10; j++)
{
if (j==5)
{
continue; // all the instances will be where j =5
}
else
{
cout<<"val if i: "<<i<<"val if j: "<<j<<endl;
}
}
}
}
// Lecture 30, 31
// switch statement
// the case can have the range value and its developed in c++ 11
#include <iostream>
using namespace std;
int main()
{
int grade = 10;
switch(grade)
{
case(1):
{
cout<<"fail";
break;
}
case(10):
{
cout<<"fail";
break;
}
default:
{
cout<<"pass";
break;
}
}
return 0;
}
// Lecture 32
// Multiple return statements
// Make sure that only 1 return statement is triggered during the prog flow
// returning the multiple values are possible using pointers
#include <iostream>
using namespace std;
bool checingForNum(int);
int main()
{
bool result = checingForNum(2);
std::cout<<result;
}
bool checingForNum(int input_var)
{
if(input_var%2 ==0)
{
return true;
}
else
{
return false;
}
}
// Lecture 34, 35
// Address of operator & return the starting byte of memory allocated to the variable
// there is special type of variables which we called as a pointer which is used to store the the adress vales
// to declare the pointer we needspecify the datatype which is nithing but data type of data stored at that particular location
// the naming will be same as normal variable except it will have * operator which specifies that its pointer variable
#include <iostream>
using namespace std;
int main()
{
int var1=9, var2, var3=90;
cout<<"Var1 is stored at: "<<&var1<<" Var2 is stored at: "<<&var2<<" Var3 is stored at: "<<&var3<<"\n";
int *var1_address = &var1;
// var1_address++;
cout<<&*var1_address;
}
// Lecture 36, 37, 38
// passing and returning the array
// pass by value: the whole value is passed to the function
// pass by referenc: address of the element is passed, any change made by this will alos reflect in the variable of main function
// array name stores the address of the first element and its just a pointer to the first element to access element at some position just use +
#include <iostream>
using namespace std;
int * acceptAndReturnTheArray(int *adr_of_first)
{
return &adr_of_first[2];
}
int main()
{
int arr[5] = {1,2,30,4,5};
cout<<"printing array using pointer: "<<*(arr+2)<<" * \n";
int *ret_arr_adr = acceptAndReturnTheArray(arr);
cout<<arr<<" -- "<<ret_arr_adr;
return 0;
}
// Lecture 39, 40
// const keyword
// if you dont want to change the value of your variable you have to use const keyword and while defining the the variable you have to initialise it
// you can declare array or any variable as a constantiterate through array using pointer
#include <iostream>
using namespace std;
void dispConstArr(int * start, int * end);
int main()
{
int var_arr[10] = {7,3,4,5,6,7,5,4,3,5};
cout<<var_arr<<" - "<<var_arr+10;
dispConstArr(var_arr, var_arr+10);
return 0;
}
void dispConstArr(int * start, int * end)
{
cout<<"\n";
while(start!=end-2)
{
cout<<*start<<"-";
start++;
}
}
// Lecture 41, 42, 43
// structures: it allows us to store different types of variables
// Structure becomes user defined data type
// the assignment can be done using array like way {}
// and the inside element is accessed using dot operator
// you can also access the structure using pointers using -> operator
// pass structure and address of structure
// classical example of failure when you pass by value. as the scope of the variable is local when you return its address you get garbage value
#include <iostream>
using namespace std;
struct Student
{
int sid;
int arr[5];
char sex;
float average;
};
Student * takingStructureAndReturningIt(Student s1);
Student oppositeOfAbove(Student * s1_adr);
int main()
{
Student suraj = {5,{2,3,4,5,6},'M',34.5} ;
suraj.arr[2] = 56;
cout<<suraj.arr[2]<<" - "<<suraj.sid<<"\n";
Student * addr_of_suraj = &suraj;
cout<<addr_of_suraj<<" --> "<<addr_of_suraj->average<<"\n";
Student * addr = takingStructureAndReturningIt(suraj);
cout<<addr<<"\n";
cout<<"\nbefore passing to other func= "<<addr->sid<<" - "<<addr->sex<<"\n";
Student temp = oppositeOfAbove(addr);
cout<<temp.sid<<" - "<<temp.average<<"\n";
}
Student * takingStructureAndReturningIt(Student s1)
{
Student * addr_of_suraj = &s1;
cout<<"\nFrom the function = "<<addr_of_suraj<<" - "<<addr_of_suraj->sid<<" - "<<addr_of_suraj->sex<<"\n";
return addr_of_suraj;
}
Student oppositeOfAbove(Student * s1_adr)
{
Student s1 = *s1_adr;
cout<<"\nFrom the function = "<<s1_adr->sid;
return s1;
}
// Lecture 44, 45, 46
// nested structutre
// nesting can be done using address or actual variable
// size of operator determined the size of data during the compile time
#include <iostream>
#include <string>
using namespace std;
struct Home
{
int home_no;
string street_adr;
};
struct Student
{
int roll_no;
char sex;
Home address;
};
struct Student_ptr
{
int roll_no;
char sex;
Home *address;
};
int main()
{
Home h1 = {61, "wachuseets"};
Student s1 = {123, 'M', h1};
Student_ptr s1_ptr = {345, 'm', &h1};
cout<<s1.address.home_no<<"\n";
cout<<s1_ptr.address->home_no<<"\n";
Student_ptr * s1_ptr_ptr = &s1_ptr;
cout<<s1_ptr_ptr->address->street_adr;
cout<<endl<<sizeof(long int);
return 0;
}
// Lecture 47
// union
// in the union the memory is stored amongest the all the datatype
// in unions we can only store the value of one variable at a time
#include <iostream>
#include <string>
union Employee
{
int eid;
char name;
};
int main()
{
std::cout<<sizeof(Employee);
Employee e1;
e1.name = 's';
std::cout<<sizeof(e1)<<e1.name<<std::endl;
int arr[5] = {1,2,3,4,5};
int* arr_ = arr;
std::cout<<arr_++;
return 0;
}
// Lecture 48, 49
// Dynamic memory allocation new and delete operator
// allocating the memory during run time and not at compile time
// generally when you build your program the OS will allocatre some memory for the program called as a stack
// stack is shared by all the programs running in the system. so lets assume you have a programs running in your system and for every program os allocate some stack space where it stored the program specific data nad local variables
// as the stack is shared space its predefined and only fixed amount of space is allocated to every program, so its not possible to assin space to your program during runtime as it will simply then try to use stack space allocated to other program
// so to solve this problem we can allocate the memory to the program in the heap.
// but you to allocate and deallocate this memory explicitely as if you dont then os wont be able to allocate the same to other program.
// Bad recursion cna lead to program crash or stack over flow
// so new and delete operators are used for assigning the memory to the fucntion from the headp
// stack, heap, global var, code memory are type of memories in ram while prog exec
#include <iostream>
using namespace std;
int main()
{
int *adr_from_heap_i = new int; // allocating to the int variable
float *adr_from_heap_f = new float [4]; // allocating to array var
int *adr_from_heap = new int [4]; // alloation from the dynamic memoyr
*adr_from_heap = 76;
cout<<&adr_from_heap<<" - "<<*adr_from_heap<<" - "<<adr_from_heap;
delete [] adr_from_heap; // deallocation
adr_from_heap_i++;
}
// Lecture 50, 51, 52
// Avoding the dangling pointer
// So the dangling of pointer happen when you allocate the memory to the pointer from the heap... you do your prog part and now deallocated the memory. but in your pointer you still store ths address and if you accidently try to access thta location you will get garbage valueso check before and after for this by setting pointer to null
// You can use auto for the automatic type deduction
#include <iostream>
using namespace std;
int main()
{
int *adr_from_heap = NULL;
adr_from_heap = new int;
if (adr_from_heap)
{
cout<<"Memory allocated successfully"<<"\n";
}
else
{
cout<<"no memory allocated"<<"\n";
}
delete adr_from_heap;
cout<<"Still got the address "<<adr_from_heap<<"\n";
adr_from_heap = NULL;
cout<<"now no dangling "<<adr_from_heap;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int arr[] = {2,233,4,45,56,6778,9,90,5};
for (int var : arr)
{
cout<<var;
}
}
#include <iostream>
#include <string>
using namespace std;
struct Address
{
int house_no;
string street;
};
struct Person
{
string name;
int age;
double salary;
Address adr;
};
int main()
{
int * adr_for_var = new int;
int * adr_for_array_size_5 = new int[5];
Person * adr_of_ulkesh = new Person();
if(adr_for_var != nullptr)
*adr_for_var = 10;
cout<<*adr_for_var<<"\n";
int array[3];
array[1] = 1;
array[2] = 2;
array[3] = 3;
cout<<array<<"\n";
*adr_for_array_size_5 = 4;
// int * next_adr = adr_for_array_size_5 + 1;
*(adr_for_array_size_5 + 3) =5;
// *next_adr = 5;
// next_adr++;
// *next_adr = 6;
// adr_for_array_size_5[1] = 5;
// adr_for_array_size_5[2] = 6;
// adr_for_array_size_5[3] = 7;
// adr_for_array_size_5[4] = 8;
for(int i=0; i<5; i++)
{
cout<<adr_for_array_size_5[i]<<" ";
}
adr_of_ulkesh -> name = "<NAME>";
cout<<"\n"<<(*adr_of_ulkesh).name<<"\n";
delete adr_for_var;
delete [] adr_for_array_size_5;
delete adr_of_ulkesh;
adr_for_var = nullptr;
adr_for_array_size_5 = nullptr;
// cout<<adr_for_array_size_5[1];
adr_of_ulkesh = nullptr;
}
// Lecture 53: string operations, recursion
#include <iostream>
#include <string>
using namespace std;
int facto(int s1)
{
if(s1==0)
{
return 1;
}
else
{
return s1*facto(s1-1);
}
}
int main()
{
int a=4;
cout<<facto(a);
}
#include <iostream>
using namespace std;
int factor(int i);
int main()
{
int* a_adr =new int;
*a_adr = 5;
cout<<factor(*a_adr);
}
int factor(int i)
{
if(i ==0 )
{
return 1;
}
else
{
return i*factor(i -1);
}
}
// recursion should have some termination case
// it have the return type
#include <iostream>
#include <string>
using namespace std;
int rec_func(int i)
{
if(i==0)
{
return 0;
}
else
{
return i + rec_func(i-1);
}
}
int main()
{
int c =9;
c = rec_func(9);
cout<<c;
}
// Lecture 55
// Function overloading
// so the fucntion will have the same name same return type but different paramaters
// generally useful during the constructor overloading
#include <iostream>
using namespace std;
void display();
void display(int i);
void display(char c);
int main()
{
display();
display(2);
display('c');
return 0;
}
void display()
{
std::cout<<"no f.."<<"\n";
}
void display(int i)
{
std::cout<<"no f.. for "<<i<<"\n";
}
void display(char c)
{
std::cout<<"no f.."<<c<<"\n";
}
// Lecture 56, 57, 58
// Object oriented programming
// class contains member function and member variable
// Access specifier: this for the making sur ethat the classes data available only in the exact region
// to access the class variables and methonds you have to create the object of the class
// object can be created in stack or heap memory
// you can access the class using . or -> operator
// Scope resolution operator :: is used to defined the method of the clss outside the class
// you can also initiliase the variable inside the class you can only use th escope resolution operator in cas eof static variables
// constructor and distructor are special methods without any return type of the class and have the same name /~same name as a classname, they are invoked automatically at the time of object creation and object distruction, we can use this method to initialise the object and memory management.
// you cant call constructor separately, and they dont have return type, you can overload the construtor. but in case of overloading the default one should need to be present all the time. constructor cant be private ++
#include <iostream>
using namespace std;
struct Return_struct
{
int s_age;
float s_height;
};
class HumanBeing
{
public:
HumanBeing(int age, float height);
HumanBeing()
{
cout<<"constructor invoked"<<"\n";
}
~HumanBeing()
{
cout<<"distructor invoked"<<"\n";
}
void display()
{
cout<<"from display function"<<"\n";
}
int public_var;
Return_struct* accessPrivateVars();
void privateVarsetterMethod(int age, float height)
{
m_age = age; m_height=height;
}
Return_struct return_struct;
int default_val = 20;
private:
int m_age;
float m_height;
};
HumanBeing::HumanBeing(int age, float height)
{
m_age = age; m_height = height;
cout<<"from overloaded constructor"<<m_age<<m_height<<"\n";
}
Return_struct* HumanBeing::accessPrivateVars()
{
return_struct.s_age = m_age;
return_struct.s_height = m_height;
return &return_struct;
}
int main()
{
HumanBeing h1, h2(2,3.4),h3;
h1.display();
h1.public_var = 10;
h1.privateVarsetterMethod(4,5.6);
// cout<<h1.accessPrivateVars()<<"\n";
cout<<h1.public_var<<"\n";
Return_struct *receive_struct = h2.accessPrivateVars();
cout<<receive_struct->s_age<<"***********\n";
HumanBeing *adr_ofh3obj = new HumanBeing(12,14.5);
receive_struct = adr_ofh3obj->accessPrivateVars();
cout<<receive_struct->s_age<<"***********\n";
cout<<h3.default_val<<"wuryw08tyhgrhgo";
// cout<<"\n"<<a<<"\n";
return 0;
}
// Lecture no 58,59,60,61,62
// constructor, constructor overloading and default constructor
// constructor is invoked at the time of object crration , like a fucntion overloading you can do construction overloading and how ever you should have a default value or default constructor else you will get the error
// distructor: distructor is a special function which dont have the return type and parament and will be invoked at the time of distruction of the object, mainley used to free the resources and house keeping activity. will invoked automatically at the time of object distruction or deleting the pointer
#include <iostream>
using namespace std;
class Human
{
public:
// Human();
Human(int age=0, float height=1.0)
{
age_=age; height_=height;
}
bool intialiseVar(int age)
{
setAge(age);
if(age_ != -1){return false;}
else{return true;}
}
int retuAge()
{
return age_;
}
~Human(){cout<<"\nur killed and you can free the heap memory apply to class variables";}
private:
int age_; float height_;
void setAge(int age){age_ = age;};
};
// Human::Human()
// {
// cout<<"default constructor invoked"<<"\n";
// }
int main()
{
Human H1;
Human *h2_adr = new Human(2, 3.4);
if(h2_adr!=NULL)
{
cout<<"\n"<<h2_adr->retuAge();
}
delete h2_adr;
h2_adr = NULL;
return 0;
}
#include <iostream>
using namespace std;
class Human
{
private:
int* age;
float* height;
public:
Human(int iage=0, float iheight=1.0)
{
age = new int; height = new float;
*age = iage;
*height = iheight;
}
void display()
{
cout<<"Age = "<<*age<<"Height = "<<*height<<"\n";
}
~Human();
};
Human::~Human()
{
delete age; delete height;age = NULL;height = NULL;
cout<<"deleted the pointers";
}
int main()
{
Human h1;
h1.display();
Human* h2_adr = new Human(2,3.4);
h2_adr->display();
delete h2_adr; h2_adr = NULL;
return 0;
}
// Lec 63, 64
// static keyword
// the storage of this variable is like global var, only one copy per program and has a class scope
// you can declare variable as a static or method as a static method
// static variable will need to be declare before its use in class i.e. before object creation
// static methos will only work on the static variables
// the static variable is stored in th eheap and can be access without creating the object
#include <iostream>
using namespace std;
class Human
{
public:
static int human_count;
Human(){human_count++;}
static void funcOnlyWorkOnStaticVar();
};
int Human::human_count = 0;
void Human::funcOnlyWorkOnStaticVar()
{
cout<<"No. of human created = "<<human_count<<"\n";
}
int main()
{
Human *adr_of_h1= new Human();
adr_of_h1->funcOnlyWorkOnStaticVar();
Human h2;
h2.funcOnlyWorkOnStaticVar();
for(int i=0; i<10; i+=2)
{
static int loop_count = 0; // was initialise only at the first time of loop
cout<<"loop count = "<<loop_count<<"\n";
loop_count++;
}
}
// Lec 65
// friend fnction
// the private and protected members of th eclass is only accesseble to the to the member functions of the class
// but there is a special function called as a friend fucntion and if you declare the function as a friend function to the class you can acccess the private and protected variables of the class
#include <iostream>
using namespace std;
class Human
{
private:
int age;
float height;
public:
Human(int iage= 0, float iheight = 0.0)
{
age=iage;
height=iheight;
}
friend void canAcessPrivateVarOfClass(Human man);
};
void canAcessPrivateVarOfClass(Human man)
{
cout<<"height is= "<<man.height<<" age is= "<<man.age<<"\n";
}
int main()
{
Human h1(2);
canAcessPrivateVarOfClass(h1);
Human *h2 = new Human();
canAcessPrivateVarOfClass(*h2);
}
*/
// // Lecture 66
// // Inheritance
// // It allows us to define the clas using other class
// inheritance
// Allows us to use feature defined in one class in another class
// to inherites the class you have to while defining the class you have to use :
// private members are not inherritated
// base class, sub class
// #include <iostream>
// #include <string>
// using namespace std;
// class Person
// {
// public:
// string name;
// int age;
// void setName(string iname){name = iname;}
// void setage(int iage){age = iage;}
// };
// class Student : public Person
// {
// public:
// int id;
// void setID(int iid){iid = id;}
// void introduce()
// {
// cout<<"Hi i am:"<<name<<" my age is:"<<age<<" my sid is:"<<id<<"\n";
// }3
// };
// int main()
// {
// Student suraj;
// suraj.setName("Suraj");
// suraj.setage(26);
// suraj.setID(242183642);
// suraj.introduce();
// return 0;
// }
// Lecture No 66
// #include <iostream>
// #include <string>
// // using namespace std;
// class Mother
// {
// public:
// std::string skin_color;
// Mother(){"Mother created \n";}
// ~Mother(){"Mother gone \n";}
// protected:
// void AskMother(){"Ask your mom anything";}
// };
// class Father
// {
// public:
// std::string height;
// Father(){"Father created \n";}
// ~Father(){"Father gone \n";}
// protected:
// void AskFather(){"Ask your dad anything";}
// float family_age;
// private:
// int cash;
// };
// class Son : protected Mother, private Father
// {
// public:
// Son(){"Son created \n";}
// ~Son(){"Son gone \n";}
// std::string name;
// using Father::family_age;
// void introcude(){std::cout<<"i am"<<name<<" - height"<<height<<" - skin_color"<<skin_color;}
// };
// int main()
// {
// Son *suraj = new Son;
// suraj->name = "suraj";
// suraj->introcude();
// delete suraj;
// return 0;
// }
// #include <iostream>
// #include <string>
// using namespace std;
// template <typename t1, typename t2>
// class Marks
// {
// public:
// t1 mark, extmark;
// t2 string_var;
// Marks(t1 imark = 0, t1 emark= 0)
// {
// mark = imark; extmark = emark;
// }
// void disp()
// {
// cout<<"internal marks: "<<mark<<" ext mark: "<<extmark;
// }
// Marks operator+ (Marks m2)
// {
// Marks temp;
// temp.mark = this->mark + m2.mark;
// temp.extmark = this->extmark + m2.extmark;
// return temp;
// }
// };
// int main()
// {
// Marks <int , int > m1 (20,30); Marks <int , int > m2 (40,50);
// Marks<int , int > m3 = m1+m2;
// m3.disp();
// }
// #include <iostream>
// using namespace std;
// void passByValue(int *a)
// {
// cout<<"val :"<<a[2];
// }
// // void passByRef(int &a[])
// // {
// // cout<<"ref :"<<a[2];
// // }
// // void passBypointer(int *a)
// // {
// // cout<<"ptr :"<<a[2];
// // }
// int main()
// {
// int arr[5] = {1,2,3,4,5};
// // passBypointer(arr);
// // passByRef(*arr[]);
// passByValue(arr[]);
// return 0;
// }
// void display();
// void display(int i);
// void display(char c);
// int display(int b){retun b;}
// int main()
// {
// display();
// display(2);
// display('c');
// int d = display('c');
// cout<<d;
// return 0;
// }
// void display()
// {
// std::cout<<"no f.."<<"\n";
// }
// void display(int i)
// {
// std::cout<<"no f.. for "<<i<<"\n";
// }
// void display(char c)
// {
// std::cout<<"no f.."<<c<<"\n";
// }
// #include <iostream>
// using namespace std;
// class Human
// {
// public:
// Human(){human_count++;}
// static int human_count;
// static void funcOnlyWorkOnStaticVar();
// };
// int Human::human_count = 0;
// void Human::funcOnlyWorkOnStaticVar()
// {
// cout<<"No. of human created = "<<human_count<<"\n";
// }
// int main()
// {
// Human *adr_of_h1= new Human();
// adr_of_h1->funcOnlyWorkOnStaticVar();
// Human h2;
// h2.funcOnlyWorkOnStaticVar();
// for(int i=0; i<10; i+=2)
// {
// static int loop_count = 0; // was initialise only at the first time of loop
// cout<<"loop count = "<<loop_count<<"\n";
// loop_count++;
// }
// // }
// #include <iostream>
// using namespace std;
// class Operator_m
// {
// public:
// int temp_var;
// void operator++()
// {
// this->temp_var++;
// }
// Operator_m operator++(int)
// {
// Operator_m temp = *this;
// this->temp_var++;
// return temp;
// }
// };
// int main()
// {
// Operator_m o1;
// o1.temp_var = 4;
// ++o1;
// cout<<o1.temp_var;
// o1++;
// cout<<o1.temp_var;
// }
#include <iostream>
using namespace std;
void func(int a)
{
cout<<"1 \n";
}
void funco(int & a)
{
cout<<"2 \n";
}
void func(int *a_adr)
{
cout<<"3 \n";
}
int main()
{
int a = 0;
func(a);
funco(a);
func(&a);
}<file_sep>/9_dynamic_programming_easy_max_subset_sum.cpp
/*Question
Write the function that takes in an array and returns the maximum sum of non-adjacent elements in the array. if a sun cnat be generated the function should return 0.
*/
// Test case {"array": [10, 5, 20, 25, 15, 5, 5, 15, 3, 15, 5, 5, 15]}
// Approach 1 => Time = O(n) | Space = O(n) / O(1) Also possible
// Iterate throught the array and store the maximum sum till that index
// for eg. max_sum for index 1 = array[0], index 2 = max(array[0],array[1]), index 3 = max(array[3]+array[0], max_sum[2])
O(n) / O(n)
#include <vector>
using namespace std;
int maxSubsetSumNoAdjacent(vector<int> array)
{
if(array.size() == 0)
{
return 0;
}
if(array.size()<3)
{
return *max_element(array.begin(),array.end());
}
vector<int> max_sum;
max_sum.resize(array.size());
max_sum[0] = array[0];
max_sum[1] = max(array[0],array[1]);
for(int i=2; i<array.size(); i++)
{
max_sum[i] = max(max_sum[i-2] + array[i] , max_sum[i-1]);
}
return *max_element(max_sum.begin(),max_sum.end());
}
O(n) / O(1)
#include <vector>
using namespace std;
int maxSubsetSumNoAdjacent(vector<int> array)
{
if(array.size() == 0)
{
return 0;
}
if(array.size()<3)
{
return *max_element(array.begin(),array.end());
}
int prevprev, prev, curr, temp;
prevprev = array[0];
prev = max(array[0],array[1]);
curr = array[2];
for(int i=2; i<array.size(); i++)
{
curr = array[i];
temp = max(prevprev + curr , prev);
prevprev = prev;
prev = temp;
}
return max(prevprev, prev);
}
<file_sep>/6_array_medium_monotonic_array.cpp
/*Question
Write a function that takes In an array of Integers and returns a boolean representing whether the array Is monotonle.
An array is said to he monotonic If Its elements, from lett to right are entlrely non-Increasing or entlrely non-decreasing.
*/
// Test case {[-1, -5, -10, -1100, -1100, -1101, -1102, -9001]}
// Approach 1 => Time = O(n) | Space = O(1)
// Determine whether array is decreasing or increasing based on first and last element
// Iterate over the array and check whether consecutive element forloowing the same trend
using namespace std;
bool isMonotonic(vector<int> array)
{
if(array.size() <= 2)
{
return true;
}
bool inc = true;
if(array[0] < array[array.size()-1])
{
inc = true;
}
else
{
inc = false;
}
for(int i=0; i<array.size()-1; i++)
{
if(inc)
{
if(array[i] > array[i+1])
{
return false;
}
}
else
{
if(array[i] < array[i+1])
{
return false;
}
}
}
return true;
}
<file_sep>/3_arrays_medium_three_number_sum.cpp
/* Question
Write a function that takes In a nan empty array of distinct Integers and an Integer representing a target sum.
The function should find all triplets In the array that sum up to the target sum
and return a two-dimensional array of all these triplets.
The numbers In each triplet should be ordered In ascending order,
and the triplets themselves should be ordered In ascending order with respect to the numbers they hold.
If no three numbers sum up to the target sum, the function should return an empty array. */
// Test case {"array": [12, 3, 1, 2, -6, 5, -8, 6], "target": 0} / {"array": [8, 10, -2, 49, 14], "targetSum": 57}
// Brute force: Iterate through the 3 numbers O(n^3)
// Approach 2 : O(n^2), O(n)fix one element and call two sum function (extra space required to store has map) and sorting also required
// Approach 3 => Iterate throught the array and use two pointer (from current array index to end) technic to find the triplets
// Time = O(n^2) | Space = O(n)-> for triplet and nothing for program
#include <vector>
using namespace std;
vector<vector<int>> threeNumberSum(vector<int> array, int targetSum)
{
vector<vector<int>> ret_vector;
sort(array.begin(), array.end());
int left = 1, right = array.size() - 1, remainder;
for(int i = 0; i<array.size(); i++)
{
left = i + 1, right = array.size() - 1;
while(left < right)
{
if(array[left] + array[right] + array[i] < targetSum)
{
left++;
}
else if(array[left] + array[right] + array[i] > targetSum)
{
right--;
}
else
{
ret_vector.push_back({array[i], array[left], array[right]});
left++; right--;
}
}
}
return ret_vector;
}
<file_sep>/README.md
# AlgoExpert
Master Repo for algoexpert
| e212966825c534727f9d11eb5cc3e56966d7448d | [
"Markdown",
"C++"
] | 14 | C++ | Suraj0712/AlgoExpert | 2064f017f08e175279e136b808aa7b990559047b | 30b680a43f38bc63a2828eb199f90efd52260a63 |
refs/heads/master | <file_sep>let isObject = function (value) {
let type = typeof value
return value !== null && (type === 'object' || type === 'function')
}
/**
*
* @param {Function} func 需要被延迟执行的函数
* @param {Number} wait 等待的时间
* @param {Object} options 自定义配置
*/
let debounce = function (func, wait, options) {
let lastArgs, // 最后一次传入的参数
lastThis, // 最后一次调用的this
maxWait, //
result,
timerId,
lastCallTime
let lastInvokeTime = 0
let leading = false
let maxing = false
let trailing = true
if (typeof func !== 'function') {
return new Error('Expected a function')
}
wait = +wait || 0
if (isObject(options)) {
leading = !!options.leading // 是否在延迟开始前调用
maxing = 'maxWait' in options
maxWait = maxing ? Math.max(+options.maxWait || 0, wait): maxWait
trailing = 'trailing' in options ? options.trailing : trailing
}
let invokeFunc = function (time) {
// 调用函数
const args = lastArgs
const ctx = lastThis
// 清空
lastThis = lastArgs = undefined
lastInvokeTime = time
return func.apply(ctx, args)
}
let startTimer = function (pendingFunc, wait) {
return window.setTimeout(pendingFunc, wait)
}
let cancelTimer = function (id) {
window.clearTimeout(id)
}
let leadingEdge = function (time) {
lastInvokeTime = time
// 设置的是否到达等待时间的定时器
timerId = startTimer(timerExpired, wait)
// 如果提前执行的话那么提前执行
return leading ? invokeFunc(time) : result
}
// 计算还需要等待的时间
let remainingWait = function (time) {
const timeSinceLastCall = time - lastCallTime
const timeSinceLastInvoke = time - lastInvokeTime
const timeWaiting = wait - timeSinceLastCall
return maxing ? Math.min(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting
}
// 判断是否可以执行函数
let shouldInvoke = function (time) {
const timeSinceLastCall = time - lastCallTime
const timeSinceLastInvoke = time - lastInvokeTime
return (lastCallTime === undefined || (timeSinceLastCall >= wait) || timeSinceLastCall < 0 || (maxing && timeSinceLastInvoke >= maxWait))
}
// 时间是否超过时间
let timerExpired = function () {
const time = Date.now()
if (shouldInvoke(time)) {
return trailingEdge(time)
}
timerId = startTimer(timerExpired, remainingWait(time))
}
let trailingEdge = function (time) {
timerId = undefined
if (trailing && lastArgs) {
return invokeFunc(time)
}
lastArgs = lastThis = undefined
return result
}
let cancel = function () {
if (timerId !== undefined ) {
cancelTimer(timerId)
}
lastInvokeTime = 0
lastArgs = lastCallTime = lastThis = timerId = undefined
}
let flush = function () {
return timerId === undefined ? result : trailingEdge(Date.now())
}
let pending = function () {
return timerId !== undefined
}
// 主要过程
let debounced = function (...args) {
const time = Date.now()
const isInvoking = shouldInvoke(time)
lastArgs = args
lastThis = this
lastCallTime = time
if (isInvoking) {
// 表示第一次
if (timerId === undefined) {
return leadingEdge(lastCallTime)
}
if (maxing) {
timerId = startTimer(timerExpired, wait)
return invokeFunc(lastCallTime)
}
}
if (timerId === undefined) {
timerId = startTimer(timerExpired, wait)
}
return result
}
debounced.cancel = cancel
return debounced
}
// console.log(debounce)
var test = setInterval(() => {
console.log('test')
}, 30)
// setInterval(test, 30)
debounce(test, 5000) | b95a9569faa236d3d1b8c2761b9d847735232992 | [
"JavaScript"
] | 1 | JavaScript | lxy2222/utilsForMyself | dbe34d09683d4a7555ea4d1764667044f5f50875 | 7657e2ed9c4cebfffc59479839988b99687d0337 |
refs/heads/master | <file_sep>json.extract! @dog, :id, :name, :bio, :birthday, :created_at, :updated_at
| 63ecd27dc506f69adcfd9192545e9e0bb5673a22 | [
"Ruby"
] | 1 | Ruby | ironn61/hw-crud | ce6b1c704460b6cfe7303f31c390b12d013f8be2 | fbb6b3e06aa74bfdd557d5594f1b2caae6f26569 |
refs/heads/master | <file_sep>app.controller('modlistController', ['$scope', 'modlistService', '$rootScope', '$mdDialog', modlistController]);
function modlistController($scope, modlistService, $rootScope, $mdDialog) {
modlistService.getLists().then(function(list) {
$scope.modlist = list;
});
$parent = $scope;
$scope.$on('MODIFIEDLISTS', function() {
modlistService.getLists().then(function(list) {
$scope.modlist = list;
});
});
$scope.rename = function(ev, $index) {
var item = $scope.modlist[$index];
$mdDialog.show({
controller: renameListController,
templateUrl: 'app/templates/AddListPrompt.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: false
});
function renameListController($scope, $mdDialog, modlistService) {
$scope.listname = item.name;
$scope.double = [];
$scope.title = 'Rename List';
$scope.checkdoubles = function() {
$scope.double = $parent.modlist.filter(function(list) {
return $scope.listname === list.name;
});
};
$scope.submitForm = function(valid) {
if (valid && $scope.double.length === 0) {
item.name = $scope.listname;
modlistService.rename(item);
$mdDialog.cancel();
}
};
$scope.cancel = function() {
$mdDialog.cancel();
};
}
};
$scope.delete = function(ev, $index) {
var confirm = $mdDialog.confirm()
.title('Really Delete ?')
.content('List '+$scope.modlist[$index].name+' will be deleted, are you sure ?')
.ok('Delete')
.cancel('Cancel')
.targetEvent(ev);
$mdDialog.show(confirm).then(function() {
modlistService.remove($scope.modlist[$index].path);
$scope.modlist.splice($index, 1);
}, function() {
$mdDialog.cancel();
});
};
$scope.selectList = function($index) {
$rootScope.$broadcast('USELIST', $scope.modlist[$index].wads, $scope.modlist[$index].name);
};
}<file_sep>var recursive = require('recursive-readdir');
app.factory('modService', ['$q',modService]);
function modService($q) {
var service = {};
service.readDir = function(wadpath) {
var defer = $q.defer();
recursive(wadpath, function(err, files) {
if (typeof files === 'undefined') {
return [];
}
var wad;
var len = files.length;
var index = [];
var mods = [];
var allowed = ['PK3', 'WAD'];
for (var i = 0; i < len; i++) {
var struc = files[i].split('\\'),
dirname = struc[struc.length - 2],
ext = struc[struc.length - 1].slice(-3).toUpperCase(),
name = struc[struc.length - 1].slice(0, -4);
if (allowed.indexOf(ext) < 0) {
continue;
}
mods.push({name: name, dir: dirname, checked: false, path: files[i]});
}
defer.resolve(mods);
});
return defer.promise;
};
service.getMods = function(config) {
return service.readDir(config.wadpath);
};
return service;
}<file_sep>var path = require('path'),
fs = require('fs');
app.controller('appController', ['$scope', '$mdDialog', '$mdToast', '$mdBottomSheet', '$mdSidenav', 'modlistService', appController]);
function appController($scope, $mdDialog, $mdToast, $mdBottomSheet, $mdSidenav, modlistService) {
var $PARENT = $scope;
var CONFIGFILE = '/config.json';
var TOASTDELAY = 1500;
$scope.reload = function() {
window.location.reload();
};
$scope.openMenu = function($mdOpenMenu, ev) {
originatorEv = ev;
$mdOpenMenu(ev);
};
$scope.toggleSidebar = function() {
$mdSidenav('left').toggle();
};
$scope.showAboutDialog = function(ev) {
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.querySelector('#popupContainer')))
.clickOutsideToClose(true)
.title('About')
.content('(c) 2015 FreaKzero, Licensed under MIT License. \n Angular Material, NWJS')
.ok('Yup')
.targetEvent(ev)
);
};
$scope.showGameSelection = function($event) {
$mdBottomSheet.show({
templateUrl: 'app/templates/GameSelection.html',
controller: GameSelectionController,
targetEvent: $event
});
function GameSelectionController($scope, $mdBottomSheet) {
$scope.obligeactive = $PARENT.config.obligeactive;
$scope.startGame = function($index) {
var iwad = $scope.iwads[$index].file;
$PARENT.$broadcast('STARTGZDOOM', iwad);
$mdBottomSheet.hide();
};
$scope.startGameOblige = function(ev, $index) {
var iwad = $scope.iwads[$index].file;
$mdBottomSheet.hide();
$mdDialog.show({
controller: ConfigDialogController,
templateUrl: 'app/templates/SelectConfig.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: false
});
function ConfigDialogController($scope, $mdDialog) {
$scope.mapconfigs = $PARENT.mapconfigs;
$scope.selected = $PARENT.mapconfigs[0];
$scope.start = function($index) {
$PARENT.$broadcast('STARTOBLIGE', iwad, $scope.selected);
};
$scope.cancel = function() {
$mdDialog.hide();
};
}
};
}
};
$scope.showSettings = function(ev) {
$mdDialog.show({
controller: DialogController,
templateUrl: 'app/templates/Settings.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: true
});
function DialogController($scope, $mdDialog) {
modlistService.getLists().then(function(list) {
$scope.modlist = list;
});
$scope.settings = $PARENT.config;
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.save = function() {
var appPath = path.dirname(process.execPath);
fs.writeFile(appPath + CONFIGFILE, JSON.stringify($scope.settings, null, 4), function(err) {
if (err) {
$mdToast.show(
$mdToast.simple().content('Error Occured please Restart').position('bottom').hideDelay(TOASTDELAY)
);
throw err;
} else {
$mdToast.show(
$mdToast.simple().content('Saved Settings - Reloading...').position('bottom').hideDelay(TOASTDELAY)
);
setTimeout(function() {
window.location.reload();
}, TOASTDELAY + 500);
}
});
$mdDialog.cancel();
};
}
};
}<file_sep>var path = require('path'),
fs = require('fs'),
recursive = require('recursive-readdir');
app.factory('modlistService', ['$q', '$rootScope',modlistService]);
function modlistService($q, $rootScope) {
var service = {};
var listDir = path.dirname(process.execPath)+'\\lists\\';
service.rename = function(item) {
var newPath = path.dirname(item.path) +'\\'+item.name+'.json';
fs.rename(item.path, newPath, function(err) {
if ( err ) console.log('ERROR: ' + err);
});
};
service.remove = function(path) {
fs.unlinkSync(path);
};
service.saveSelected = function(name, list) {
fs.writeFile(listDir+name+".json", JSON.stringify(list), function(err) {
if(err) {
return alert(err);
}
});
$rootScope.$broadcast('MODIFIEDLISTS');
};
service.readDir = function(wadpath) {
var defer = $q.defer();
recursive(wadpath, function(err, files) {
if (typeof files === 'undefined') {
return [];
}
var wad;
var len = files.length;
var index = [];
var lists = [];
var allowed = ['JSON'];
for (var i = 0; i < len; i++) {
var struc = files[i].split('\\'),
ext = struc[struc.length - 1].slice(-4).toUpperCase(),
name = struc[struc.length - 1].slice(0, -5);
if (allowed.indexOf(ext) < 0) {
continue;
}
lists.push({
name: name,
path: files[i],
wads: JSON.parse(fs.readFileSync(files[i], "utf8"))
});
}
defer.resolve(lists);
});
return defer.promise;
};
service.getLists = function() {
return service.readDir(listDir);
};
return service;
}<file_sep>var execFile = require('child_process').execFile,
fs = require('fs');
app.controller('modController', ['$scope', 'modService', 'modlistService', '$mdDialog', modController]);
function modController($scope, modService, modlistService, $mdDialog) {
var self = this;
var $parent = $scope;
$scope.usedList = false;
$scope.selected = [];
modService.getMods($scope.config).then(function(mods) {
$scope.mods = mods;
if ($scope.config.initList !== false) {
try {
var startListJSON = JSON.parse($scope.config.initList);
var startList = JSON.parse(fs.readFileSync(startListJSON.path, "utf8"));
$scope.$broadcast('USELIST', startList, startListJSON.name);
} catch(e) {
console.log(e);
}
}
});
$scope.$on('USELIST', function(ev, wads, name) {
$scope.selected = wads;
$scope.usedList = name;
$scope.mods.filter(function(item) {
item.checked = false;
});
_.each(wads, function(item) {
var index = _.findIndex($scope.mods, {
path: item.path
});
$scope.mods[index].checked = true;
});
});
$scope.newSelected = function() {
$scope.mods.filter(function(item) {
item.checked = false;
});
$scope.selected = [];
$scope.usedList = false;
};
$scope.saveSelected = function(ev) {
$mdDialog.show({
controller: saveSelectedController,
templateUrl: 'app/templates/AddListPrompt.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: false
});
function saveSelectedController($scope, $mdDialog, modlistService) {
$scope.title = 'Save List';
if ($parent.usedList !== false) {
$scope.listname = $parent.usedList;
}
$scope.double = [];
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.checkdoubles = function() {};
$scope.submitForm = function() {
modlistService.saveSelected($scope.listname, $parent.selected);
$mdDialog.cancel();
};
}
};
$scope.moveUp = function($index) {
if ($index > 0) {
_.move($scope.selected, $index, $index - 1);
}
};
$scope.moveDown = function($index) {
if ($scope.selected.length - 1 !== $index) {
_.move($scope.selected, $index, $index + 1);
}
};
$scope.checked = function(mod) {
if (mod.checked === false) {
$scope.selected = _($scope.selected).filter(function(item) {
return item.path !== mod.path;
});
} else {
$scope.selected.push(mod);
}
};
$scope.$on('STARTOBLIGE', function(ev, iwad, config) {
$mdDialog.show({
templateUrl: 'app/templates/ObligeLoading.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: false
});
var child;
var params = ['--batch', $scope.config.mappath];
var endparam = params.concat(['--load'], $scope.config.mapconfig + config);
child = execFile($scope.config.oblige, endparam, function(error, stdout, stderr) {
if (error) {
$mdDialog.hide();
alert(error.signal);
return false;
}
});
child.on('exit', function(code) {
$mdDialog.hide();
$scope.$broadcast('STARTGZDOOM', iwad, $scope.config.mappath);
});
});
$scope.$on('STARTGZDOOM', function(ev, iwad, map) {
if (typeof map === 'undefined') {
map = false;
}
var child;
var params = ['-iwad', $scope.config.iwadpath + iwad];
var wads = $scope.selected.map(function(item) {
return item.path;
});
if (map !== false) {
wads.push(map);
}
params = params.concat(['-file'], wads);
child = execFile($scope.config.gzDoom, params,
function(error, stdout, stderr) {
if (error) {
console.log(error.stack);
console.log('Error code: ' + error.code + ' ' + error.signal);
}
});
child.on('exit', function(code) {
console.log('EXIT: ' + code);
});
});
} | b1fd89f4e249e3e5d6b41b9a472ba22495071a3c | [
"JavaScript"
] | 5 | JavaScript | gitter-badger/gzdoom-launcher | 080d31d800c6db89cbe9175a3422bc8e3c8d7d33 | c7f6722de670510e670de32fb5a46e6f6198e3ae |
refs/heads/master | <repo_name>xpectro93/lab1<file_sep>/giphy.js
const axios = require("axios");
const express = require("express");
const app = express();
// const getGifs = (req, res, next) => {
// axios.get(`http://api.giphy.com/v1/gifs/search?q=${searched}&api_key=M0232PRL539A1xx8A99hwy0GOMWW0SIO`)
// .then(response => {
// res.gifs = response.data.data;
// next();
// })
// }
//localhost:3000/gif/?search=spongebob
app.get('/:gif', (req, res) => {
let gifSearched = req.params.gif;
let route = req.params.route;
let inputs = req.query;
let theSearched = inputs['search']
let searchh = [];
// console.log(gifSearched);
axios.get(`http://api.giphy.com/v1/gifs/search?q=${theSearched}&api_key=M0232PRL539A1xx8A99hwy0GOMWW0SIO`)
.then(response => {
res.gifs = response.data.data
//.images.downsized.url
console.log(res.gifs[0].images.downsized.url)
searchh.push(res.gifs[0].images.downsized.url);
res.json(searchh);
})
});
app.listen(3000, (req, res) => {
console.log("You are listening to port 3000 at gif");
}); | c723c48deb62329ea01091622e440bba90c1ef97 | [
"JavaScript"
] | 1 | JavaScript | xpectro93/lab1 | 336e86ae1b03a680b5f02261d57475054fbdcbfc | 5d5a52c2f3923c88ba23baf711f2660e994e2974 |
refs/heads/master | <file_sep>// +build !go1.10
package raven
import (
"strings"
)
// Determines whether frame should be marked as InApp
func isInAppFrame(frame StacktraceFrame, appPackagePrefixes []string) bool {
if frame.Module == "main" {
return true
}
for _, prefix := range appPackagePrefixes {
if strings.HasPrefix(frame.Module, prefix) &&
!strings.Contains(frame.Module, "vendor") &&
!strings.Contains(frame.Module, "third_party") {
return true
}
}
return false
}
<file_sep>// +build go1.10
package raven
import (
"go/build"
"os"
"strings"
)
// As of go 1.10, the value of build.Default.GOROOT in a running program is
// either $GOROOT of the executing machine, if set, or $GOROOT/$GOROOT_FINAL of
// the building machine (set by the linker). We want the latter, so we can
// reliably identify stack frames from go stdlib packages.
//
// See https://go-review.googlesource.com/c/go/+/86835/ for more details.
//
var gorootFromLinker bool
func init() {
gorootFromLinker = os.Getenv("GOROOT") == ""
}
// Determines whether frame should be marked as InApp
func isInAppFrame(frame StacktraceFrame, appPackagePrefixes []string) bool {
if gorootFromLinker {
if strings.HasPrefix(frame.AbsolutePath, build.Default.GOROOT) ||
strings.Contains(frame.AbsolutePath, "/go/pkg/mod/") ||
strings.Contains(frame.Module, "vendor") ||
strings.Contains(frame.Module, "third_party") {
return false
}
return true
} else {
if frame.Module == "main" {
return true
}
for _, prefix := range appPackagePrefixes {
if strings.HasPrefix(frame.Module, prefix) &&
!strings.Contains(frame.AbsolutePath, "/go/pkg/mod/") &&
!strings.Contains(frame.Module, "vendor") &&
!strings.Contains(frame.Module, "third_party") {
return true
}
}
return false
}
}
| 8da55fbe918ade4651a789031039e1981b186f10 | [
"Go"
] | 2 | Go | tooolbox/raven-go | a851f364251b9191fb8ddcacddf4a8fe9492afa9 | 741494f4b34c7d40c8aed6b311a81d6574dd7276 |
refs/heads/master | <repo_name>Prateek93a/quickcert-client<file_sep>/scripts/coach.js
window.onload=()=>{
}
const handleSubmit =()=>{
const selectElementValue = document.querySelector('select').value;
const name1 = document.getElementById('name1').value;
const name2 = document.getElementById('name2').value;
const name3 = document.getElementById('name3').value;
const class1 = document.getElementById('class1').value;
const class2 = document.getElementById('class2').value;
const class3 = document.getElementById('class3').value;
const section1 = document.getElementById('section1').value;
const section2 = document.getElementById('section2').value;
const section3 = document.getElementById('section3').value;
let jsonobj = {
"eventID":selectElementValue,
"firstName":name1,
"firstSection":section1,
"firstClass":class1,
"secondName":name2,
"secondSection":section2,
"secondClass":class2,
"thirdName":name3,
"thirdSection":section3,
"thirdClass":class3,
}
fetch(`https://event-certificate-service.herokuapp.com/recordResults`, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // no-referrer, *client
body: JSON.stringify(jsonobj) // body data type must match "Content-Type" header
}).then((response)=>{
return response.json()
}).then((response)=>{
if(response.success===true){
window.location.href='./submitdone.html';
}
})
}<file_sep>/README.md
# event-certificates-system | 038c419fdb3866520cc91bab71b7f0b521f51337 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Prateek93a/quickcert-client | c41b3c8c497bbcbf19d7c1f1dfc56e17eb080cd2 | ff72c2ef36ce53fa954defaa09d45964c434f745 |
refs/heads/master | <repo_name>ZBNLP/FlinkApplications<file_sep>/src/main/java/com/zbcmdata/flink/FlinkApplications/bean/DepMemAuditDataInfo.java
package com.zbcmdata.flink.FlinkApplications.bean;
import java.io.Serializable;
import java.text.ParseException;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
public class DepMemAuditDataInfo implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String stat_date;
private int item_type;
private int department_id;
private int member_id;
private int audit_cnt;
private int firstaudited_cnt;
private int againaudited_cnt;
private int firstpassed_audit_cnt;
private int againpassed_audit_cnt;
private int firstnopassed_audit_cnt;
private int nopassed_audit_cnt;
public int getMember_id() {
return member_id;
}
public void setMember_id(int member_id) {
this.member_id = member_id;
}
public void setStatDate(String stat_date){
this.stat_date = stat_date;
}
public String getStatDate(){
return this.stat_date;
}
public void setDepartment(int department_id){
this.department_id = department_id;
}
public int getDepartment(){
return this.department_id;
}
public void setItemType(int item_type){
this.item_type = item_type;
}
public int getItemType(){
return this.item_type;
}
public void setAudited(int audit_cnt){
this.audit_cnt = audit_cnt;
}
public int getAudited(){
return this.audit_cnt;
}
public void setFirstHasAudited(int firstaudited_cnt){
this.firstaudited_cnt = firstaudited_cnt;
}
public int getFirstHasAudited(){
return this.firstaudited_cnt;
}
public void setAgainHasAudited(int againaudited_cnt){
this.againaudited_cnt = againaudited_cnt;
}
public int getAgainHasAudited(){
return this.againaudited_cnt;
}
public void setFirstPassAudited(int firstpassed_audit_cnt){
this.firstpassed_audit_cnt = firstpassed_audit_cnt;
}
public int getFirstPassAudited(){
return this.firstpassed_audit_cnt;
}
public void setAgainPassAudited(int againpassed_audit_cnt){
this.againpassed_audit_cnt = againpassed_audit_cnt;
}
public int getAgainPassAudited(){
return this.againpassed_audit_cnt;
}
public void setNoPassAudited(int allpassed_audit_cnt){
this.nopassed_audit_cnt = allpassed_audit_cnt;
}
public int getNoPassAudited(){
return this.nopassed_audit_cnt;
}
public int getFirstNoPassAudited() {
return firstnopassed_audit_cnt;
}
public void setFirstNoPassAudited(int firstnopassed_audit_cnt) {
this.firstnopassed_audit_cnt = firstnopassed_audit_cnt;
}
/**
* kafka队列中传递过来的原始日志数据
*
* @throws JSONException
* */
/**
* @param jsonString
* @return ItemInfo
* @throws JSONException
* @throws ParseException
*/
public static DepMemAuditDataInfo parseFromJson(String jsonString)throws JSONException, ParseException{
JSONObject object = JSONObject.parseObject(jsonString);
DepMemAuditDataInfo depMemauditInfo = new DepMemAuditDataInfo();
depMemauditInfo.setStatDate(object.getString("stat_date"));
if (object.containsKey("action_group")) {
depMemauditInfo.setDepartment(object.getIntValue("action_group"));
}else {
depMemauditInfo.setDepartment(-1);
}
if (object.containsKey("item_type")) {
depMemauditInfo.setItemType(object.getIntValue("item_type"));
}else {
depMemauditInfo.setItemType(-1);
}
if (object.containsKey("action_person")) {
depMemauditInfo.setMember_id(object.getIntValue("action_person"));
}else {
depMemauditInfo.setMember_id(-1);
}
if (object.containsKey("audit_cnt")) {
depMemauditInfo.setAudited(object.getIntValue("audit_cnt"));
}else {
depMemauditInfo.setAudited(0);
}
if (object.containsKey("firstaudited_cnt")) {
depMemauditInfo.setFirstHasAudited(object.getIntValue("firstaudited_cnt"));
}else {
depMemauditInfo.setFirstHasAudited(0);
}
if (object.containsKey("againaudited_cnt")) {
depMemauditInfo.setAgainHasAudited(object.getIntValue("againaudited_cnt"));
}else {
depMemauditInfo.setAgainHasAudited(0);
}
if (object.containsKey("firstpassed_audit_cnt")) {
depMemauditInfo.setFirstPassAudited(object.getIntValue("firstpassed_audit_cnt"));
}else {
depMemauditInfo.setFirstPassAudited(0);
}
if (object.containsKey("againpassed_audit_cnt")) {
depMemauditInfo.setAgainPassAudited(object.getIntValue("againpassed_audit_cnt"));
}else {
depMemauditInfo.setAgainPassAudited(0);
}
if (object.containsKey("firstnopassed_audit_cnt")) {
depMemauditInfo.setFirstNoPassAudited(object.getIntValue("firstnopassed_audit_cnt"));
}else {
depMemauditInfo.setFirstNoPassAudited(0);
}
if (object.containsKey("nopassed_audit_cnt")) {
depMemauditInfo.setNoPassAudited(object.getIntValue("nopassed_audit_cnt"));
}else {
depMemauditInfo.setNoPassAudited(0);
}
return depMemauditInfo;
}
}
<file_sep>/src/main/java/com/zbcmdata/flink/FlinkApplications/streaming/onlineRecommend/v2/UserPreferenceEstimationFunction.java
package com.zbcmdata.flink.FlinkApplications.streaming.onlineRecommend.v2;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.util.Collector;
import redis.clients.jedis.ScanParams;
import redis.clients.jedis.ScanResult;
import redis.clients.jedis.Tuple;
import com.alibaba.fastjson.JSONObject;
import com.zbcmdata.flink.common.Constant;
import com.zbcmdata.flink.service.redis.RedisClient;
import com.zbcmdata.flink.util.LogUtil;
import redis.clients.jedis.exceptions.JedisConnectionException;
public class UserPreferenceEstimationFunction extends RichFlatMapFunction<Tuple2<String, String>, String>{
private static final Log LOGGER = LogFactory.getLog(UserPreferenceEstimationFunction.class);
public RedisClient redisClient = null;
@Override
public void flatMap(Tuple2<String, String> input, Collector<String> collector) throws Exception {
// TODO Auto-generated method stub
//System.out.println(LogUtil.logTime() + "EstimationFunction fetch input: " + input.f1 + ", user:" + input.f0 + "\n");
String collectOutJson = getRecommendVideos(input);
collector.collect(collectOutJson);
}
public String getRecommendVideos(Tuple2<String, String> input) throws Exception{
boolean isSuccess = true;
String user = input.f0;
user = user.replace("(", "");
user = user.replace(")", "");
String weightList = input.f1;
String[] pairs = weightList.split(" ");
List<String> recList = new ArrayList<String>();
for (String pair : pairs) {
int itemId = -1;
int type = -1;
try {
String[] temps = pair.split(":");
String key = temps[0];
type = Integer.parseInt(key.split("_")[0]);
itemId = Integer.parseInt(key.split("_")[1]);
double weight = Double.parseDouble(temps[1]);
insertFilterRecord(user, type, itemId);
List<Tuple> candidateList = getCandidateList(itemId, type);
for (Tuple tuple : candidateList) {
recList.add(type + "_" + tuple.getElement() + ":" + weight * tuple.getScore());
}
} catch (Exception e) {
// TODO: handle exception
System.out.println(LogUtil.logTime() + "EstimationFunction exception for type: " + type + ", pair:" + pair + "\n");
e.printStackTrace();
}
}
String ss = String.join(",", recList);
JSONObject collectOutJson = new JSONObject();
collectOutJson.put("user", user);
collectOutJson.put("recScoreList", ss);
System.out.println(LogUtil.logTime() + "UserPreferenceEstimationFunction collect out "
+ recList.size()
+ " original recommend items for user:" + user + "\n");
return collectOutJson.toString();
}
public List<Tuple> getCandidateList(int itemId, int type) throws Exception{
if (redisClient.isClose()) {
redisClient = new RedisClient();
}
String cursor = ScanParams.SCAN_POINTER_START;
String key = Constant.ZQRSJ_CUSTOM_ID + "_3" + type + "1_" + itemId;
ScanResult<Tuple> result = redisClient.ZSCAN(key, cursor, Constant.REDIS_ZQRSJ_VIDEO_ZSCAN_COUNT);
List<Tuple> list = result.getResult();
return list;
}
public void insertFilterRecord(String user, int type, int candidate){
String watchedKey = Constant.ZQRSJ_CUSTOM_ID + "_" + type + "_watched_" + user + "_" + candidate;
redisClient.set(watchedKey, "1");
}
@Override
public void open(Configuration configuration)throws Exception{
redisClient = new RedisClient();
LOGGER.info("UserPreferenceEstimationFunction create Redis Client Connection!");
super.open(configuration);
}
@Override
public void close()throws Exception{
LOGGER.info("UserPreferenceEstimationFunction close Redis Client Connection!");
redisClient.close();
}
}
<file_sep>/src/main/java/com/zbcmdata/flink/FlinkApplications/bean/DepAuditDataInfo.java
package com.zbcmdata.flink.FlinkApplications.bean;
import java.io.Serializable;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.zbcmdata.flink.util.StringUtil;
public class DepAuditDataInfo implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String stat_date;
private int department_id;
private int item_type;
private int incoming_audit_cnt;
private int firstaudited_cnt;
private int againaudited_cnt;
private int passed_audit_cnt;
private int firstpassed_audit_cnt;
private int againpassed_audit_cnt;
private int nopassed_audit_cnt;
public void setStatDate(String stat_date){
this.stat_date = stat_date;
}
public String getStatDate(){
return this.stat_date;
}
public void setDepartment(int department_id){
this.department_id = department_id;
}
public int getDepartment(){
return this.department_id;
}
public void setItemType(int item_type){
this.item_type = item_type;
}
public int getItemType(){
return this.item_type;
}
public void setInComing(int incoming_audit_cnt){
this.incoming_audit_cnt = incoming_audit_cnt;
}
public int getInComing(){
return this.incoming_audit_cnt;
}
public void setFirstHasAudited(int firstaudited_cnt){
this.firstaudited_cnt = firstaudited_cnt;
}
public int getFirstHasAudited(){
return this.firstaudited_cnt;
}
public void setAgainHasAudited(int againaudited_cnt){
this.againaudited_cnt = againaudited_cnt;
}
public int getAgainHasAudited(){
return this.againaudited_cnt;
}
public void setPassAudited(int passed_audit_cnt){
this.passed_audit_cnt = passed_audit_cnt;
}
public int getPassAudited(){
return this.passed_audit_cnt;
}
public void setFirstPassAudited(int firstpassed_audit_cnt){
this.firstpassed_audit_cnt = firstpassed_audit_cnt;
}
public int getFirstPassAudited(){
return this.firstpassed_audit_cnt;
}
public void setAgainPassAudited(int againpassed_audit_cnt){
this.againpassed_audit_cnt = againpassed_audit_cnt;
}
public int getAgainPassAudited(){
return this.againpassed_audit_cnt;
}
public void setNoPassAudited(int allpassed_audit_cnt){
this.nopassed_audit_cnt = allpassed_audit_cnt;
}
public int getNoPassAudited(){
return this.nopassed_audit_cnt;
}
/**
* kafka队列中传递过来的原始日志数据
*
* @throws JSONException
* */
/**
* @param jsonString
* @return ItemInfo
* @throws JSONException
* @throws ParseException
*/
public static DepAuditDataInfo parseFromJson(String jsonString)throws JSONException, ParseException{
JSONObject object = JSONObject.parseObject(jsonString);
DepAuditDataInfo depauditInfo = new DepAuditDataInfo();
depauditInfo.setStatDate(object.getString("stat_date"));
if (object.containsKey("action_group")) {
depauditInfo.setDepartment(object.getIntValue("action_group"));
}else {
depauditInfo.setDepartment(-1);
}
if (object.containsKey("item_type")) {
depauditInfo.setItemType(object.getIntValue("item_type"));
}else {
depauditInfo.setItemType(-1);
}
if (object.containsKey("incoming_audit_cnt")) {
depauditInfo.setInComing(object.getIntValue("incoming_audit_cnt"));
}else {
depauditInfo.setInComing(0);
}
if (object.containsKey("firstaudited_cnt")) {
depauditInfo.setFirstHasAudited(object.getIntValue("firstaudited_cnt"));
}else {
depauditInfo.setFirstHasAudited(0);
}
if (object.containsKey("againaudited_cnt")) {
depauditInfo.setAgainHasAudited(object.getIntValue("againaudited_cnt"));
}else {
depauditInfo.setAgainHasAudited(0);
}
if (object.containsKey("passed_audit_cnt")) {
depauditInfo.setPassAudited(object.getIntValue("passed_audit_cnt"));
}else {
depauditInfo.setPassAudited(0);
}
if (object.containsKey("firstpassed_audit_cnt")) {
depauditInfo.setFirstPassAudited(object.getIntValue("firstpassed_audit_cnt"));
}else {
depauditInfo.setFirstPassAudited(0);
}
if (object.containsKey("againpassed_audit_cnt")) {
depauditInfo.setAgainPassAudited(object.getIntValue("againpassed_audit_cnt"));
}else {
depauditInfo.setAgainPassAudited(0);
}
if (object.containsKey("nopassed_audit_cnt")) {
depauditInfo.setNoPassAudited(object.getIntValue("nopassed_audit_cnt"));
}else {
depauditInfo.setNoPassAudited(0);
}
return depauditInfo;
}
}
<file_sep>/src/main/java/com/zbcmdata/flink/service/dao/StoreServiceFactory.java
package com.zbcmdata.flink.service.dao;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang.time.StopWatch;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.log4j.Logger;
import com.zbcmdata.flink.service.dao.impl.HBaseDaoImpl;
/**
*
* @author micahel.shentu
* @since 2014-08-01
*
* */
public class StoreServiceFactory {
private static Logger LOG = Logger.getLogger(StoreServiceFactory.class);
private static HbaseDao hbaseDao = null;
private static Properties properties = null;
public static void setHbaseDao(HBaseDaoImpl hBaseDaoImpl){
hbaseDao = hBaseDaoImpl;
}
public static HbaseDao getHbaseDao(){
try {
if (hbaseDao == null) {
hbaseDao = new HBaseDaoImpl();
}
return hbaseDao;
} catch (Exception e) {
// TODO: handle exception
return null;
}
}
public static HbaseDao getHbaseDao(String confPath){
try {
return new HBaseDaoImpl(confPath);
} catch (Exception e) {
// TODO: handle exception
return null;
}
}
public static HbaseDao getHbaseDao(Properties properties)throws Exception{
try {
return new HBaseDaoImpl(properties);
} catch (Exception e) {
// TODO: handle exception
throw e;
}
}
}
<file_sep>/src/main/java/com/zbcmdata/flink/FlinkApplications/functions/userFunction/IncomingProcessFunction.java
package com.zbcmdata.flink.FlinkApplications.functions.userFunction;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.flink.api.common.functions.MapFunction;
import com.alibaba.fastjson.JSONObject;
import com.zbcmdata.flink.FlinkApplications.bean.DepAuditDataInfo;
import com.zbcmdata.flink.common.Constant;
import com.zbcmdata.flink.FlinkApplications.streaming.rongcloudBI.service.dao.MysqlDao;
import com.zbcmdata.flink.FlinkApplications.streaming.rongcloudBI.service.dao.impl.MysqlDaoImpl;
public class IncomingProcessFunction implements MapFunction<String, String>{
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static final Log LOGGER = LogFactory.getLog(NLPAnalysisFunction.class);
@Override
public String map(String value) throws Exception {
// TODO Auto-generated method stub
String create_time = null;
String st_date = null;
int item_id = 0;
int item_type = 0;
String item_label = null;
int action_type = 0;
int action_result = 0;
String remarks = null;
int action_group = 0;
int action_person = 0;
String timeKey = null;
MysqlDao mysqlDao = new MysqlDaoImpl(Constant.MTY_CONFIGURE_DIR + File.separator +
"configure/client/client_storeservice_conf.properties");
String dep_audit_daily_table = "dep_audit_data_sdt0";
String dep_wait_audit_table = "dep_wait_audit_data_fdt0";
//全量累计中需要单独计算的:待初审量 待复审量
int dep_wait_firstaudit_cnt = 0;
//区间中需要计算的:进审量
int depIncomingAudit;
StringBuffer stringBuffer = new StringBuffer();
String nowDatetime = null;
int i=0;
int waitData_key = 0;
int member_key = 0;
String key = null;
int value1 = 0;
JSONObject jsonObject = JSONObject.parseObject(value);
JSONObject dayDepAuditDataInfo = new JSONObject();
DepAuditDataInfo depAuditDataInfo;
create_time = jsonObject.getString("createtime");
action_group = jsonObject.getIntValue("action_group");
item_id = jsonObject.getIntValue("item_id");
item_type = jsonObject.getIntValue("item_type");
item_label = jsonObject.getString("item_label");
action_type = jsonObject.getIntValue("action_type");
action_result = jsonObject.getIntValue("action_result");
remarks = jsonObject.getString("remarks");
action_person = jsonObject.getIntValue("action_person");
//append函数将记录不断追加在变量
stringBuffer.append("进审日志内容 createtime:" + create_time + " item_id:" + item_id + " item_type:" + item_type + " item_label:" + item_label + " action_type:" + action_type + " action_result:" + action_result + " remarks:" + remarks + " action_group:" + action_group + " action_person:" + action_person + "\n");
//System.out.println(stringBuffer);
st_date = create_time.substring(0,10);
String select_depincomedata_sql = "select incoming_audit_cnt from " + dep_audit_daily_table + " where stat_date = '" + st_date + "' and item_type = " + item_type ;
List<HashMap<String, String>> dep_income_list;
String select_depwaitdata_sql = "select department_id,wait_firstaudit_cnt from " + dep_wait_audit_table + " where item_type = " + item_type;
List<HashMap<String, String>> dep_waitaudit_list;
//进审
if ( action_type == 0 ) {
//2System.out.println("进审");
dep_income_list = mysqlDao.query(select_depincomedata_sql, 3);
dep_waitaudit_list = mysqlDao.query(select_depwaitdata_sql, 3);
//初始化进审量,每个部门都相同,并进行进审量 + 1
if ( ! dep_income_list.isEmpty() ) {//需要更新当天所以部门对应的进审
depIncomingAudit = Integer.parseInt(dep_income_list.get(0).get("incoming_audit_cnt")) + 1;
mysqlDao.updateDepIncomeData(dep_audit_daily_table, st_date, item_type,depIncomingAudit, 3);
}
else {//需要插入,默认指定"太梦"审核团队 id为1
depIncomingAudit = 1;
dayDepAuditDataInfo.put("stat_date", st_date);
dayDepAuditDataInfo.put("action_group",1);
dayDepAuditDataInfo.put("item_type", item_type);
dayDepAuditDataInfo.put("incoming_audit_cnt", depIncomingAudit);
dayDepAuditDataInfo.put("firstaudited_cnt", 0);
dayDepAuditDataInfo.put("againaudited_cnt", 0);
dayDepAuditDataInfo.put("passed_audit_cnt", 0);
dayDepAuditDataInfo.put("firstpassed_audit_cnt", 0);
dayDepAuditDataInfo.put("againpassed_audit_cnt", 0);
dayDepAuditDataInfo.put("nopassed_audit_cnt", 0);
depAuditDataInfo = DepAuditDataInfo.parseFromJson(dayDepAuditDataInfo.toString());
mysqlDao.updateInsertDepAuditResultRecord(dep_audit_daily_table, depAuditDataInfo, 3);
}
//初始化初审待审量,每个部门不一定相同,并进行待初审量 + 1
if ( ! dep_waitaudit_list.isEmpty() ) {//需要更新全部团队的
for(HashMap<String, String> map:dep_waitaudit_list) {
waitData_key = Integer.parseInt(map.get("department_id"));
value1 = Integer.parseInt(map.get("wait_firstaudit_cnt")) + 1;
//depwaitDataMap.put(waitData_key, value);
mysqlDao.updateDepWaitData(dep_wait_audit_table,item_type,waitData_key, value1, 3);
}
} else {//需要插入,默认指定"太梦"审核团队 id为1
dep_wait_firstaudit_cnt =1;
mysqlDao.updateInsertDepWaitAuditResultRecord(dep_wait_audit_table,item_type, 1,1, 0, 3);
}
return new JSONObject().toJSONString();
} else {
//进入初审和复审计算逻辑
return jsonObject.toString();
}
}
}
<file_sep>/src/resources/product/configure/client/mail.properties
mail.protocol =smtp
mail.host =smtp.126.com
mail.port =25
mail.username =<EMAIL>
mail.password =<PASSWORD>!
mail.defaultEncoding =UTF-8
mail.receiver=<file_sep>/src/main/java/com/zbcmdata/flink/util/PropertiesFileUtil.java
package com.zbcmdata.flink.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.util.Properties;
public class PropertiesFileUtil {
/**
* @author michael.shentu
* @since 2014-11-07
* */
public static Properties load(String CONFIGFILE){
Properties props = null;
InputStream istream = null;
try {
if (CONFIGFILE.startsWith("classpath")) {
istream = PropertiesFileUtil.class.getResourceAsStream("/"
+ CONFIGFILE.split(":")[1]);
} else {
istream = new FileInputStream(CONFIGFILE);
}
props = new Properties();
props.load(istream);
istream.close();
} catch (Exception e) {
if (e instanceof InterruptedIOException
|| e instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
e.printStackTrace();
} finally {
if (istream != null) {
try {
istream.close();
} catch (InterruptedIOException ignore) {
Thread.currentThread().interrupt();
} catch (Throwable ignore) {
}
}
}
return props;
}
public static void main(String args[]) {
Properties p = load("classpath:configure/client/client_storeservice_conf.properties");
System.out.println("db.oracle.jdbcUrl: " + p.get("db.oracle.jdbcUrl"));
System.out.println("db.oracle.user: " + p.get("db.oracle.user"));
}
}
<file_sep>/src/main/java/com/zbcmdata/flink/FlinkApplications/functions/sink/elasticsearch/FlinkElasticsearchSink.java
package com.zbcmdata.flink.FlinkApplications.functions.sink.elasticsearch;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkFunction;
import org.apache.flink.streaming.connectors.elasticsearch.RequestIndexer;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.Requests;
import com.alibaba.fastjson.JSONObject;
public class FlinkElasticsearchSink implements ElasticsearchSinkFunction<String>{
public IndexRequest createIndexRequest(JSONObject elements) {
String index = elements.getString("index_name");
String index_type = elements.getString("index_type");
Map<String, String> source = new HashMap<String, String>();
source.put("title", elements.getString("title"));
source.put("description", elements.getString("description"));
source.put("tag1", elements.getString("tag1"));
source.put("tag2", elements.getString("tag2"));
source.put("publish_time", elements.getString("publish_time"));
System.out.println("Index Request, Source: " + source.toString());
return Requests.indexRequest().index(index).type(index_type)
.id(elements.getString("item_id")).source(source);
}
@Override
public void process(String jsonString, RuntimeContext runtimeContext,
RequestIndexer requestIndexer) {
// TODO Auto-generated method stub
if ("NULL".equals(jsonString)) {
return;
}else {
try {
requestIndexer.add(createIndexRequest(JSONObject.parseObject(jsonString)));
} catch (Exception e) {
// TODO: handle exception
System.out.println("ES Index Exception for json: " + jsonString);
e.printStackTrace();
}
}
}
}
<file_sep>/src/test/java/com/zbcmdata/flink/FlinkApplications/util/JSONTest.java
package com.zbcmdata.flink.FlinkApplications.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.flink.table.shaded.org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import junit.framework.TestCase;
public class JSONTest extends TestCase {
public void testParseObject(){
/*
* FileReader reader = new FileReader("D:/test.txt"); BufferedReader br = new
* BufferedReader(reader); String line = br.readLine();
* System.out.println(line); JSONObject json = JSONObject.parseObject(line);
* String line2 = StringCharsetUtil.changeCharset(line, "UTF-8");
* System.out.println(line2);
*/
String[] keys = { "log_type", "log_version", "type", "item_id", "custom_id", "publish_time", "title",
"description", "duration", "is_check_time", "video_from", "filesize", "status", "tags" };
/*
* String tmp = "[{\"tag1\":\"\",\"tag2\":\"\"}]";
* System.out.println(tmp);
*/
FileReader reader = null;
Map<String,BufferedWriter> fileMap=new HashMap<String,BufferedWriter>();
try {
reader = new FileReader("D://abc.txt");
BufferedReader br = new BufferedReader(reader);
String line=null;
while ((line=br.readLine()) != null) {
String[] words = line.split("\t");
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONObject tagsJson = new JSONObject();
for (int i = 0; i < keys.length; i++) {
if ( i == 13 && ("null".equals(words[i]) || "NULL".equals(words[i]) || "\\N".equals(words[i]) || words[i].isEmpty())) {
words[i] = "[{\"tag1\":\"\",\"tag2\":\"\"}]";
jsonArray = JSONArray.parseArray(words[i]);
jsonObject.put(keys[i], jsonArray);
} else if (i == 13 ) {
//System.out.println(words[i]);
jsonArray = JSONArray.parseArray(words[i]);
jsonObject.put(keys[i], jsonArray);
} else {
if( "null".equals(words[i]) || "NULL".equals(words[i]) || "\\N".equals(words[i]) || words[i].isEmpty()) {
words[i] = "";
}
jsonObject.put(keys[i], words[i]);
}
}
String fileName=(String)jsonObject.get("publish_time");
if(StringUtils.isNoneBlank(fileName)&&fileName.length()>10) {
fileName=fileName.substring(0, 10);
BufferedWriter bw=fileMap.get(fileName);
if(bw==null) {
FileWriter fw = new FileWriter("D://Buffered"+fileName+".txt");
bw=new BufferedWriter(fw);
fileMap.put(fileName, bw);
}
bw.write(jsonObject.toJSONString());
bw.newLine();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(reader!=null) {try {reader.close();} catch (IOException e) {e.printStackTrace();}}
for(BufferedWriter bw:fileMap.values()) {
try {bw.close();} catch (IOException e) {e.printStackTrace();}
}
}
}
}
<file_sep>/src/main/java/com/zbcmdata/flink/examples/streaming/join/BroadCastWordCountExample3.java
package com.zbcmdata.flink.examples.streaming.join;
import org.apache.flink.api.common.state.BroadcastState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.KeyedBroadcastProcessFunction;
import org.apache.flink.streaming.api.functions.source.RichSourceFunction;
import org.apache.flink.util.Collector;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class BroadCastWordCountExample3 {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
final MapStateDescriptor<String, String> mapStateDescriptor1 = new MapStateDescriptor<>(
"config-keywords",
String.class,
String.class);
// 自定义广播流(单例)
BroadcastStream<String> broadcastStream = env.addSource(new RichSourceFunction<String>() {
private volatile boolean isRunning = true;
//测试数据集
private String[] dataSet = new String[]{
"java",
"swift",
"php",
"go",
"python"
};
/**
* 数据源:模拟每30秒随机更新一次拦截的关键字
* @param ctx
* @throws Exception
*/
@Override
public void run(SourceContext<String> ctx) throws Exception {
while (isRunning) {
TimeUnit.SECONDS.sleep(1);
Random random = new Random();
//todo 定时刷新,睡眠6秒
int i = random.nextInt(5);
ctx.collect(dataSet[i]);
System.out.println("发送的字符串:" +dataSet[i]);
}
}
@Override
public void cancel() {
isRunning = false;
}
}).broadcast(mapStateDescriptor1);
// 自定义数据流(单例)
DataStream<String> dataStream = env.addSource(new RichSourceFunction<String>() {
private volatile boolean isRunning = true;
//测试数据集
private String[] dataSet = new String[]{
"你喜欢武藤兰吗",
"永井流奈也还可以呢",
"青木真麻你了解过吗",
"坂本真綾也是很不错的呢",
"佐藤遥希呢,很漂亮呢"
};
/**
* 模拟每3秒随机产生1条消息
* @param ctx
* @throws Exception
*/
@Override
public void run(SourceContext<String> ctx) throws Exception {
int size = dataSet.length;
while (isRunning) {
TimeUnit.SECONDS.sleep(3);
int seed = (int) (Math.random() * size);
ctx.collect(dataSet[seed]);
// System.out.println("kafka接收数据:" + dataSet[seed]);
}
}
@Override
public void cancel() {
isRunning = false;
}
}).setParallelism(1);
dataStream.keyBy(new KeySelector<String, String>(){
@Override
public String getKey(String value) throws Exception {
return value;
}
}).connect(broadcastStream).process(new KeyedBroadcastProcessFunction<String, String, String, String>(){
private final MapStateDescriptor<String, String> mapDescriptor =
new MapStateDescriptor<>(
"RulesBroadcastState",
String.class,
String.class);
@Override
public void open(Configuration parameters) throws Exception {
super.open(parameters);
}
@Override
public void processElement(String value, ReadOnlyContext ctx, Collector<String> out) throws Exception {
String result = ctx.getBroadcastState(mapStateDescriptor1).get("a");
System.out.println("result = " + result+",value = "+value);
}
@Override
public void processBroadcastElement(String value, Context ctx, Collector<String> out) throws Exception {
// System.out.println("mapDescriptor = " + mapDescriptor);
BroadcastState<String,String> broadcastState = ctx.getBroadcastState(mapStateDescriptor1);
broadcastState.put("a",value);
}
});
// List list = new ArrayList<>();
// list.add(new Tuple3("no", 1, 1L));
// list.add(new Tuple3("no", 2, 1L));
// list.add(new Tuple3("yes", 1, 3L));
// list.add(new Tuple3("yes", 1, 4L));
// list.add(new Tuple3("yes", 1, 1L));
// list.add(new Tuple3("flink", 1, 1L));
//
// DataStream<Tuple3<String, Integer, Long>> dataStream = env.fromCollection(list);
// DataStream<String> sourceDstream = env.fromElements("yes", "no");
//
// final MapStateDescriptor<String, String> broadCastConfigDescriptor = new MapStateDescriptor<>("broadCastConfig",
// BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO);
//
//// BroadcastStream<String> broadcastStream = sourceDstream.broadcast(broadCastConfigDescriptor);
// BroadcastStream<String> broadcastStream = sourceDstream.broadcast(broadCastConfigDescriptor);
//
// dataStream.keyBy(0).connect(broadcastStream).process(new KeyedBroadcastProcessFunction<String, Tuple3<String, Integer, Long>,String, Tuple2<String, Integer>>() {
// private final Logger logger = LoggerFactory.getLogger(BroadCastWordCountExample2.class);
//
// private transient MapState<String, Integer> counterState;
//
// int length = 5;
// private final MapStateDescriptor<String, String> mapDescriptor = new MapStateDescriptor<>(
// "broadCastConfig",
// BasicTypeInfo.STRING_TYPE_INFO,
// BasicTypeInfo.STRING_TYPE_INFO);
//
// private final MapStateDescriptor<String, Integer> descriptor = new MapStateDescriptor<>("counter", String.class, Integer.class);
//
// @Override
// public void open(Configuration parameters) throws Exception {
// super.open(parameters);
// counterState = getRuntimeContext().getMapState(descriptor);
//
// }
//
// @Override
// public void processElement(Tuple3<String, Integer, Long> value, ReadOnlyContext ctx, Collector<Tuple2<String, Integer>> out) throws Exception {
//
// //todo 获取的广播变量参数只是 可读
// ReadOnlyBroadcastState<String, String> broadcastState = ctx.getBroadcastState(mapDescriptor);
//
//
// //todo @#@IYU#$ 就是没数据
// String broadcastStateKey111 = broadcastState.get("broadcastStateKey");
// if (broadcastState.contains("broadcastStateKey")) {
// String broadcastStateKey = broadcastState.get("broadcastStateKey");
// System.out.println("broadcastStateKey = " + broadcastStateKey);
// }
//
// //todo 继续
// if (value.f0.length() > length) {
// logger.warn("length of str {} > {}, ignored", value.f0, length);
// return;
// }
// if (counterState.contains(value.f0)) {
// counterState.put(value.f0, counterState.get(value.f0) + value.f1);
// } else {
// counterState.put(value.f0, value.f1);
// }
// out.collect(new Tuple2<>(value.f0, counterState.get(value.f0)));
// }
//
//
// //todo 处理广播变量,赋值
// @Override
// public void processBroadcastElement(String value, Context ctx, Collector<Tuple2<String, Integer>> out) throws Exception {
//
// BroadcastState<String,String> broadcastState = ctx.getBroadcastState(mapDescriptor);
// broadcastState.put("broadcastStateKey1", "aaa");
//// if (broadcastState.contains("broadcastStateKey")) {
//// String oldStr = broadcastState.get("broadcastStateKey");
//// System.out.println("oldStr =" + oldStr +",value = "+value);
////
//// } else {
//// System.out.println("value = " + value);
//// }
//
//
// }
// }).print();
env.execute("BroadCastWordCountExample");
}
}
<file_sep>/src/main/java/com/zbcmdata/flink/service/redis/RedisClient.java
package com.zbcmdata.flink.service.redis;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.Map;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.ScanParams;
import redis.clients.jedis.ScanResult;
import redis.clients.jedis.Tuple;
import com.zbcmdata.flink.common.Constant;
import com.zbcmdata.flink.util.PropertiesFileUtil;
public class RedisClient {
private static JedisPool jedisPool = null;
private static Properties properties = null;
private static final String APPEND_SYMBOL = ",";
public RedisClient(){
properties = PropertiesFileUtil.load(Constant.CONFIGURE_DIR + File.separator +
"configure/client/client_storeservice_conf.properties");
initial(properties);
}
public RedisClient(Properties properties){
this.properties = properties;
initial(properties);
}
public void initial(Properties properties){
String host = properties.getProperty("redis.host");
int port = Integer.parseInt(properties.getProperty("redis.port"));
if (jedisPool == null) {
JedisPoolConfig poolConfig = new JedisPoolConfig();
int maxTotal = Integer.parseInt(properties.getProperty("jedis.MaxTotal"));
int maxIdle = Integer.parseInt(properties.getProperty("jedis.MaxIdle"));
poolConfig.setMaxTotal(maxTotal);
poolConfig.setMaxIdle(maxIdle);
poolConfig.setTestOnBorrow(true);
//return 一个jedis实例给pool时,是否检查连接可用性(ping())
poolConfig.setTestOnReturn(true);
jedisPool = new JedisPool(poolConfig, host, port);
}
}
public static RedisClient getRedisClient(){
return new RedisClient();
}
public static RedisClient getRedisClient(Properties properties){
return new RedisClient(properties);
}
public void del(String key){
if (null == jedisPool || jedisPool.isClosed()) {
initial(properties);
}
Jedis jedis = null;
jedis = jedisPool.getResource();
jedis.del(key);
if (jedis.isConnected()) {
jedis.close();
}
}
public void hset(String key, String field, String value){
if (null == jedisPool || jedisPool.isClosed()) {
initial(properties);
}
Jedis jedis = null;
jedis = jedisPool.getResource();
jedis.hset(key, field, value);
if (jedis.isConnected()) {
jedis.close();
}
}
public String hget(String key, String field){
if (null == jedisPool || jedisPool.isClosed()) {
initial(properties);
}
Jedis jedis = null;
jedis = jedisPool.getResource();
String result = jedis.hget(key, field);
if (jedis.isConnected()) {
jedis.close();
}
return result;
}
public boolean hexists(String key, String field){
if (null == jedisPool || jedisPool.isClosed()) {
initial(properties);
}
Jedis jedis = null;
jedis = jedisPool.getResource();
boolean result = jedis.hexists(key, field);
if (jedis.isConnected()) {
jedis.close();
}
return result;
}
public void hdel(String key, String field){
if (null == jedisPool || jedisPool.isClosed()) {
initial(properties);
}
Jedis jedis = null;
jedis = jedisPool.getResource();
jedis.hdel(key, field);
if (jedis.isConnected()) {
jedis.close();
}
}
public Set<String> hkeys(String key){
if (null == jedisPool || jedisPool.isClosed()) {
initial(properties);
}
Jedis jedis = null;
jedis = jedisPool.getResource();
Set<String> result = jedis.hkeys(key);
if (jedis != null) {
jedis.close();
}
return result;
}
public Map<String, String> hgetall(String key){
if (null == jedisPool || jedisPool.isClosed()) {
initial(properties);
}
Jedis jedis = null;
jedis = jedisPool.getResource();
Map<String, String> result = jedis.hgetAll(key);
if (jedis != null) {
jedis.close();
}
return result;
}
public void hmset(String key, HashMap<String, String> map){
if (null == jedisPool || jedisPool.isClosed()) {
initial(properties);
}
Jedis jedis = null;
jedis = jedisPool.getResource();
jedis.hmset(key, map);
if (jedis != null) {
jedis.close();
}
}
public long persist(String key){
if (null == jedisPool || jedisPool.isClosed()) {
initial(properties);
}
Jedis jedis = null;
jedis = jedisPool.getResource();
long result = jedis.persist(key);
if (jedis != null) {
jedis.close();
}
return result;
}
public long expire(String key, int seconds){
if (null == jedisPool || jedisPool.isClosed()) {
initial(properties);
}
Jedis jedis = null;
jedis = jedisPool.getResource();
long result = jedis.expire(key, seconds);
if (jedis != null) {
jedis.close();
}
return result;
}
public boolean exists(String key){
if (null == jedisPool || jedisPool.isClosed()) {
initial(properties);
}
Jedis jedis = null;
jedis = jedisPool.getResource();
boolean result = jedis.exists(key);
if (jedis != null) {
jedis.close();
}
return result;
}
public String set(String key, String value){
if (null == jedisPool || jedisPool.isClosed()) {
initial(properties);
}
Jedis jedis = null;
jedis = jedisPool.getResource();
String result = jedis.set(key, value);
if (jedis != null) {
jedis.close();
}
return result;
}
public String get(String key){
if (null == jedisPool || jedisPool.isClosed()) {
initial(properties);
}
Jedis jedis = null;
jedis = jedisPool.getResource();
String result = jedis.get(key);
if (jedis != null) {
jedis.close();
}
return result;
}
public void sadd(String key, String member){
if (null == jedisPool || jedisPool.isClosed()) {
initial(properties);
}
Jedis jedis = null;
jedis = jedisPool.getResource();
jedis.sadd(key, member);
if (jedis != null) {
jedis.close();
}
}
public void sadd(String key, String[] members){
if (null == jedisPool || jedisPool.isClosed()) {
initial(properties);
}
Jedis jedis = null;
jedis = jedisPool.getResource();
jedis.sadd(key, members);
if (jedis != null) {
jedis.close();
}
}
public void srem(String key, String member){
if (null == jedisPool || jedisPool.isClosed()) {
initial(properties);
}
Jedis jedis = null;
jedis = jedisPool.getResource();
jedis.srem(key, member);
if (jedis != null) {
jedis.close();
}
}
public Set<String> smembers(String key){
if (null == jedisPool || jedisPool.isClosed()) {
initial(properties);
}
Jedis jedis = null;
if (jedis == null) {
jedis = jedisPool.getResource();
}
Set<String> result = jedis.smembers(key);
if (jedis != null) {
jedis.close();
}
return result;
}
public boolean sismember(String key, String member){
if (null == jedisPool || jedisPool.isClosed()) {
initial(properties);
}
Jedis jedis = null;
jedis = jedisPool.getResource();
boolean result = jedis.sismember(key, member);
if (jedis != null) {
jedis.close();
}
return result;
}
public void append(String key, String value){
if (null == jedisPool || jedisPool.isClosed()) {
initial(properties);
}
Jedis jedis = null;
jedis = jedisPool.getResource();
if (!jedis.exists(key)) { //new key
jedis.set(key, value);
}else {
jedis.append(key, APPEND_SYMBOL + value);
}
if (jedis != null) {
jedis.close();
}
}
public boolean isClose()throws Exception{
return jedisPool.isClosed();
}
public void close()throws Exception{
if (!jedisPool.isClosed()) {
jedisPool.close();
}
}
public Jedis getJedis(){
return jedisPool.getResource();
}
public Pipeline pipelined(){
Jedis jedis = null;
if (jedis == null) {
jedis = jedisPool.getResource();
}
Pipeline pipeline = jedis.pipelined();
return pipeline;
}
public void lpush(String key, String value){
Jedis jedis = null;
if (jedis == null) {
jedis = jedisPool.getResource();
}
jedis.lpush(key, value);
if (jedis != null) {
jedis.close();
}
}
public String lpop(String key){
Jedis jedis = null;
if (jedis == null) {
jedis = jedisPool.getResource();
}
String value = jedis.lpop(key);
if (jedis.isConnected()) {
jedis.close();
}
return value;
}
/**
* ZREMRANGEBYRANK key start stop
* 移除有序集 key 中,指定排名(rank)区间内的所有成员。
* 区间分别以下标参数 start 和 stop 指出,包含 start 和 stop 在内。
* 下标参数 start 和 stop 都以 0 为底,也就是说,以 0 表示有序集第一个成员,以 1 表示有序集第二个成员,以此类推。
* 你也可以使用负数下标,以 -1 表示最后一个成员, -2 表示倒数第二个成员,以此类推。
*/
public void zremrangebyrank(String setKey, long start, long stop) {
Jedis jedis = null;
jedis = jedisPool.getResource();
jedis.zremrangeByRank(setKey, start, stop);
if (jedis.isConnected()) {
jedis.close();
}
}
/**
* ZRANGE key start stop [WITHSCORES]
* 返回有序集 key 中,指定区间内的成员。
* 其中成员的位置按 score 值递增(从小到大)来排序。
* 具有相同 score 值的成员按字典序(lexicographical order )来排列。
* 如果你需要成员按 score 值递减(从大到小)来排列,请使用 ZREVRANGE 命令。
* 下标参数 start 和 stop 都以 0 为底,也就是说,以 0 表示有序集第一个成员,以 1 表示有序集第二个成员,以此类推。
* 你也可以使用负数下标,以 -1 表示最后一个成员, -2 表示倒数第二个成员,以此类推。
* 超出范围的下标并不会引起错误。
* 比如说,当 start 的值比有序集的最大下标还要大,或是 start > stop 时, ZRANGE 命令只是简单地返回一个空列表。
* 另一方面,假如 stop 参数的值比有序集的最大下标还要大,那么 Redis 将 stop 当作最大下标来处理。
* 可以通过使用 WITHSCORES 选项,来让成员和它的 score 值一并返回,返回列表以 value1,score1, ...,
* valueN,scoreN 的格式表示。
* 客户端库可能会返回一些更复杂的数据类型,比如数组、元组等。
* ZREVRANGE key start stop [WITHSCORES]
* 返回有序集 key 中,指定区间内的成员。
* 其中成员的位置按 score 值递减(从大到小)来排列。
* 具有相同 score 值的成员按字典序的逆序(reverse lexicographical order)排列。
* 除了成员按 score 值递减的次序排列这一点外, ZREVRANGE 命令的其他方面和 ZRANGE 命令一样。
*/
public Set<Tuple> zrange(String setKey, long start, long stop) {
Jedis jedis = null;
jedis = jedisPool.getResource();
Set<Tuple> tuples = jedis.zrangeWithScores(setKey, start, stop);
if (null != jedis) {
jedis.close();
}
return tuples;
}
public Set<String> zrevrange(String setKey, long start, long stop){
Jedis jedis = null;
jedis = jedisPool.getResource();
Set<String> resultSet = jedis.zrevrange(setKey, start, stop);
if (null != jedis) {
jedis.close();
}
return resultSet;
}
/**
* ZADD key score member [[score member] [score member] ...]
* 将一个或多个 member 元素及其 score 值加入到有序集 key 当中。
* 如果某个 member 已经是有序集的成员,那么更新这个 member 的 score 值,
* 并通过重新插入这个 member 元素,来保证该 member 在正确的位置上。
* score 值可以是整数值或双精度浮点数。
* 如果 key 不存在,则创建一个空的有序集并执行 ZADD 操作。
* 当 key 存在但不是有序集类型时,返回一个错误。
*/
public void zadd(String setKey, Map<String, Double> sourceMember) {
Jedis jedis = null;
jedis = jedisPool.getResource();
jedis.zadd(setKey, sourceMember);
if (null != jedis) {
jedis.close();
}
}
public void zadd(String setKey, double score, String member){
Jedis jedis = null;
jedis = jedisPool.getResource();
jedis.zadd(setKey, score, member);
if (null != jedis) {
jedis.close();
}
}
/**
* ZCARD key
* 返回有序集 key 的基数。
*/
public long zcard(String setKey) {
Jedis jedis = null;
jedis = jedisPool.getResource();
long value = jedis.zcard(setKey);
if (null != jedis) {
jedis.close();
}
return value;
}
/**
* ZRANK key member
* 返回有序集 key 中成员 member 的排名。其中有序集成员按 score 值递增(从小到大)顺序排列。
* 排名以 0 为底,也就是说, score 值最小的成员排名为 0 。
* 使用 ZREVRANK 命令可以获得成员按 score 值递减(从大到小)排列的排名。
* ZREVRANK key member
* 返回有序集 key 中成员 member 的排名。其中有序集成员按 score 值递减(从大到小)排序。
* 排名以 0 为底,也就是说, score 值最大的成员排名为 0 。
* 使用 ZRANK 命令可以获得成员按 score 值递增(从小到大)排列的排名。
*/
public long zrank(String setKey, String itemKey) {
Jedis jedis = null;
jedis = jedisPool.getResource();
long rank = jedis.zrank(setKey, itemKey);
if (null != jedis) {
jedis.close();
}
return rank;
}
/**
* ZREM key member [member ...]
* 移除有序集 key 中的一个或多个成员,不存在的成员将被忽略。
* 当 key 存在但不是有序集类型时,返回一个错误。
*/
public void ZREM(String setKey) {
Jedis jedis = null;
jedis = jedisPool.getResource();
jedis.zrem(setKey, "layman72.0", "layman77.0");
if (null != jedis) {
jedis.close();
}
}
/**
* ZSCORE key member
* 返回有序集 key 中,成员 member 的 score 值。
* 如果 member 元素不是有序集 key 的成员,或 key 不存在,返回 nil 。
*/
public Double ZSCORE(String setKey, String itemKey) {
Jedis jedis = null;
jedis = jedisPool.getResource();
Double score = jedis.zscore(setKey, itemKey);
if (null != jedis) {
jedis.close();
}
return score;
}
/**
* ZINCRBY key increment member
* 为有序集 key 的成员 member 的 score 值加上增量 increment 。
* 可以通过传递一个负数值 increment ,让 score 减去相应的值,比如 ZINCRBY key -5 member ,就是让 member 的 score 值减去 5 。
* 当 key 不存在,或 member 不是 key 的成员时, ZINCRBY key increment member 等同于 ZADD key increment member 。
* 当 key 不是有序集类型时,返回一个错误。
* score 值可以是整数值或双精度浮点数。
*/
public void ZINCRBY(String setKey, double increment, String member) {
Jedis jedis = null;
jedis = jedisPool.getResource();
jedis.zincrby(setKey, increment, member);
if (null != jedis) {
jedis.close();
}
}
public ScanResult<Tuple> ZSCAN(String setKey, String cursor, int itemCount){
Jedis jedis = null;
jedis = jedisPool.getResource();
ScanParams scanParams = new ScanParams();
scanParams.count(itemCount * 2);
ScanResult<Tuple> result = jedis.zscan(setKey, cursor, scanParams);
jedis.close();
return result;
}
private static int getRandomInt() {
return new Random().nextInt(100);
}
public static void main(String[] args) throws Exception{
String conf = "E:/conf_test/configure/client/client_storeservice_conf.properties";
Properties properties = PropertiesFileUtil.load(conf);
RedisClient redisClient = new RedisClient(properties);
// redisClient.sadd("10", "michael");
// redisClient.sadd("10", "leo");
// redisClient.sadd("10", "tom");
// redisClient.sadd("10", "jame");
// redisClient.sadd("5", "jacke");
// redisClient.sadd("6", "boys");
// String[] list = {"test10","test12", "test5", "test6"};
//
// redisClient.sadd("10", list);
//
// redisClient.expire("10", 120);
// redisClient.set("name", "michael");
//
// redisClient.append("name", "shentu");
// for (String string : redisClient.smembers("topic_2")) {
// System.out.println(string);
// }
// for (int i = 0; i < 50; i++) {
// System.out.println("topic : " + i + " size: " + redisClient.smembers("topic_" + i).size());
// // redisClient.del("topic_" + i);
// }
// String setKey = "sorted_set";
// String item = "layman_";
// Map<String, Double> sourceMember = new HashMap<String, Double>();
// for (int i = 0; i < 20; i++) {
// double score = getRandomInt();
// sourceMember.put(item + score, score);
// System.out.println("" + item + score + " : " + score);
// }
// redisClient.zadd(setKey, sourceMember);
// System.out.println("test");
// String setKey = "zq<KEY>";
// Set<Tuple> tuples = redisClient.zrange(setKey, 0, -1);
// System.out.println(tuples.size());
// for (Tuple tuple : tuples) {
// System.out.println(tuple.getElement() + " " + tuple.getScore());
// }
//
// redisClient.zremrangebyrank(setKey, 0, -51);
// Set<String> resultSet = redisClient.zrevrange(setKey, 0, -1);
//
// for (String result : resultSet) {
// System.out.println(result);
// }
// redisClient.lpush("uid1_test", "1111");
// redisClient.lpush("uid1_test", "2222");
// redisClient.lpush("uid1_test", "3333");
//
// System.out.println();
//
// System.out.println(redisClient.lpop("zqsv_on_401_388635"));
// System.out.println(redisClient.lpop("zqsv_on_401_388635"));
// redisClient.close();
// redisClient.set("recommended_" + "test1" + "_" + 1222, "1");
// redisClient.expire("recommended_" + "test1" + "_" + 1222, 14400);
// System.out.println(redisClient.get("recommended_" + "test1" + "_" + 1222));
// for (int i = 0; i < 15; i++) {
// System.out.println(redisClient.lpop("zqsv_on_401_212013"));
// }
// redisClient.sadd("set_test1", "abc");
// redisClient.sadd("set_test1", "234");
// redisClient.sadd("set_test1", "edf");
//
// Set<String> list = redisClient.smembers("set_test1");
//
// for (String string : list) {
// System.out.println(string);
// }
//
// redisClient.del("set_test1");
//
// System.out.println(redisClient.smembers("set_test1"));
//
// Set<String> set = new HashSet<>();
// set.add("1111111111");
// set.add("2222222222");
// set.add("3333333333");
// redisClient.sadd("set_test1", "1111111111");
// redisClient.sadd("set_test1", "2222222222");
//
// System.out.println(redisClient.smembers("set_test1"));
//
// redisClient.sadd("set_test1", "3333333333");
// System.out.println(redisClient.smembers("set_test1"));
java.text.DecimalFormat decimalFormat =new java.text.DecimalFormat("#.000");
String cursor = ScanParams.SCAN_POINTER_START;
ScanResult<Tuple> result = redisClient.ZSCAN("zqsv_303_10540", cursor, 50);
System.out.println("result:");
List<Tuple> list = result.getResult();
System.out.println(list.size());
redisClient.close();
}
}
<file_sep>/src/main/java/com/zbcmdata/flink/examples/streaming/window/StreamingProcessTimeWindowWatermark.java
package com.zbcmdata.flink.examples.streaming.window;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.AssignerWithPeriodicWatermarks;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer08;
import org.apache.flink.streaming.util.serialization.SimpleStringSchema;
import org.apache.flink.util.Collector;
import com.alibaba.fastjson.JSONObject;
import com.zbcmdata.flink.common.Constant;
import com.zbcmdata.flink.util.PropertiesFileUtil;
public class StreamingProcessTimeWindowWatermark {
public static void main(String[] args) throws Exception {
final ParameterTool parameterTool = ParameterTool.fromArgs(args);
//获取运行环境
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.getConfig().disableSysoutLogging();
env.getConfig().setRestartStrategy(RestartStrategies.fixedDelayRestart(4, 10000));
env.enableCheckpointing(5000); // create a checkpoint every 5 seconds
env.getConfig().setGlobalJobParameters(parameterTool); // make parameters available in the web interface
//设置并行度为1,默认并行度是当前机器的cpu数量
env.setParallelism(1);
//Properties kafkaProperties = PropertiesFileUtil.load("classpath:configure/client/consumer.properties");
Properties kafkaProperties = PropertiesFileUtil.load(Constant.CONFIGURE_DIR + File.separator +
"configure/client/consumer.properties");
kafkaProperties.setProperty("group.id", "zhanqi_recommend_group_test2");
kafkaProperties.setProperty("topic", "zhanqi_shortvedio_clientLog_windowprocess_test2");
kafkaProperties.put("auto.offset.reset", "smallest");
kafkaProperties.put("auto.commit.enable", "true");
DataStream<String> messageStream = env.addSource(new FlinkKafkaConsumer08<>(
kafkaProperties.getProperty("topic"),
new SimpleStringSchema(),
kafkaProperties));
//解析输入的数据
DataStream<Tuple2<String, String>> inputMapStream = messageStream.map(new MapFunction<String, Tuple2<String, String>>() {
@Override
public Tuple2<String, String> map(String value) throws Exception {
JSONObject jsonObject = JSONObject.parseObject(value);
String key = jsonObject.getString("uid");
System.out.println("jsonstring: " + value);
return new Tuple2<>(key, value);
}
});
//按照消息的EventTime分配窗口,和调用TimeWindow效果一样
DataStream<String> window = inputMapStream.keyBy(0)
.window(TumblingProcessingTimeWindows.of(Time.seconds(10)))
.apply(new WindowFunction<Tuple2<String, String>,
String,
Tuple,
TimeWindow>() {
private static final long serialVersionUID = 1L;
/**
* 对window内的数据进行统计,获取实时计算结果
* @param tuple
* @param window
* @param input
* @param out
* @throws Exception
*/
@Override
public void apply(Tuple tuple,
TimeWindow window,
Iterable<Tuple2<String, String>> input,
Collector<String> out) throws Exception {
String key = tuple.toString();
List<String> arrarList = new ArrayList<String>();
Iterator<Tuple2<String, String>> it = input.iterator();
Map<String, Integer> statisticMap = new HashMap<>();
String uid = null;
while (it.hasNext()) {
Tuple2<String, String> next = it.next();
JSONObject jsonObject = JSONObject.parseObject(next.f1);
String vid = jsonObject.getIntValue("vid") + "";
uid = jsonObject.getString("uid");
if (!statisticMap.containsKey(vid)) {
statisticMap.put(vid, 1);
}else {
int score = statisticMap.get(vid);
score += 1;
statisticMap.put(vid, score);
}
arrarList.add(next.f1);
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String result = "window key: "+ key + ", uid: " + uid + "\n 触发窗内数据个数 : "
+ arrarList.size()
+ "\n 触发窗起始数据: " + JSONObject.parseObject(arrarList.get(0)).getString("timeStamp")
+ "\n 触发窗最后(可能是延时)数据:"
+ JSONObject.parseObject(arrarList.get(arrarList.size() - 1)).getString("timeStamp")
+ "\n 实际窗起始和结束时间: "
+ sdf.format(window.getStart()) + "《----》" + sdf.format((window.getEnd())) + " \n";
StringBuffer sb = new StringBuffer();
sb.append("uid: " + uid + ", video score list: " + " \n");
for(Map.Entry<String, Integer> entry : statisticMap.entrySet()){
sb.append("vid: " + entry.getKey() + ", score: " + entry.getValue() + " \n");
}
out.collect(result + sb.toString());
}
});
//测试-把结果打印到控制台即可
window.print();
//注意:因为flink是懒加载的,所以必须调用execute方法,上面的代码才会执行
env.execute("process-time window streaming");
}
}
<file_sep>/src/main/java/com/zbcmdata/flink/FlinkApplications/model/similarity/VideoSimilarity.java
package com.zbcmdata.flink.FlinkApplications.model.similarity;
import com.zbcmdata.flink.FlinkApplications.bean.ItemInfo;
import com.zbcmdata.flink.common.Constant;
public class VideoSimilarity {
public static double NLPFeatureSimilarity(ItemInfo base, ItemInfo candidate){
double content_similarity = KeyWordsSimilarity.getKWListSimilarRatioWithScore(
base.getTitleWords() + Constant.KEYWORD_MERGE_MARK + base.getSummaryWords(),
candidate.getTitleWords() + Constant.KEYWORD_MERGE_MARK + candidate.getSummaryWords());
double tag_similarity = KeyWordsSimilarity.getKWListSimilarRatioWithScore(
base.getTagFeature(), candidate.getTagFeature());
double similarity = tag_similarity + content_similarity;
return similarity;
}
}
<file_sep>/src/main/java/com/zbcmdata/flink/service/dao/HbaseDao.java
package com.zbcmdata.flink.service.dao;
import java.util.List;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.HTablePool;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
public interface HbaseDao {
public HTablePool getHTablePool();
public int[] saveIndex(String table, List<Put> datas) throws Exception;
public Result queryOne(String table, String key)throws Exception;
public int[] delete(String table, List<Delete> datas) throws Exception;
public int delete(String table, Delete data) throws Exception;
public boolean exists(String table, String key) throws Exception;
public int update(String table, Put data, String update) throws Exception;
public void saveOneData(String tableName, Put put)throws Exception;
public Result getOneData(String tableName, String rowkey)throws Exception;
public void saveDataList(String tableName, List<Put> datas)throws Exception;
public List<Result> getAllData(String tableName)throws Exception;
}
<file_sep>/src/main/java/com/zbcmdata/flink/FlinkApplications/functions/sink/hbase/HBaseClientLogSink.java
package com.zbcmdata.flink.FlinkApplications.functions.sink.hbase;
import java.io.File;
import java.io.FileReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSONObject;
import com.zbcmdata.flink.common.Constant;
import com.zbcmdata.flink.service.dao.impl.HBaseDaoImpl;
import com.zbcmdata.flink.util.DateUtil;
import com.zbcmdata.flink.util.HbaseUtil;
public class HBaseClientLogSink extends RichSinkFunction<String>{
private static Logger LOGGER = Logger.getLogger(HBaseClientLogSink.class);
/**
*
*/
private static final long serialVersionUID = 1564970258855083046L;
private static HBaseDaoImpl hBaseDao = null;
private static String format = "yyyy-MM-dd HH:mm:ss";
private static DateFormat df = new SimpleDateFormat(format);
private static final String file_separator = Constant.FILE_SEPARATOR;
private static String toString(Object jsonValue){
if (null == jsonValue) {
return "";
}else {
return String.valueOf(jsonValue);
}
}
private static int getActionTypeCode(JSONObject jsonObject){
int code = -1;
String actionType = jsonObject.getString("type");
if (actionType.equals("click")) {
code = Constant.ACTION_CLICK;
}else if (actionType.equals("like")) {
code = Constant.ACTION_LIKE;
}else if (actionType.equals("comment")) {
code = Constant.ACTION_COMMENT;
}else if ("1".equals( toString(jsonObject.get("share")))) {
code = Constant.ACTION_SHARE;
}else if ("1".equals(toString(jsonObject.get("play")))) {
code = Constant.ACTION_PLAY;
}
return code;
}
@Override
public void invoke(String value) throws Exception {
// TODO Auto-generated method stub
JSONObject jsonObject = JSONObject.parseObject(value);
String uid = toString(jsonObject.get("uid"));
String vid = toString(jsonObject.get("vid"));
String type = toString(jsonObject.get("type"));
String result = toString(jsonObject.get("value"));
String playingTime = toString(jsonObject.get("playing_time"));
String videoSecond = toString(jsonObject.get("video_second"));
String actionTime = toString(jsonObject.get("server_date")); //"yyyy-MM-dd hh:mm:ss"
String timeStamp = toString(jsonObject.get("server_time")); //time stamp
int dayId = Integer.parseInt(jsonObject.getString("dayId"));
int actionCode = getActionTypeCode(jsonObject);
//index table rowkey: dayid_uid_vid_
String clientLogId_str = uid + file_separator +
actionCode + file_separator +
vid + file_separator +
timeStamp;
String rowkey = dayId + file_separator + clientLogId_str;
//put for clientLog index table
Put put = new Put(Bytes.toBytes(rowkey));
put.add(Bytes.toBytes("f1"), Bytes.toBytes("type"), Bytes.toBytes(type));
put.add(Bytes.toBytes("f1"), Bytes.toBytes("result"), Bytes.toBytes(result));
put.add(Bytes.toBytes("f1"), Bytes.toBytes("actionTime"), Bytes.toBytes(actionTime));
if (type.equals("play")) {
put.add(Bytes.toBytes("f1"), Bytes.toBytes("playingTime"), Bytes.toBytes(playingTime));
put.add(Bytes.toBytes("f1"), Bytes.toBytes("videoSecond"), Bytes.toBytes(videoSecond));
}
String logMessage = null;
try {
hBaseDao.saveOneData(Constant.HBASE_ZHANQI_VIDEOREC_CLIENTLOG_INDEX, put);
logMessage = "successed save log index recored into table: " +
Constant.HBASE_ZHANQI_VIDEOREC_CLIENTLOG_INDEX +
", rowkey: " + rowkey;
LOGGER.info(logMessage);
} catch (Exception e) {
// TODO: handle exception
logMessage = "failed to save log index recored into table: " +
Constant.HBASE_ZHANQI_VIDEOREC_CLIENTLOG_INDEX +
", rowkey: " + rowkey;
LOGGER.error(logMessage);
}
}
@Override
public void open(Configuration configuration)throws Exception{
hBaseDao = new HBaseDaoImpl();
LOGGER.info("create hbase connection server");
super.open(configuration);
}
@Override
public void close()throws Exception{
hBaseDao.close();
LOGGER.info("close hbase connection server");
}
}
<file_sep>/src/main/java/com/zbcmdata/flink/FlinkApplications/streaming/onlineRecommend/v2/CandidateItemScoreStatisticFunction.java
package com.zbcmdata.flink.FlinkApplications.streaming.onlineRecommend.v2;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.util.Collector;
import redis.clients.jedis.Tuple;
import com.alibaba.fastjson.JSONObject;
import com.zbcmdata.flink.common.Constant;
import com.zbcmdata.flink.service.redis.RedisClient;
import com.zbcmdata.flink.util.LogUtil;
public class CandidateItemScoreStatisticFunction extends RichFlatMapFunction<Tuple2<String, String>,
Tuple2<String, String>>
{
private static final Log LOGGER = LogFactory.getLog(CandidateItemScoreStatisticFunction.class);
private RedisClient redisClient = null;
@Override
public void flatMap(Tuple2<String, String> input, Collector<Tuple2<String, String>> out)
throws Exception {
// TODO Auto-generated method stub
JSONObject recScoreMap = new JSONObject();
String uid = null;
Set<String> typeSet = new HashSet<String>();
try {
JSONObject object = JSONObject.parseObject(input.f1);
uid = object.getString("user");
String recScoreListStr = object.getString("recScoreList");
if (recScoreListStr.equals("")) {
System.out.println(LogUtil.logTime() + "--------->VideoScoreStatisticFunction, recScoreList is NULL!" + "\n");
}else {
List<String> recScoreList = Arrays.asList(recScoreListStr.split(","));
for (String value : recScoreList) {
String[] values = value.split(":");
String key = values[0];
String type = key.split("_")[0];
String itemId = key.split("_")[1];
if (isToFilter(uid, itemId, type)) {
continue;
}
typeSet.add(type);
double similarity = Double.parseDouble(values[1]);
//不同板块创建各自的推荐列表
if (!recScoreMap.containsKey(type)) {
JSONObject valueDict = new JSONObject();
valueDict.put(itemId, similarity);
recScoreMap.put(type, valueDict);
}else {
JSONObject valueDict = recScoreMap.getJSONObject(type);
if (!valueDict.containsKey(itemId)) {
valueDict.put(itemId, similarity);
}else {
double w = (Double)valueDict.get(itemId);
w += similarity;
valueDict.put(itemId, w);
}
recScoreMap.put(type, valueDict);
}
}
}
System.out.println(LogUtil.logTime() + "CandidateItemsScoreStatisticFunction collect out:");
for(String type : typeSet){
System.out.println(" type: "+ type + ", recList size: " + recScoreMap.getJSONObject(type).size());
}
System.out.println("candidate items for uid:" + uid + "\n");
out.collect(new Tuple2<>(uid, recScoreMap.toString()));
} catch (Exception e) {
// TODO: handle exception
System.out.println(LogUtil.logTime() + "ScoreStatisticFunction Exception, input ----->" + input + "\n");
e.printStackTrace();
}
}
private boolean isToFilter(String uid, String candidate, String type){
boolean toFilter = false;
String watchedKey = Constant.ZQRSJ_CUSTOM_ID + "_" + type + "_watched_" + uid + "_" + candidate;
String recommendedKey = Constant.ZQRSJ_CUSTOM_ID + "_" + type + "_recommended_" + uid + "_" + candidate;
if (redisClient.exists(watchedKey)) {
System.out.println(LogUtil.logTime() + watchedKey + " is to filtered!");
return true;
}
if (redisClient.exists(recommendedKey)) {
System.out.println(LogUtil.logTime() + recommendedKey + " is to filtered!");
return true;
}
return toFilter;
}
@Override
public void open(Configuration configuration)throws Exception{
redisClient = new RedisClient();
LOGGER.info("CandidateVideoScoreStatisticFunction create Redis Client Connection!");
super.open(configuration);
}
@Override
public void close()throws Exception{
redisClient.close();
LOGGER.info("CandidateVideoScoreStatisticFunction close Redis Client Connection!");
}
}
<file_sep>/src/main/java/com/zbcmdata/flink/FlinkApplications/bean/ItemInfo.java
package com.zbcmdata.flink.FlinkApplications.bean;
import java.io.Serializable;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.zbcmdata.flink.util.StringUtil;
public class ItemInfo implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private int itemId;
private String title;
private String summary;
private String summaryWords;
private String titleWords;
private String publishTime;
private String tag1;
private String tag2;
private String tagFeature;
private int type;
private int is_check_time;
public void setItemId(int itemId){
this.itemId = itemId;
}
public int getItemId(){
return this.itemId;
}
public void setTitle(String title){
this.title = title;
}
public String getTitle(){
return this.title;
}
public void setSummary(String summary){
this.summary = summary;
}
public String getSummary(){
return this.summary;
}
public void setSummaryWords(String summaryWords){
this.summaryWords = summaryWords;
}
public String getSummaryWords(){
return this.summaryWords;
}
public void setTitleWords(String titleWords){
this.titleWords = titleWords;
}
public String getTitleWords(){
return this.titleWords;
}
public void setPublishTime(String statDate){
this.publishTime = statDate;
}
public String getPublishTime(){
return this.publishTime;
}
public void setTag1(String tag){
this.tag1 = tag;
}
public String getTag1(){
return this.tag1;
}
public void setTag2(String tag){
this.tag2 = tag;
}
public String getTag2(){
return this.tag2;
}
public void setTagFeature(String vec){
this.tagFeature = vec;
}
public String getTagFeature(){
return this.tagFeature;
}
public void setType(int type){
this.type = type;
}
public int getType(){
return this.type;
}
public void setIsCheckTime(int is_check_time){
this.is_check_time = is_check_time;
}
public int getIsCheckTime(){
return this.is_check_time;
}
/**
* kafka队列中传递过来的原始日志数据
*
* @throws JSONException
* */
/**
* @param jsonString
* @return ItemInfo
* @throws JSONException
*/
public static ItemInfo parseFromJson(String jsonString)throws JSONException{
JSONObject object = JSONObject.parseObject(jsonString);
ItemInfo itemInfo = new ItemInfo();
itemInfo.setItemId(object.getIntValue("item_id"));
if (object.containsKey("tag1")) {
itemInfo.setTag1(object.getString("tag1"));
}else {
itemInfo.setTag1("");
}
if (object.containsKey("tag2")) {
itemInfo.setTag2(object.getString("tag2"));
}else {
itemInfo.setTag2("");
}
if (object.containsKey("publish_time")) {
itemInfo.setPublishTime(object.getString("publish_time"));
}else {
itemInfo.setPublishTime("");
}
if (object.containsKey("titleWords")) {
itemInfo.setTitleWords(object.getString("titleWords"));
}else {
itemInfo.setTitleWords("");
}
if (object.containsKey("description")) {
itemInfo.setSummary(object.getString("description"));
}else {
itemInfo.setSummary("");
}
if (object.containsKey("summaryWords")) {
itemInfo.setSummaryWords(object.getString("summaryWords"));
}else {
itemInfo.setSummaryWords("");
}
if (object.containsKey("title")) {
itemInfo.setTitle(object.getString("title"));
}else {
itemInfo.setTitle("");
}
if (object.containsKey("tagFeature")) {
itemInfo.setTagFeature(object.getString("tagFeature"));
}else {
itemInfo.setTagFeature("");
}
if (object.containsKey("type")) {
itemInfo.setType(object.getIntValue("type"));
} else {
itemInfo.setType(-1);
}
if (object.containsKey("is_check_time")) {
itemInfo.setIsCheckTime(object.getIntValue("is_check_time"));
} else {
itemInfo.setIsCheckTime(-1);
}
return itemInfo;
}
}
<file_sep>/src/resources/product/configure/client/producer.properties
metadata.broker.list=10.8.26.27:9092,10.8.26.28:9092,10.8.26.29:9092
producer.type=async
request.required.acks=1
serializer.class=kafka.serializer.StringEncoder
result.queue=test-result-topic1<file_sep>/README.md
-----------------------------------------------------------------------------------
1. hanlp生成的jar如何安装到第三方应用系统中:
本地maven安装命令:
cmd定位到jar所在的windows目录下:执行
mvn install:install-file -DgroupId=com.hankcs -DartifactId=hanlp -Dversion=1.7.2 -Dpackaging=jar -Dfile=hanlp-1.7.2.jar
mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=172.16.31.10 -Dpackaging=jar -Dfile=ojdbc6-12.1.0.1.jar
mvn install:install-file -DgroupId=jdk.tools -DartifactId=jdk.tools -Dversion=1.6 -Dpackaging=jar -Dfile=jdk.tools-1.6.jar
2.词库更新的方法以及如何更新到linux集群中去:
2.1 更新自定义词库与停用词库后, 需要删除data\dictionary\custom下的CustomDictionary.txt.bin文件与data\dictionary下的stopwords.txt.bin文件,同时运行任何一个demo,重新生成这两个bin文件并会加载到本地的data相关目录中去,mode下的所有bin目录
不需要更新,如果需要更新,与hanlp官网去下载更新
2.2 本地的data词库更新后,将data同步到linux集群中,替换掉老的版本文件,并在整个集群上进行同步。
<file_sep>/src/main/java/com/zbcmdata/flink/FlinkApplications/streaming/elasticsearch/requestFailureHandler/FlinkActionRequestFailureHandler.java
package com.zbcmdata.flink.FlinkApplications.streaming.elasticsearch.requestFailureHandler;
import java.util.Map;
import org.apache.flink.streaming.connectors.elasticsearch.ActionRequestFailureHandler;
import org.apache.flink.streaming.connectors.elasticsearch.RequestIndexer;
import org.apache.flink.util.ExceptionUtils;
import org.apache.log4j.Logger;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException;
import com.zbcmdata.flink.FlinkApplications.streaming.elasticsearch.OnlineESIndexProcess;
public class FlinkActionRequestFailureHandler implements ActionRequestFailureHandler{
private static final Logger LOGGER = Logger.getLogger(FlinkActionRequestFailureHandler.class);
@Override
public void onFailure(ActionRequest action, Throwable failure, int restStatusCode,
RequestIndexer indexer) throws Throwable {
// TODO Auto-generated method stub
if (ExceptionUtils.findThrowable(failure, EsRejectedExecutionException.class).isPresent()) {
// 将失败请求继续加入队列,后续进行重试写入
indexer.add(action);
} else if (ExceptionUtils.findThrowable(failure, ElasticsearchParseException.class).isPresent()) {
// 添加自定义的处理逻辑
IndexRequest indexAction = (IndexRequest)action;
String index = indexAction.index();
String type = indexAction.type();
String id = indexAction.id();
Map<String, Object> json = indexAction.sourceAsMap();
LOGGER.error("index name: " + index + ", index type: "
+ type + ", id: " + id + ", json Message: " + json.toString());
} else {
throw failure;
}
}
}
<file_sep>/src/main/java/com/zbcmdata/flink/FlinkApplications/model/similarity/KeyWordsSimilarity.java
package com.zbcmdata.flink.FlinkApplications.model.similarity;
import java.util.Arrays;
import org.jcodings.transcode.specific.From_GB18030_Transcoder;
import com.zbcmdata.flink.common.Constant;
public class KeyWordsSimilarity {
private static int computMatchNum(String[] a, String[] b)
{
int rlt = 0;
int len = b.length;
for(int i=0; i<len; i++)
{
rlt += binarySearch(a, b[i]);
}
return rlt;
}
private static int binarySearch(String[] a, String b)
{
int left = 0;
int right = a.length-1;
while(left <= right)
{
int middle = left + ((right-left)>>1);
int cmp = a[middle].compareTo(b);
if(cmp > 0)
{
right = middle - 1;
}
else if(cmp < 0)
{
left = middle + 1;
}
else
{
return 1;
}
}
return 0;
}
private static boolean isKeywordsSimilar(String[] a, String[] b)
{
if(getKeywordsSimilarRatio(a, b) > Constant.KEYWORDS_SIMILAR_THRESHOLD)
{
return true;
}
return false;
}
private static double getKeywordsSimilarRatio(String[] a, String[] b)
{
if(a.equals("null") || b.equals("null") || a.equals("") || b.equals(""))
{
return 0;
}
int len_a = a.length;
int len_b = b.length;
if(0 == len_a || 0 == len_b)
{
return 0;
}
return 1.0f*computMatchNum(a, b)/Math.max(len_a, len_b);
}
public static double getKWListSimilarRatio(String a, String b)
{
if(a.equals("null") || b.equals("null") || a.equals("") || b.equals(""))
{
return 0;
}
String[] s1 = a.split(Constant.KEYWORD_SPACE_MARK);
String[] s2 = b.split(Constant.KEYWORD_SPACE_MARK);
return getKeywordsSimilarRatio(s1, s2);
}
public static double getKWListSimilarRatioWithScore(String a, String b)
{
if(a.equals("null") || b.equals("null") || a.equals("") || b.equals(""))
{
return 0;
}
String[] s1 = a.split(Constant.KEYWORD_SPACE_MARK);
String[] s2 = b.split(Constant.KEYWORD_SPACE_MARK);
String[] compare_s1 = new String[s1.length];
String[] compare_s2 = new String[s2.length];
for (int i = 0; i < compare_s1.length; i++) {
String[] item = s1[i].split(":");
String word = item[0];
compare_s1[i] = word;
}
for (int i = 0; i < compare_s2.length; i++) {
String[] item = s2[i].split(":");
String word = item[0];
compare_s2[i] = word;
}
return getKeywordsSimilarRatio(compare_s1, compare_s2);
}
public static boolean isTwoKeywordListSimilar(String a, String b)
{
if(a.equals("null") || b.equals("null") || a.equals("") || b.equals(""))
{
return false;
}
String[] s1 = a.split(Constant.KEYWORD_SPACE_MARK);
String[] s2 = b.split(Constant.KEYWORD_SPACE_MARK);
return isKeywordsSimilar(s1, s2);
}
public static void main(String[] args) {
String key1 = "d";
String key2 = "";
String[] s1 = key1.split("\\|");
String[] s2 = key2.split("\\|");
Arrays.sort(s1);
Arrays.sort(s2);
for(int i=0; i< s1.length; i++)
{
System.out.print(s1[i] + " ");
}
System.out.println();
for(int i=0; i< s2.length; i++)
{
System.out.print(s2[i] + " ");
}
System.out.println();
//s1 = null;
//s2 = null;
Long startTime = System.nanoTime();
System.out.println(KeyWordsSimilarity.getKeywordsSimilarRatio(s1, s2));
Long endTime = System.nanoTime();
System.out.println("---Totle time is " + (endTime - startTime) + " ns---");
}
}
<file_sep>/src/resources/test/configure/client/producer.properties
metadata.broker.list=10.8.26.23:9092,10.8.26.24:9092,10.8.26.25:9092
producer.type=async
request.required.acks=1
serializer.class=kafka.serializer.StringEncoder
result.queue=streaming-flink-test1<file_sep>/src/main/java/com/zbcmdata/flink/FlinkApplications/functions/sink/redis/RedisUserOnlineRecommendSink.java
package com.zbcmdata.flink.FlinkApplications.functions.sink.redis;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import com.zbcmdata.flink.FlinkApplications.model.recommend.user.UserOnLineRecommend;
import com.zbcmdata.flink.FlinkApplications.model.recommend.video.VideoOnLineRecommend;
public class RedisUserOnlineRecommendSink extends RichSinkFunction<String>{
private static UserOnLineRecommend userOnLineRecommend = null;
private static final Log LOGGER = LogFactory.getLog(RedisUserOnlineRecommendSink.class);
@Override
public void invoke(String value) throws Exception {
// TODO Auto-generated method stub
//boolean result = userOnLineRecommend.getRecommendVideos(value);
}
@Override
public void open(Configuration configuration)throws Exception{
userOnLineRecommend = new UserOnLineRecommend();
super.open(configuration);
}
@Override
public void close()throws Exception{
userOnLineRecommend.close();
LOGGER.info("close mysql connection server");
}
}
<file_sep>/src/main/java/com/zbcmdata/flink/examples/streaming/window/AsyncMysqlDataRequest.java
package com.zbcmdata.flink.examples.streaming.window;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Collections;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.api.java.tuple.Tuple6;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.async.ResultFuture;
import org.apache.flink.streaming.api.functions.async.RichAsyncFunction;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
public class AsyncMysqlDataRequest extends
RichAsyncFunction<Tuple3<String, String, Integer>, Tuple6<String, String, Integer, Integer, String, String>> {
private static final long serialVersionUID = 2616266924198175122L;
private transient PreparedStatement ps;
private transient Connection connection;
private transient volatile Cache<String, Tuple3<Integer, String, String>/*String*/> cityPercent;
private transient ExecutorService executorService;
@Override
public void open(Configuration parameters) throws Exception {
//初始化Mysql-Client
connection=getConnection();
ps = connection.prepareStatement("select * from test1");
//初始化线程数
executorService = Executors.newFixedThreadPool(30);
//缓存设置
cityPercent = CacheBuilder.<String, Tuple3<Integer, String, String>>newBuilder().recordStats().maximumSize(100)
.expireAfterWrite(100, TimeUnit.MINUTES)
.removalListener(
//生成环境,可以注销,这个是测试观察缓存使用
new RemovalListener<Object, Object>() {
@Override
public void onRemoval(RemovalNotification<Object, Object> notification) {
// System.out.println(notification.getKey() + "从缓存移除,原因是:" + notification.getCause());
}
}
).build();
}
@Override
public void close() throws Exception {
super.close();
// 关闭连接和释放资源
if (connection != null) {
connection.close();
}
if (ps != null) {
ps.close();
}
}
@Override
public void asyncInvoke(Tuple3<String, String, Integer> input,
ResultFuture<Tuple6<String, String, Integer, Integer, String, String>> resultFuture) throws Exception {
// Tuple2<String, String> fromToCity = input.f0;
String keyName=input.f1;
//若缓存里存在,直接从缓存里读取key
Tuple3<Integer, String, String>/*String */ value = cityPercent.getIfPresent(keyName);
/*System.out.println("##############asyn####################");
System.out.println(input);
System.out.println(keyName);
System.out.println(value);
System.out.println("##################################");*/
long size = cityPercent.size();
// System.out.println("当前缓存有:"+size+"条");
// System.out.println("当前缓存状态:"+cityPercent.stats());
if (value != null) {
// System.out.println("从缓存中获取到数据 :" + value);
System.out.println("----------------------缓存-----------");
Tuple6 te = new Tuple6<String, String, Integer, Integer, String, String>(input.f0, input.f1, input.f2,
value.f0, value.f1, value.f2);
resultFuture.complete(Collections.singleton(te));
} else {
search(input, resultFuture);
}
}
//异步去读Es表
private void search(Tuple3<String, String, Integer> input,
ResultFuture<Tuple6<String, String, Integer, Integer, String, String>> resultFuture) {
executorService.submit(() -> {
try {
// submit query
// System.out.println("submit query : " + asyncUser.getId() + "-1-" + System.currentTimeMillis());
//AsyncUser tmp = client.query1(asyncUser);
ResultSet rs = ps.executeQuery();
if (!rs.isClosed()) {
while (rs.next()){
int id = rs.getInt(1);
String name=rs.getString(2);
String number=rs.getString(3);
Tuple3<Integer, String, String> temp = new Tuple3<>(id, name, number);
// 一定要记得放回 resultFuture,不然数据全部是timeout 的
// System.out.println("从数据库中得到数据 :" + temp);
System.out.println("----------------------数据库-----------");
cityPercent.put(name, temp);
Tuple6 te = new Tuple6<String, String, Integer, Integer, String, String>(input.f0, input.f1,
input.f2, temp.f0, temp.f1, temp.f2);
resultFuture.complete(Collections.singleton(te));
}
}
}catch (Exception e){
e.printStackTrace();
}
});
}
//异步去读Es表
/* private void search(Tuple2<Tuple2<String, String>, Integer> input, ResultFuture<Tuple2<Tuple2<String, String>, String>> resultFuture) {
SearchRequest searchRequest = new SearchRequest("posts");
searchRequest.indices("trafficwisdom.train_section_percent");
String fromCity = input.f0.f0;
String toCity = input.f0.f1;
QueryBuilder builder = QueryBuilders.boolQuery().must(QueryBuilders.termQuery("from_city", fromCity)).must(QueryBuilders.termQuery("to_city", toCity));
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(builder);
searchRequest.source(sourceBuilder);
ActionListener<SearchResponse> listener = new ActionListener<SearchResponse>() {
//成功
@Override
public void onResponse(SearchResponse searchResponse) {
String stationPercent = null;
SearchHit[] searchHits = searchResponse.getHits().getHits();
if (searchHits.length > 0) {
JSONObject jsonObject = JSONObject.parseObject(searchHits[0].getSourceAsString());
stationPercent = jsonObject.getString("section_search_percent");
cityPercent.put(input.f0, stationPercent);
}
System.out.println("get data from the es :" + stationPercent);
resultFuture.complete(Collections.singleton(new Tuple2<Tuple2<String, String>, String>(input.f0, stationPercent)));
}
//失败
@Override
public void onFailure(Exception e) {
resultFuture.complete(Collections.singleton(new Tuple2<Tuple2<String, String>, String>(input.f0, null)));
}
};
restHighLevelClient.searchAsync(searchRequest, listener);
}*/
private static Connection getConnection() {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://192.168.10.22:3306/flinkdb?useUnicode=true&characterEncoding=UTF-8", "root", "root123");
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
}
<file_sep>/src/main/java/com/zbcmdata/flink/FlinkApplications/functions/sink/hbase/HBaseVideoInfoSink.java
package com.zbcmdata.flink.FlinkApplications.functions.sink.hbase;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSONObject;
import com.zbcmdata.flink.service.dao.HbaseDao;
import com.zbcmdata.flink.service.dao.impl.HBaseDaoImpl;
import com.zbcmdata.flink.util.HbaseUtil;
import com.zbcmdata.flink.FlinkApplications.bean.ItemInfo;
import com.zbcmdata.flink.common.Constant;
public class HBaseVideoInfoSink extends RichSinkFunction<String> {
private static Logger LOGGER = Logger.getLogger(HBaseVideoInfoSink.class);
/**
*
*/
private static final long serialVersionUID = 1564970258855083046L;
private static HBaseDaoImpl hBaseDao = null;
@Override
public void invoke(String value) throws Exception {
// TODO Auto-generated method stub
ItemInfo videoInfo = ItemInfo.parseFromJson(value);
int vid = videoInfo.getItemId();
String title = videoInfo.getTitle();
String summary = videoInfo.getSummary();
String titleWords = videoInfo.getTitleWords();
String summaryWords = videoInfo.getSummaryWords();
String tag1 = videoInfo.getTag1();
String tag2 = videoInfo.getTag2();
String statDate = videoInfo.getPublishTime();
String rowkey = HbaseUtil.vid2md5(vid + "");
Put put = new Put(Bytes.toBytes(rowkey));
put.add(Bytes.toBytes("f1"), Bytes.toBytes("title"), Bytes.toBytes(title));
put.add(Bytes.toBytes("f1"), Bytes.toBytes("summary"), Bytes.toBytes(summary));
put.add(Bytes.toBytes("f1"), Bytes.toBytes("titleWords"), Bytes.toBytes(titleWords));
put.add(Bytes.toBytes("f1"), Bytes.toBytes("summaryWords"), Bytes.toBytes(summaryWords));
put.add(Bytes.toBytes("f1"), Bytes.toBytes("tag1"), Bytes.toBytes(tag1));
put.add(Bytes.toBytes("f1"), Bytes.toBytes("tag2"), Bytes.toBytes(tag2));
put.add(Bytes.toBytes("f1"), Bytes.toBytes("publishTime"), Bytes.toBytes(statDate));
try {
hBaseDao.saveOneData(Constant.HBASE_ZHANQI_VIDEOREC_INFO, put);
// logMessage = "successed save log index recored into table: " +
// Constant.HBASE_ZHANQI_VIDEOREC_CLIENTLOG_INDEX +
// ", rowkey: " + rowkey;
// LOGGER.info(logMessage);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
// logMessage = "failed to save log index recored into table: " +
// Constant.HBASE_ZHANQI_VIDEOREC_CLIENTLOG_INDEX +
// ", rowkey: " + rowkey;
// LOGGER.error(logMessage);
}
}
public void open(Configuration configuration)throws Exception{
hBaseDao = new HBaseDaoImpl();
LOGGER.info("create hbase connection server");
super.open(configuration);
}
public void close()throws Exception{
hBaseDao.close();
LOGGER.info("close hbase connection server");
}
}
<file_sep>/src/main/java/com/zbcmdata/flink/examples/cep/monitoring/CEPMonitoring.java
package com.zbcmdata.flink.examples.cep.monitoring;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternFlatSelectFunction;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.IterativeCondition;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.AssignerWithPeriodicWatermarks;
import org.apache.flink.streaming.api.functions.AssignerWithPunctuatedWatermarks;
import org.apache.flink.streaming.api.functions.IngestionTimeExtractor;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
import java.util.List;
import java.util.Map;
public class CEPMonitoring {
private static final double TEMPERATURE_THRESHOLD = 100;
private static final int MAX_RACK_ID = 10;
private static final long PAUSE = 100;
private static final double TEMPERATURE_RATIO = 0.5;
private static final double POWER_STD = 10;
private static final double POWER_MEAN = 100;
private static final double TEMP_STD = 20;
private static final double TEMP_MEAN = 80;
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// Use ingestion time => TimeCharacteristic == EventTime + IngestionTimeExtractor
/*
flink的TimeCharacteristic枚举定义了三类值,分别是ProcessingTime、IngestionTime、EventTime
/*ProcessingTime:处理时间:消息被计算处理的时间, 也就是由机器的系统时间来决定。
EventTime:事件时间:事件发生时的时间, 一般就是数据本身携带的时间。
IngestionTime: 摄取时间:事件进入流处理系统的时间
*
* flink的TimeCharacteristic枚举定义了三类值,分别是ProcessingTime、IngestionTime、EventTime
ProcessingTime是以operator处理的时间为准,它使用的是机器的系统时间来作为data stream的时间;
IngestionTime是以数据进入flink streaming data flow的时间为准;
EventTime是以数据自带的时间戳字段为准,应用程序需要指定如何从record中抽取时间戳字段
指定为EventTime的source需要自己定义event time以及emit watermark,
或者在source之外通过assignTimestampsAndWatermarks在程序手工指定
*/
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
System.out.println("1");
// Input stream of monitoring events
DataStream<MonitoringEvent> inputEventStream = env.addSource(new MonitoringEventSource(
MAX_RACK_ID,
PAUSE,
TEMPERATURE_RATIO,
POWER_STD,
POWER_MEAN,
TEMP_STD,
TEMP_MEAN))
.assignTimestampsAndWatermarks(new AssignerWithPunctuatedWatermarks<MonitoringEvent>(){
/**
*
*/
private static final long serialVersionUID = 457562561111149533L;
@Override
public long extractTimestamp(MonitoringEvent element,
long previousElementTimestamp) {
// TODO Auto-generated method stub
System.out.println("2");
return 0;
}
@Override
public Watermark checkAndGetNextWatermark(
MonitoringEvent lastElement, long extractedTimestamp) {
System.out.println("3");
// TODO Auto-generated method stub
return null;
}
});
//.assignTimestampsAndWatermarks(new IngestionTimeExtractor<>());
//每个模式都由一系列事件组成,这些事件可以分配可选的过滤条件
//first pattern 只对温度高于阈值的TemperatureEvents感兴趣,因此我们必须添加一个额外的子类型约束subtype和一个where子句
//next: 新的pattern相当于只是对之前的pattern包了一层,在上一个event时间后面添加了新的匹配事件,得到了新的pattern,
//新pattern的匹配事件必须直接跟着先前pattern的匹配事件严格连续,这样就保证了需求中:10秒内连续两次上报的温度超过阈值 满足告警的需求条件
//定义事件模式
Pattern<MonitoringEvent, ?> warningPattern = Pattern.<MonitoringEvent>begin("first event")
.subtype(TemperatureEvent.class)
.where(new IterativeCondition<TemperatureEvent>() {
private static final long serialVersionUID = -6301755149429716724L;
@Override
public boolean filter(TemperatureEvent value, Context<TemperatureEvent> ctx) throws Exception {
return value.getTemperature() >= TEMPERATURE_THRESHOLD;
}
})
.next("second event")
.subtype(TemperatureEvent.class)
.where(new IterativeCondition<TemperatureEvent>() {
private static final long serialVersionUID = 2392863109523984059L;
@Override
public boolean filter(TemperatureEvent value, Context<TemperatureEvent> ctx) throws Exception {
return value.getTemperature() >= TEMPERATURE_THRESHOLD;
}
})
.within(Time.seconds(10));
System.out.println("4");
//通过“rackID” POJO字段进行keyby输入事件流,使得模式的匹配事件都具有相同得rackID,并将事件模式应用于inputEventStream
// Create a pattern stream from our warning pattern
PatternStream<MonitoringEvent> tempPatternStream = CEP.pattern(
inputEventStream.keyBy("rackID"),
warningPattern);
//select API调用访问成功匹配得事件序列
// Generate temperature warnings for each matched warning pattern
//使用select方法为每个匹配的报警模式生成相应的报警。
//其中返回值是一个map,key是我们定义的模式,value是匹配的事件列表
// DataStream<TemperatureWarning> warnings = tempPatternStream.select(
// (Map<String, List<MonitoringEvent>> pattern) -> {
// TemperatureEvent first = (TemperatureEvent) pattern.get("first").get(0);
// TemperatureEvent second = (TemperatureEvent) pattern.get("second").get(0);
//
// return new TemperatureWarning(first.getRackID(), (first.getTemperature() + second.getTemperature()) / 2);
// }
// );
//从初始监视事件流生成了一个新的复杂事件流DataStream 警告,此复杂事件流可再次用作另一轮复杂事件处理的输入
DataStream<TemperatureWarning> warnings = tempPatternStream.select(
new PatternSelectFunction<MonitoringEvent,TemperatureWarning>(){
private static final long serialVersionUID = 198546543L;
@Override
public TemperatureWarning select(
Map<String, List<MonitoringEvent>> pattern)
throws Exception {
TemperatureEvent first = (TemperatureEvent) pattern.get("first").get(0);
TemperatureEvent second = (TemperatureEvent) pattern.get("second").get(0);
System.out.println("5");
return new TemperatureWarning(first.getRackID(), (first.getTemperature() + second.getTemperature()) / 2);
}});
// Alert pattern: Two consecutive temperature warnings appearing within a time interval of 20 seconds
//每当我们看到温度升高的同一机架连续两次温度警报时,我们就会使用TemperatureWarnings生成TemperatureAlerts
//首先,必须定义警报事件模式:希望在20秒内看到两个温度警报。 第一个事件的名称为“First Event”,第二个连续的事件的名称为“Second Event”
//单个事件没有分配where子句,因为我们需要访问这两个事件以确定温度是否在增加。
Pattern<TemperatureWarning, ?> alertPattern = Pattern.<TemperatureWarning>begin("first")
.next("second")
.within(Time.seconds(20));
// Create a pattern stream from our alert pattern
//通过“rackID” keyby 警告输入流,以便我们单独为每个机架生成警报
PatternStream<TemperatureWarning> alertPatternStream = CEP.pattern(
warnings.keyBy("rackID"),
alertPattern);
// Generate a temperature alert only if the second temperature warning's average temperature is higher than
// first warning's temperature
// DataStream<TemperatureAlert> alerts = alertPatternStream.flatSelect(
// (Map<String, List<TemperatureWarning>> pattern, Collector<TemperatureAlert> out) -> {
// TemperatureWarning first = pattern.get("first").get(0);
// TemperatureWarning second = pattern.get("second").get(0);
//
// if (first.getAverageTemperature() < second.getAverageTemperature()) {
// out.collect(new TemperatureAlert(first.getRackID()));
// }
// },
// TypeInformation.of(TemperatureAlert.class));
//flatSelect方法,该方法将允许我们访问匹配的事件序列,并允许我们输出任意数量的复杂事件
//因此,当且仅当温度升高时,我们才会生成TemperatureAlert
//TemperatureAlert警报是每个机架的温度警报的数据流。 基于这些警报,我们现在可以调整过热架的工作负载或冷却。
DataStream<TemperatureAlert> alerts = alertPatternStream.flatSelect(
new PatternFlatSelectFunction<TemperatureWarning,TemperatureAlert>(){
@Override
public void flatSelect(
Map<String, List<TemperatureWarning>> pattern,
Collector<TemperatureAlert> out) throws Exception {
TemperatureWarning first = pattern.get("first").get(0);
TemperatureWarning second = pattern.get("second").get(0);
if (first.getAverageTemperature() < second.getAverageTemperature()) {
out.collect(new TemperatureAlert(first.getRackID()));
}
}},
TypeInformation.of(TemperatureAlert.class));
// Print the warning and alert events to stdout
System.out.println("6");
warnings.print();
alerts.print();
System.out.println("7");
env.execute("CEP monitoring job");
}
}
<file_sep>/src/main/java/com/zbcmdata/flink/FlinkApplications/model/recommend/user/UserOnLineRecommend.java
package com.zbcmdata.flink.FlinkApplications.model.recommend.user;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import com.alibaba.fastjson.JSONObject;
import com.sun.tools.corba.se.idl.constExpr.And;
import com.zbcmdata.flink.FlinkApplications.bean.ItemInfo;
import com.zbcmdata.flink.FlinkApplications.model.similarity.KeyWordsSimilarity;
import com.zbcmdata.flink.FlinkApplications.model.similarity.VideoSimilarity;
import com.zbcmdata.flink.FlinkApplications.model.sort.ContentRecommendSort;
import com.zbcmdata.flink.common.Constant;
import com.zbcmdata.flink.service.dao.MysqlDao;
import com.zbcmdata.flink.service.dao.impl.MysqlDaoImpl;
import com.zbcmdata.flink.service.redis.RedisClient;
import com.zbcmdata.flink.util.LogUtil;
public class UserOnLineRecommend {
private static MysqlDao mysqlDao = new MysqlDaoImpl();
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
private static RedisClient redisClient = new RedisClient();
public boolean getRecommendVideos(String value, int type) throws Exception{
boolean isSuccess = true;
String candidateDateStr = getCandidateDateStr(Constant.USER_REC_CANDIDATE_DAYS);
JSONObject jsonObject = JSONObject.parseObject(value);
int uid = Integer.parseInt(jsonObject.getString("uid"));
String scoreList = jsonObject.getString("scorelist");
Map<String, Double> recScoreMap = new HashMap<String, Double>(); //推荐候选集
Map<String, List<ItemInfo>> candidateVideoSet = new HashMap<>(); //初始候选集
String[] pairs = scoreList.split(" ");
for (String pair : pairs) {
int itemId = -1;
try {
String[] temps = pair.split(":");
itemId = Integer.parseInt(temps[0]);
double weight = Double.parseDouble(temps[1]);
//1. get category first
String sql = "select tag1,tag_feature,titleWords,summaryWords from " + Constant.IDL_ZQFZB_NLP_FEATURE_INFO
+ " where item_id = " + itemId + " and type = " + type;
List<HashMap<String, String>> rs = mysqlDao.query(sql, 1);
if (rs.size() < 1) {
System.out.println(LogUtil.logTime() + "can not get nlp feature info for itemId: " + itemId + "\n");
continue;
}
String tag1 = rs.get(0).get("tag1");
String titleWords = rs.get(0).get("titleWords");
String summaryWords = rs.get(0).get("summaryWords");
String tag_feature = rs.get(0).get("tag_feature");
ItemInfo baseInfo = new ItemInfo();
baseInfo.setItemId(itemId);
baseInfo.setTag1(tag1);
baseInfo.setTagFeature(tag_feature);
baseInfo.setTitleWords(titleWords);
baseInfo.setSummaryWords(summaryWords);
baseInfo.setType(type);
List<ItemInfo> candidateInfos = new ArrayList<>();
if (candidateVideoSet.containsKey(tag1)) {
candidateInfos = candidateVideoSet.get(tag1);
}else {
//2. get video infos by categoryId
List<ItemInfo> itemInfos = mysqlDao.getItemInfoByCategoryAndDate(Constant.IDL_ZQFZB_NLP_FEATURE_INFO,
tag1,
candidateDateStr,
type,
1);
for (ItemInfo itemInfo : itemInfos) {
if (isToFilter(uid, itemInfo)) {
continue;
}else {
candidateInfos.add(itemInfo);
}
}
candidateVideoSet.put(candidateDateStr, candidateInfos);
}
//3. update recommend score map
updateRecommendScore(baseInfo, candidateInfos, weight, recScoreMap);
} catch (Exception e) {
// TODO: handle exception
System.out.println("exception for vid: " + itemId);
e.printStackTrace();
}
}
//4. recommend sort by score & publish time
List<String> recommend_list = ContentRecommendSort.sortWithNoSimilarity(recScoreMap, 10);
//5. update into redis
saveIntoRedis(uid, recommend_list);
return isSuccess;
}
//候选集中的video是否需要过滤
private boolean isToFilter(int uid, ItemInfo candidate){
boolean toFilter = false;
String watchedKey = "watched_" + uid + "_" + candidate.getItemId();
String recommendedKey = "recommended_" + uid + "_" + candidate.getItemId();
if (redisClient.exists(watchedKey) || redisClient.exists(recommendedKey)) {
toFilter = true;
}
return toFilter;
}
private String getCandidateDateStr(int days){
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, days);
date = calendar.getTime();
return sdf.format(date);
}
private void updateRecommendScore(ItemInfo base, List<ItemInfo> candidateList,
double weight, Map<String, Double> recScoreMap){
for (ItemInfo candidate : candidateList) {
if (base.getItemId() == candidate.getItemId()) {
continue;
}
double similarity = VideoSimilarity.NLPFeatureSimilarity(base, candidate);
if (!recScoreMap.containsKey(candidate.getItemId())) {
recScoreMap.put(candidate.getItemId()+"", similarity);
}else {
double value = recScoreMap.get(candidate.getItemId());
value += similarity;
recScoreMap.put(candidate.getItemId()+"", value);
}
}
}
private void saveIntoRedis(int uid, List<String> recommend_list){
Jedis jedis = redisClient.getJedis();
Pipeline pipeline = jedis.pipelined();
for (int i = recommend_list.size() -1 ; i >= 0; i--) {
String vid = recommend_list.get(i);
redisClient.set("recommended_" + uid + "_" + vid, "1");
redisClient.expire("recommended_" + uid + "_" + vid, Constant.REDIS_VIDEO_RECOMMENDED_EXPIRE_TIME);
pipeline.lpush("zqsv_on_401_" + uid, vid);
pipeline.expire("zqsv_on_401_" + uid, 43200);
}
List<Object> results = pipeline.syncAndReturnAll();
pipeline.clear();
try {
pipeline.close();
jedis.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
System.out.println("OnLine recommenditon for redis key:" + "zqsv_on_401_" + uid + ", push " + recommend_list.size() + " videos");
}
public void close(){
try {
if (null != redisClient) {
redisClient.close();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
try {
if (null != mysqlDao) {
mysqlDao.close();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
//load infos from redis
public List<ItemInfo> loadCandidateVideoInfoFromDB(String candidateDateStr, int type) throws Exception{
List<ItemInfo> list = mysqlDao.getItemInfoByDate(Constant.IDL_ZQFZB_NLP_FEATURE_INFO,
candidateDateStr,
type,
1);
return list;
}
}
<file_sep>/src/main/java/com/zbcmdata/flink/FlinkApplications/streaming/rongcloudBI/service/dao/impl/MysqlDaoImpl.java
package com.zbcmdata.flink.FlinkApplications.streaming.rongcloudBI.service.dao.impl;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.log4j.Logger;
import com.mysql.cj.exceptions.ConnectionIsClosedException;
import com.zbcmdata.flink.FlinkApplications.bean.AuditDataInfo;
import com.zbcmdata.flink.FlinkApplications.bean.AuditLogInfo;
import com.zbcmdata.flink.FlinkApplications.bean.DepAuditDataInfo;
import com.zbcmdata.flink.FlinkApplications.bean.DepMemAuditDataInfo;
import com.zbcmdata.flink.FlinkApplications.streaming.rongcloudBI.service.dao.MysqlDao;
import com.zbcmdata.flink.common.Constant;
import com.zbcmdata.flink.util.DateUtil;
import com.zbcmdata.flink.util.PropertiesFileUtil;
public class MysqlDaoImpl implements MysqlDao{
private static Logger LOGGER = Logger.getLogger(MysqlDaoImpl.class);
public static String driver = "com.mysql.jdbc.Driver";
private static String jdbcUrl;
private static String user;
private static String pwd;
private static Connection connection = null;
private static Properties properties = null;
public MysqlDaoImpl(){
connection = getConnection();
}
public MysqlDaoImpl(String confDir){
connection = getConnection(confDir);
}
public MysqlDaoImpl(Configuration configuration){
connection = getConnection(configuration);
}
private Connection getConnection() {
Connection connection = null;
try {
Class.forName(driver).newInstance();
// properties = PropertiesFileUtil.load("classpath:configure/client/client_storeservice_conf.properties");
properties = PropertiesFileUtil.load(Constant.MTY_CONFIGURE_DIR + File.separator +
"configure/client/client_storeservice_conf.properties");
jdbcUrl= properties.getProperty("db.mysql.jdbcUrl");
user = properties.getProperty("db.mysql.user");
pwd = properties.getProperty("<PASSWORD>");
connection = (Connection) DriverManager.getConnection(jdbcUrl, user,
pwd);
} catch (InstantiationException e) {
e.printStackTrace();
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
return null;
} catch (IllegalAccessException e) {
e.printStackTrace();
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
return null;
} catch (ClassNotFoundException e) {
e.printStackTrace();
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
return null;
} catch (SQLException e) {
e.printStackTrace();
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
return null;
}
return connection;
}
public Connection getConnection(String confDir){
Connection connection = null;
try {
Class.forName(driver).newInstance();
properties = PropertiesFileUtil.load(confDir);
jdbcUrl = properties.getProperty("db.mysql.jdbcUrl");
user = properties.getProperty("db.mysql.user");
pwd = properties.getProperty("<PASSWORD>");
connection = (Connection) DriverManager.getConnection(jdbcUrl, user,
pwd);
} catch (InstantiationException e) {
e.printStackTrace();
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
return null;
} catch (IllegalAccessException e) {
e.printStackTrace();
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
return null;
} catch (ClassNotFoundException e) {
e.printStackTrace();
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
return null;
} catch (SQLException e) {
e.printStackTrace();
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
return null;
}
return connection;
}
public Connection getConnection(Configuration configuration){
Connection connection = null;
try {
Class.forName(driver).newInstance();
jdbcUrl = configuration.get("db.mysql.jdbcUrl");
user = configuration.get("db.mysql.user");
pwd = <PASSWORD>.get("<PASSWORD>");
connection = (Connection) DriverManager.getConnection(jdbcUrl, user, pwd);
} catch (InstantiationException e) {
e.printStackTrace();
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
return null;
} catch (IllegalAccessException e) {
e.printStackTrace();
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
return null;
} catch (ClassNotFoundException e) {
e.printStackTrace();
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
return null;
} catch (SQLException e) {
e.printStackTrace();
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
return null;
}
return connection;
}
public List<HashMap<String, String>> query(String sql, int retryCount)
throws Exception
{
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
if(retryCount > 3)
throw new Exception("retry count > 3");
if (null == connection || connection.isClosed()) {
connection = getConnection();
}
try {
preparedStatement = connection.prepareStatement(sql);
//System.out.print(sql);
resultSet = preparedStatement.executeQuery(sql);
}catch(ConnectionIsClosedException closedException) {
closedException.printStackTrace();
connection = getConnection();
query(sql, ++retryCount);
}catch (SQLException e) {
e.printStackTrace();
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
query(sql, ++retryCount);
}
List<HashMap<String, String>> result = new ArrayList<HashMap<String, String>>();
try {
ResultSetMetaData md = resultSet.getMetaData();
int columnCount = md.getColumnCount();
while (resultSet.next()) {
HashMap<String, String> columnMap = new HashMap<String, String>();
for (int i = 1; i <= columnCount; i++) {
columnMap.put(md.getColumnName(i), resultSet.getString(i));
}
result.add(columnMap);
}
resultSet.close();
preparedStatement.close();
}catch (SQLException e) {
e.printStackTrace();
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
}
return result;
}
public synchronized void close() {
try {
if (!connection.isClosed()) {
connection.close();
connection = null;
}
} catch (SQLException e) {
e.printStackTrace();
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
}
}
public void insertOneAuditLogRecord(String tableName, AuditLogInfo auditLogInfo, int retryCount)
throws Exception {
if(null == tableName || null == auditLogInfo)
throw new IllegalArgumentException("argument is null!");
if(retryCount > 3)
throw new Exception("retry count > 3");
PreparedStatement preparedStatement = null;
try
{
if(null == connection || connection.isClosed())
connection = getConnection();
String sql = "insert into "+ tableName +" (createtime,item_id,type,label,action_type,action_result,remark ,action_group ,action_person,source_id) values (?,?,?,?,?,?,?,?,?,?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, auditLogInfo.getCreateTime());
preparedStatement.setInt(2, auditLogInfo.getItemID());
preparedStatement.setInt(3, auditLogInfo.getItemType());
preparedStatement.setString(4, auditLogInfo.getItemLabel());
preparedStatement.setInt(5, auditLogInfo.getActionType());
preparedStatement.setInt(6, auditLogInfo.getActionResult());
preparedStatement.setString(7, auditLogInfo.getRemarks());
preparedStatement.setInt(8, auditLogInfo.getActionGroup());
preparedStatement.setInt(9, auditLogInfo.getActionPerson());
preparedStatement.setInt(10, auditLogInfo.getSourceId());
//System.out.println("执行审核数据插入语句: " + '\n' + preparedStatement.toString());
preparedStatement.executeUpdate();
//System.out.println("当前审核计算数据成功插入到mysql表:" + tableName);
preparedStatement.close();
}catch(ConnectionIsClosedException closedException) {
closedException.printStackTrace();
connection = getConnection();
insertOneAuditLogRecord(tableName, auditLogInfo, ++retryCount);
}catch(SQLException e){
e.printStackTrace();
if(preparedStatement != null)
try{
preparedStatement.close();
}catch(SQLException sqlexception) {
System.out.println(e.getMessage());
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
}
insertOneAuditLogRecord(tableName, auditLogInfo, ++retryCount);
}
}
@Override
public void insertOneAuditResultRecord(String tableName, AuditDataInfo auditLogInfo, int retryCount)
throws Exception {
if(null == tableName || null == auditLogInfo)
throw new IllegalArgumentException("argument is null!");
if(retryCount > 3)
throw new Exception("retry count > 3");
PreparedStatement preparedStatement = null;
try
{
if(null == connection || connection.isClosed())
connection = getConnection();
String sql = "insert into "+ tableName +" (stat_date,item_type,source_id,incoming_audit_cnt,firstaudited_cnt," +
"againaudited_cnt,passed_audit_cnt,firstpassed_audit_cnt,againpassed_audit_cnt,nopassed_audit_cnt) values (?,?,?,?,?,?,?,?,?,?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, auditLogInfo.getStatDate());
preparedStatement.setInt(2, auditLogInfo.getItemType());
preparedStatement.setInt(3, auditLogInfo.getSourceId());
preparedStatement.setInt(4, auditLogInfo.getInComing());
preparedStatement.setInt(5, auditLogInfo.getFirstHasAudited());
preparedStatement.setInt(6, auditLogInfo.getAgainHasAudited());
preparedStatement.setInt(7, auditLogInfo.getPassAudited());
preparedStatement.setInt(8, auditLogInfo.getFirstPassAudited());
preparedStatement.setInt(9, auditLogInfo.getAgainPassAudited());
preparedStatement.setInt(10, auditLogInfo.getNoPassAudited());
//System.out.println("执行审核数据插入语句: " + '\n' + preparedStatement.toString());
preparedStatement.executeUpdate();
//System.out.println("当前审核计算数据成功插入到mysql表:" + tableName);
preparedStatement.close();
}catch(ConnectionIsClosedException closedException) {
closedException.printStackTrace();
connection = getConnection();
insertOneAuditResultRecord(tableName, auditLogInfo, ++retryCount);
}catch(SQLException e){
e.printStackTrace();
if(preparedStatement != null)
try{
preparedStatement.close();
}catch(SQLException sqlexception) {
System.out.println(e.getMessage());
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
}
insertOneAuditResultRecord(tableName, auditLogInfo, ++retryCount);
}
}
public void insertWaitAuditResultRecord(String tableName,int item_type,int source_id, int wait_firstaudit_cnt, int wait_againaudit_cnt, int retryCount)
throws Exception {
if(null == tableName)
throw new IllegalArgumentException("argument is null!");
if(retryCount > 3)
throw new Exception("retry count > 3");
PreparedStatement preparedStatement = null;
try
{
if(null == connection || connection.isClosed())
connection = getConnection();
String sql = "insert into "+ tableName +" (stat_time,item_type,source_id,wait_firstaudit_cnt,wait_againaudit_cnt) values (?,?,?,?,?)";
Date date = new Date();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,DateUtil.date2String(date));
preparedStatement.setInt(2,item_type );
preparedStatement.setInt(3,source_id );
preparedStatement.setInt(4,wait_firstaudit_cnt );
preparedStatement.setInt(5, wait_againaudit_cnt);
//System.out.println("执行待审核数据插入语句: " + '\n' + preparedStatement.toString());
preparedStatement.executeUpdate();
//System.out.println("当前待审核计算数据成功插入到mysql表:" + tableName);
preparedStatement.close();
}catch(ConnectionIsClosedException closedException) {
closedException.printStackTrace();
connection = getConnection();
insertWaitAuditResultRecord(tableName,item_type,source_id, wait_firstaudit_cnt,wait_againaudit_cnt, ++retryCount);
}catch(SQLException e){
e.printStackTrace();
if(preparedStatement != null)
try{
preparedStatement.close();
}catch(SQLException sqlexception) {
System.out.println(e.getMessage());
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
}
insertWaitAuditResultRecord(tableName, item_type,source_id,wait_firstaudit_cnt,wait_againaudit_cnt, ++retryCount);
}
}
@Override
public void clearAll(String tableName, int retryCount) throws Exception {
if(retryCount > 3)
throw new Exception("retry count > 3");
PreparedStatement prest = null;
try{
if (null == connection || connection.isClosed()) {
connection = getConnection();
}
String sql = (new StringBuilder("truncate table ")).append(tableName).toString();
prest = connection.prepareStatement(sql);
prest.executeUpdate();
prest.close();
}catch(SQLException e){
e.printStackTrace();
clearAll(tableName, ++retryCount);
}catch(Exception e){
System.out.println(e.getMessage());
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
}finally {
if (null != prest) {
prest.close();
}
}
}
public void updateAuditResultRecord(String tableName, AuditDataInfo auditLogInfo, int retryCount)
throws Exception {
if(null == tableName || null == auditLogInfo)
throw new IllegalArgumentException("argument is null!");
if(retryCount > 3)
throw new Exception("retry count > 3");
PreparedStatement preparedStatement = null;
try
{
if(null == connection || connection.isClosed())
connection = getConnection();
String sql = "update "+ tableName +" set incoming_audit_cnt = ?,firstaudited_cnt = ?,againaudited_cnt = ?," +
"passed_audit_cnt = ?,firstpassed_audit_cnt = ?,againpassed_audit_cnt = ?,nopassed_audit_cnt = ?" +
" where stat_date = ? and item_type = ? and source_id = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, auditLogInfo.getInComing());
preparedStatement.setInt(2, auditLogInfo.getFirstHasAudited());
preparedStatement.setInt(3, auditLogInfo.getAgainHasAudited());
preparedStatement.setInt(4, auditLogInfo.getPassAudited());
//preparedStatement.setInt(3, auditLogInfo.getFirstPassAudited() + auditLogInfo.getAgainPassAudited());
preparedStatement.setInt(5, auditLogInfo.getFirstPassAudited());
preparedStatement.setInt(6, auditLogInfo.getAgainPassAudited());
preparedStatement.setInt(7, auditLogInfo.getNoPassAudited());
preparedStatement.setString(8, auditLogInfo.getStatDate());
preparedStatement.setInt(9, auditLogInfo.getItemType());
preparedStatement.setInt(10, auditLogInfo.getSourceId());
//System.out.println("执行更新语句: " + '\n' + preparedStatement.toString());
preparedStatement.executeUpdate();
//System.out.println("当前审核计算数据成功更新到mysql表:" + tableName);
preparedStatement.close();
}catch(ConnectionIsClosedException closedException) {
closedException.printStackTrace();
connection = getConnection();
updateAuditResultRecord(tableName, auditLogInfo, ++retryCount);
}catch(SQLException e){
e.printStackTrace();
if(preparedStatement != null)
try{
preparedStatement.close();
}catch(SQLException sqlexception) {
System.out.println(e.getMessage());
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
}
updateAuditResultRecord(tableName, auditLogInfo, ++retryCount);
}
}
//更新插入按天按部门审核统计数据
public void updateInsertDepAuditResultRecord(String tableName, DepAuditDataInfo depAuditLogInfo, int retryCount)
throws Exception {
if(null == tableName || null == depAuditLogInfo)
throw new IllegalArgumentException("argument is null!");
if(retryCount > 3)
throw new Exception("retry count > 3");
PreparedStatement preparedStatement = null;
try
{
if(null == connection || connection.isClosed())
connection = getConnection();
String sql = "insert into "+ tableName +" set stat_date = ? ,item_type = ?,department_id = ?,incoming_audit_cnt = ?,firstaudited_cnt = ?,againaudited_cnt = ?," +
"passed_audit_cnt = ?,firstpassed_audit_cnt = ?,againpassed_audit_cnt = ?,nopassed_audit_cnt = ?" +
" on duplicate key update incoming_audit_cnt = ?,firstaudited_cnt = ?,againaudited_cnt = ?," +
"passed_audit_cnt = ?,firstpassed_audit_cnt = ?,againpassed_audit_cnt = ?,nopassed_audit_cnt = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, depAuditLogInfo.getStatDate());
preparedStatement.setInt(2, depAuditLogInfo.getItemType());
preparedStatement.setInt(3, depAuditLogInfo.getDepartment());
preparedStatement.setInt(4, depAuditLogInfo.getInComing());
preparedStatement.setInt(5, depAuditLogInfo.getFirstHasAudited());
preparedStatement.setInt(6, depAuditLogInfo.getAgainHasAudited());
preparedStatement.setInt(7, depAuditLogInfo.getPassAudited());
preparedStatement.setInt(8, depAuditLogInfo.getFirstPassAudited());
preparedStatement.setInt(9, depAuditLogInfo.getAgainPassAudited());
preparedStatement.setInt(10, depAuditLogInfo.getNoPassAudited());
preparedStatement.setInt(11, depAuditLogInfo.getInComing());
preparedStatement.setInt(12, depAuditLogInfo.getFirstHasAudited());
preparedStatement.setInt(13, depAuditLogInfo.getAgainHasAudited());
preparedStatement.setInt(14, depAuditLogInfo.getPassAudited());
preparedStatement.setInt(15, depAuditLogInfo.getFirstPassAudited());
preparedStatement.setInt(16, depAuditLogInfo.getAgainPassAudited());
preparedStatement.setInt(17, depAuditLogInfo.getNoPassAudited());
//System.out.println("执行更新语句: " + '\n' + preparedStatement.toString());
preparedStatement.executeUpdate();
//System.out.println("当前审核计算数据成功更新到mysql表:" + tableName);
preparedStatement.close();
}catch(ConnectionIsClosedException closedException) {
closedException.printStackTrace();
connection = getConnection();
updateInsertDepAuditResultRecord(tableName, depAuditLogInfo, ++retryCount);
}catch(SQLException e){
e.printStackTrace();
if(preparedStatement != null)
try{
preparedStatement.close();
}catch(SQLException sqlexception) {
System.out.println(e.getMessage());
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
}
updateInsertDepAuditResultRecord(tableName, depAuditLogInfo, ++retryCount);
}
}
@Override
public void deleteOneAuditRecord(String tableName, String stat_date, int item_type, int retryCount)
throws Exception {
if(retryCount > 3)
throw new Exception("retry count > 3");
PreparedStatement prest = null;
try{
if (null == connection || connection.isClosed()) {
connection = getConnection();
}
String sql = (new StringBuilder("delete from ")).append(tableName).append(" where stat_date = ? and item_type = ?").toString();
prest = connection.prepareStatement(sql);
prest.setString(1, stat_date);
prest.setInt(2, item_type);
prest.executeUpdate();
prest.close();
}catch(ConnectionIsClosedException closedException) {
closedException.printStackTrace();
connection = getConnection();
deleteOneAuditRecord(tableName, stat_date, item_type, ++retryCount);
}catch(SQLException e){
e.printStackTrace();
deleteOneAuditRecord(tableName, stat_date, item_type, ++retryCount);
}catch(Exception e){
e.printStackTrace();
}finally{
if (null != prest) {
prest.close();
}
}
}
//更新当天全部部门的进审量数据
public void updateDepIncomeData(String tableName,String statDate, int item_type,int incoming_audit_cnt, int retryCount)
throws Exception {
if(null == tableName)
throw new IllegalArgumentException("argument is null!");
if(retryCount > 3)
throw new Exception("retry count > 3");
PreparedStatement preparedStatement = null;
try
{
if(null == connection || connection.isClosed())
connection = getConnection();
String sql = "update "+ tableName +" set incoming_audit_cnt = ? " + " where stat_date = ? and item_type = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,incoming_audit_cnt);
preparedStatement.setString(2,statDate );
preparedStatement.setInt(3,item_type);
//System.out.println("执行更新语句: " + '\n' + preparedStatement.toString());
preparedStatement.executeUpdate();
//System.out.println("当前审核计算数据成功更新到mysql表:" + tableName);
preparedStatement.close();
}catch(ConnectionIsClosedException closedException) {
closedException.printStackTrace();
connection = getConnection();
updateDepIncomeData(tableName, statDate,item_type,incoming_audit_cnt, ++retryCount);
}catch(SQLException e){
e.printStackTrace();
if(preparedStatement != null)
try{
preparedStatement.close();
}catch(SQLException sqlexception) {
System.out.println(e.getMessage());
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
}
updateDepIncomeData(tableName,statDate,item_type,incoming_audit_cnt, ++retryCount);
}
}
//更新全部部门的初审待审核量
public void updateDepWaitData(String tableName,int item_type,int department_id, int wait_firstaudit_cnt, int retryCount)
throws Exception {
if(null == tableName)
throw new IllegalArgumentException("argument is null!");
if(retryCount > 3)
throw new Exception("retry count > 3");
PreparedStatement preparedStatement = null;
try
{
if(null == connection || connection.isClosed())
connection = getConnection();
String sql = "update "+ tableName +" set stat_time = ? ,wait_firstaudit_cnt = ? where department_id =? and item_type = ? " ;
Date date = new Date();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,DateUtil.date2String(date));
preparedStatement.setInt(2,wait_firstaudit_cnt );
preparedStatement.setInt(3,department_id );
preparedStatement.setInt(4,item_type );
//System.out.println("执行更新语句: " + '\n' + preparedStatement.toString());
preparedStatement.executeUpdate();
//System.out.println("当前审核计算数据成功更新到mysql表:" + tableName);
preparedStatement.close();
}catch(ConnectionIsClosedException closedException) {
closedException.printStackTrace();
connection = getConnection();
updateDepWaitData(tableName, item_type,department_id,wait_firstaudit_cnt,++retryCount);
}catch(SQLException e){
e.printStackTrace();
if(preparedStatement != null)
try{
preparedStatement.close();
}catch(SQLException sqlexception) {
System.out.println(e.getMessage());
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
}
updateDepWaitData(tableName,item_type,department_id,wait_firstaudit_cnt, ++retryCount);
}
}
public void updateWaitAuditResultRecord(String tableName, int item_type,int source_id,int wait_firstaudit_cnt, int wait_againaudit_cnt, int retryCount)
throws Exception {
if(null == tableName)
throw new IllegalArgumentException("argument is null!");
if(retryCount > 3)
throw new Exception("retry count > 3");
PreparedStatement preparedStatement = null;
try
{
if(null == connection || connection.isClosed())
connection = getConnection();
String sql = "update "+ tableName +" set stat_time = ? ,wait_firstaudit_cnt = ?,wait_againaudit_cnt = ? where source_id = ? and item_type = ?";
Date date = new Date();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,DateUtil.date2String(date));
preparedStatement.setInt(2,wait_firstaudit_cnt );
preparedStatement.setInt(3, wait_againaudit_cnt);
preparedStatement.setInt(4,source_id );
preparedStatement.setInt(5,item_type );
//System.out.println("执行更新语句: " + '\n' + preparedStatement.toString());
preparedStatement.executeUpdate();
//System.out.println("当前审核计算数据成功更新到mysql表:" + tableName);
preparedStatement.close();
}catch(ConnectionIsClosedException closedException) {
closedException.printStackTrace();
connection = getConnection();
updateWaitAuditResultRecord(tableName,item_type, source_id,wait_firstaudit_cnt,wait_againaudit_cnt, ++retryCount);
}catch(SQLException e){
e.printStackTrace();
if(preparedStatement != null)
try{
preparedStatement.close();
}catch(SQLException sqlexception) {
System.out.println(e.getMessage());
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
}
updateWaitAuditResultRecord(tableName,item_type,source_id, wait_firstaudit_cnt,wait_againaudit_cnt, ++retryCount);
}
}
// String sql = "insert into "+ tableName +" (stat_date,label,incoming_cnt) values (?,?,?)";
public void updateInsertLabelRankResultRecord(String tableName, String statDate,int item_type,int source_id,String label, int incoming_cnt, int retryCount)
throws Exception {
if(null == tableName)
throw new IllegalArgumentException("argument is null!");
if(retryCount > 3)
throw new Exception("retry count > 3");
PreparedStatement preparedStatement = null;
try
{
if(null == connection || connection.isClosed())
connection = getConnection();
String sql = "insert into "+ tableName +" set incoming_cnt = ?,stat_date = ?,item_type = ?, source_id = ?, label = ?" + " on duplicate key update incoming_cnt = ? ";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,incoming_cnt);
preparedStatement.setString(2,statDate );
preparedStatement.setInt(3,item_type);
preparedStatement.setInt(4,source_id);
preparedStatement.setString(5,label);
preparedStatement.setInt(6,incoming_cnt);
//System.out.println("执行更新语句: " + '\n' + preparedStatement.toString());
preparedStatement.executeUpdate();
//System.out.println("当前审核计算数据成功更新到mysql表:" + tableName);
preparedStatement.close();
}catch(ConnectionIsClosedException closedException) {
closedException.printStackTrace();
connection = getConnection();
updateInsertLabelRankResultRecord(tableName, statDate,item_type,source_id,label,incoming_cnt, ++retryCount);
}catch(SQLException e){
e.printStackTrace();
if(preparedStatement != null)
try{
preparedStatement.close();
}catch(SQLException sqlexception) {
System.out.println(e.getMessage());
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
}
updateInsertLabelRankResultRecord(tableName,statDate,item_type,source_id,label,incoming_cnt, ++retryCount);
}
}
//更新插入按部门统计累计待审核相关数据,部门作为唯一键
public void updateInsertDepWaitAuditResultRecord(String tableName,int item_type, int department, int wait_firstaudit_cnt, int wait_againaudit_cnt, int retryCount)
throws Exception {
if(null == tableName)
throw new IllegalArgumentException("argument is null!");
if(retryCount > 3)
throw new Exception("retry count > 3");
PreparedStatement preparedStatement = null;
try
{
if(null == connection || connection.isClosed())
connection = getConnection();
String sql = "insert into "+ tableName +" set stat_time = ?,item_type = ? ,department_id = ?,wait_firstaudit_cnt = ?,wait_againaudit_cnt = ?" + " on duplicate key update stat_time = ?,wait_firstaudit_cnt = ?,wait_againaudit_cnt = ? ";
Date date = new Date();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,DateUtil.date2String(date));
preparedStatement.setInt(2,item_type);
preparedStatement.setInt(3,department);
preparedStatement.setInt(4,wait_firstaudit_cnt );
preparedStatement.setInt(5, wait_againaudit_cnt);
preparedStatement.setString(6,DateUtil.date2String(date));
preparedStatement.setInt(7,wait_firstaudit_cnt );
preparedStatement.setInt(8, wait_againaudit_cnt);
//System.out.println("执行更新语句: " + '\n' + preparedStatement.toString());
preparedStatement.executeUpdate();
//System.out.println("当前审核计算数据成功更新到mysql表:" + tableName);
preparedStatement.close();
}catch(ConnectionIsClosedException closedException) {
closedException.printStackTrace();
connection = getConnection();
updateInsertDepWaitAuditResultRecord(tableName,item_type, department,wait_firstaudit_cnt,wait_againaudit_cnt, ++retryCount);
}catch(SQLException e){
e.printStackTrace();
if(preparedStatement != null)
try{
preparedStatement.close();
}catch(SQLException sqlexception) {
System.out.println(e.getMessage());
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
}
updateInsertDepWaitAuditResultRecord(tableName,item_type,department,wait_firstaudit_cnt,wait_againaudit_cnt, ++retryCount);
}
}
//更新插入按内容来源按小时统计累计审核未通过数据分布,小时+内容来源方id作为唯一键
public void updateInsertNosafehourData(String tableName,String statHour,int item_type, int source_id, int nosafe_cnt, int retryCount)
throws Exception {
if(null == tableName)
throw new IllegalArgumentException("argument is null!");
if(retryCount > 3)
throw new Exception("retry count > 3");
PreparedStatement preparedStatement = null;
try
{
if(null == connection || connection.isClosed())
connection = getConnection();
String sql = "insert into "+ tableName +" set stat_hour = ?,item_type=?,source_id = ?,nosafe_cnt = ? " + " on duplicate key update nosafe_cnt = ? ";
//Date date = new Date();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,statHour);
preparedStatement.setInt(2,item_type);
preparedStatement.setInt(3,source_id);
preparedStatement.setInt(4,nosafe_cnt );
preparedStatement.setInt(5, nosafe_cnt);
//System.out.println("执行更新语句: " + '\n' + preparedStatement.toString());
preparedStatement.executeUpdate();
//System.out.println("当前审核计算数据成功更新到mysql表:" + tableName);
preparedStatement.close();
}catch(ConnectionIsClosedException closedException) {
closedException.printStackTrace();
connection = getConnection();
updateInsertNosafehourData(tableName, statHour,item_type,source_id,nosafe_cnt, ++retryCount);
}catch(SQLException e){
e.printStackTrace();
if(preparedStatement != null)
try{
preparedStatement.close();
}catch(SQLException sqlexception) {
System.out.println(e.getMessage());
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
}
updateInsertNosafehourData(tableName,statHour,item_type,source_id,nosafe_cnt, ++retryCount);
}
}
//更新插入按天按部门统计每个成员当天审核量数据,日期+部门+name作为唯一键
public void updateInsertDepMemberAuditResultRecord(String tableName, DepMemAuditDataInfo depMemAuditLogInfo, int retryCount)
throws Exception {
if(null == tableName)
throw new IllegalArgumentException("argument is null!");
if(retryCount > 3)
throw new Exception("retry count > 3");
PreparedStatement preparedStatement = null;
try
{
if(null == connection || connection.isClosed())
connection = getConnection();
String sql = "insert into "+ tableName +" set stat_date = ?,item_type = ? ,department_id = ?,member_id = ?,audit_cnt = ? ,firstaudited_cnt = ?,againaudited_cnt = ?,firstpassed_audit_cnt = ?,againpassed_audit_cnt = ?,firstnopassed_audit_cnt = ? ,nopassed_audit_cnt = ?"
+ " on duplicate key update audit_cnt = ? ,firstaudited_cnt = ?,againaudited_cnt = ?,firstpassed_audit_cnt = ?,againpassed_audit_cnt = ?,firstnopassed_audit_cnt = ?,nopassed_audit_cnt = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,depMemAuditLogInfo.getStatDate());
preparedStatement.setInt(2,depMemAuditLogInfo.getItemType() );
preparedStatement.setInt(3,depMemAuditLogInfo.getDepartment() );
preparedStatement.setInt(4, depMemAuditLogInfo.getMember_id());
preparedStatement.setInt(5,depMemAuditLogInfo.getAudited());
preparedStatement.setInt(6,depMemAuditLogInfo.getFirstHasAudited());
preparedStatement.setInt(7,depMemAuditLogInfo.getAgainHasAudited());
preparedStatement.setInt(8,depMemAuditLogInfo.getFirstPassAudited());
preparedStatement.setInt(9,depMemAuditLogInfo.getAgainPassAudited());
preparedStatement.setInt(10,depMemAuditLogInfo.getFirstNoPassAudited());
preparedStatement.setInt(11,depMemAuditLogInfo.getNoPassAudited());
preparedStatement.setInt(12,depMemAuditLogInfo.getAudited());
preparedStatement.setInt(13,depMemAuditLogInfo.getFirstHasAudited());
preparedStatement.setInt(14,depMemAuditLogInfo.getAgainHasAudited());
preparedStatement.setInt(15,depMemAuditLogInfo.getFirstPassAudited());
preparedStatement.setInt(16,depMemAuditLogInfo.getAgainPassAudited());
preparedStatement.setInt(17,depMemAuditLogInfo.getFirstNoPassAudited());
preparedStatement.setInt(18,depMemAuditLogInfo.getNoPassAudited());
//System.out.println("执行更新语句: " + '\n' + preparedStatement.toString());
preparedStatement.executeUpdate();
//System.out.println("当前审核计算数据成功更新到mysql表:" + tableName);
preparedStatement.close();
}catch(ConnectionIsClosedException closedException) {
closedException.printStackTrace();
connection = getConnection();
updateInsertDepMemberAuditResultRecord(tableName, depMemAuditLogInfo, ++retryCount);
}catch(SQLException e){
e.printStackTrace();
if(preparedStatement != null)
try{
preparedStatement.close();
}catch(SQLException sqlexception) {
System.out.println(e.getMessage());
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
}
updateInsertDepMemberAuditResultRecord(tableName,depMemAuditLogInfo, ++retryCount);
}
}
//更新插入按天按视频内容来源统计每个安全等级下的视频数据,日期+视频来源id+安全等级作为唯一键
public void updateInsertSafeLevelResultRecord(String tableName,String stadDate,int item_type, int source_id, String safe_level_type, int safe_cnt, int retryCount)
throws Exception {
if(null == tableName)
throw new IllegalArgumentException("argument is null!");
if(retryCount > 3)
throw new Exception("retry count > 3");
PreparedStatement preparedStatement = null;
try
{
if(null == connection || connection.isClosed())
connection = getConnection();
String sql = "insert into "+ tableName +" set stat_date = ?,item_type = ?,source_id = ?,safe_level_type = ?,safe_cnt = ?" + " on duplicate key update safe_cnt = ? ";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,stadDate);
preparedStatement.setInt(2,item_type );
preparedStatement.setInt(3,source_id );
preparedStatement.setString(4, safe_level_type);
preparedStatement.setInt(5,safe_cnt);
preparedStatement.setInt(6,safe_cnt);
//System.out.println("执行更新语句: " + '\n' + preparedStatement.toString());
preparedStatement.executeUpdate();
//System.out.println("当前审核计算数据成功更新到mysql表:" + tableName);
preparedStatement.close();
}catch(ConnectionIsClosedException closedException) {
closedException.printStackTrace();
connection = getConnection();
updateInsertSafeLevelResultRecord(tableName, stadDate,item_type,source_id,safe_level_type,safe_cnt, ++retryCount);
}catch(SQLException e){
e.printStackTrace();
if(preparedStatement != null)
try{
preparedStatement.close();
}catch(SQLException sqlexception) {
System.out.println(e.getMessage());
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
}
updateInsertSafeLevelResultRecord(tableName,stadDate,item_type,source_id,safe_level_type,safe_cnt, ++retryCount);
}
}
//更新插入按天按视频内容来源统计每个违规类型下的视频数据,日期+视频来源id+违规类型作为唯一键
public void updateInsertNoSafeLevelResultRecord(String tableName,String stadDate, int item_type,int source_id, String nosafe_level_type, int nosafe_cnt, int retryCount)
throws Exception {
if(null == tableName)
throw new IllegalArgumentException("argument is null!");
if(retryCount > 3)
throw new Exception("retry count > 3");
PreparedStatement preparedStatement = null;
try
{
if(null == connection || connection.isClosed())
connection = getConnection();
String sql = "insert into "+ tableName +" set stat_date = ?,item_type = ?,source_id = ?,nosafe_level_type = ?,nosafe_cnt = ?" + " on duplicate key update nosafe_cnt = ? ";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,stadDate);
preparedStatement.setInt(2,item_type );
preparedStatement.setInt(3,source_id );
preparedStatement.setString(4, nosafe_level_type);
preparedStatement.setInt(5,nosafe_cnt);
preparedStatement.setInt(6,nosafe_cnt);
//System.out.println("执行更新语句: " + '\n' + preparedStatement.toString());
preparedStatement.executeUpdate();
//System.out.println("当前审核计算数据成功更新到mysql表:" + tableName);
preparedStatement.close();
}catch(ConnectionIsClosedException closedException) {
closedException.printStackTrace();
connection = getConnection();
updateInsertNoSafeLevelResultRecord(tableName, stadDate,item_type,source_id,nosafe_level_type,nosafe_cnt, ++retryCount);
}catch(SQLException e){
e.printStackTrace();
if(preparedStatement != null)
try{
preparedStatement.close();
}catch(SQLException sqlexception) {
System.out.println(e.getMessage());
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
}
updateInsertNoSafeLevelResultRecord(tableName,stadDate,item_type,source_id,nosafe_level_type,nosafe_cnt, ++retryCount);
}
}
//更新插入按天按部门统计每个安全等级下的视频数据,日期+部门+安全等级作为唯一键
public void updateInsertDepMemSafeLevelResultRecord(String tableName,String stadDate, int item_type,int department,int member_id,int action_type,String safe_level_type, int safe_cnt, int retryCount)
throws Exception {
if(null == tableName)
throw new IllegalArgumentException("argument is null!");
if(retryCount > 3)
throw new Exception("retry count > 3");
PreparedStatement preparedStatement = null;
try
{
if(null == connection || connection.isClosed())
connection = getConnection();
String sql = "insert into "+ tableName +" set stat_date = ?,item_type = ?,department_id = ?,member_id = ?, first_or_again = ?,safe_level_type = ?,safe_cnt = ?" + " on duplicate key update safe_cnt = ? ";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,stadDate);
preparedStatement.setInt(2,item_type );
preparedStatement.setInt(3,department );
preparedStatement.setInt(4,member_id );
preparedStatement.setInt(5,action_type );
preparedStatement.setString(6, safe_level_type);
preparedStatement.setInt(7,safe_cnt);
preparedStatement.setInt(8,safe_cnt);
//System.out.println("执行更新语句: " + '\n' + preparedStatement.toString());
preparedStatement.executeUpdate();
//System.out.println("当前审核计算数据成功更新到mysql表:" + tableName);
preparedStatement.close();
}catch(ConnectionIsClosedException closedException) {
closedException.printStackTrace();
connection = getConnection();
updateInsertDepMemSafeLevelResultRecord(tableName, stadDate,item_type,department,member_id,action_type,safe_level_type,safe_cnt, ++retryCount);
}catch(SQLException e){
e.printStackTrace();
if(preparedStatement != null)
try{
preparedStatement.close();
}catch(SQLException sqlexception) {
System.out.println(e.getMessage());
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
}
updateInsertDepMemSafeLevelResultRecord(tableName,stadDate,item_type,department,member_id,action_type,safe_level_type,safe_cnt, ++retryCount);
}
}
//更新插入按天按部门统计每个违规类型下的视频数据,日期+部门+违规类型作为唯一键
public void updateInsertDepMemNoSafeLevelResultRecord(String tableName,String stadDate,int item_type,int department,int member_id,int action_type, String nosafe_level_type, int nosafe_cnt, int retryCount)
throws Exception {
if(null == tableName)
throw new IllegalArgumentException("argument is null!");
if(retryCount > 3)
throw new Exception("retry count > 3");
PreparedStatement preparedStatement = null;
try
{
if(null == connection || connection.isClosed())
connection = getConnection();
String sql = "insert into "+ tableName +" set stat_date = ?,item_type= ? ,department_id = ?, member_id = ?,first_or_again = ?,nosafe_level_type = ?,nosafe_cnt = ?" + " on duplicate key update nosafe_cnt = ? ";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,stadDate);
preparedStatement.setInt(2,item_type );
preparedStatement.setInt(3,department );
preparedStatement.setInt(4,member_id );
preparedStatement.setInt(5,action_type );
preparedStatement.setString(6, nosafe_level_type);
preparedStatement.setInt(7,nosafe_cnt);
preparedStatement.setInt(8,nosafe_cnt);
//System.out.println("执行更新语句: " + '\n' + preparedStatement.toString());
preparedStatement.executeUpdate();
//System.out.println("当前审核计算数据成功更新到mysql表:" + tableName);
preparedStatement.close();
}catch(ConnectionIsClosedException closedException) {
closedException.printStackTrace();
connection = getConnection();
updateInsertDepMemNoSafeLevelResultRecord(tableName, stadDate,item_type,department,member_id,action_type,nosafe_level_type,nosafe_cnt, ++retryCount);
}catch(SQLException e){
e.printStackTrace();
if(preparedStatement != null)
try{
preparedStatement.close();
}catch(SQLException sqlexception) {
System.out.println(e.getMessage());
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
}
updateInsertDepMemNoSafeLevelResultRecord(tableName,stadDate,item_type,department,member_id,action_type,nosafe_level_type,nosafe_cnt, ++retryCount);
}
}
@Override
public List<AuditDataInfo> getOneDayByTypeAuditData(String tableName,
String stat_date, int item_type,int source_id, int retryCount) throws Exception {
if(retryCount > 3)
throw new Exception("retry count > 3");
ResultSet rs = null;
PreparedStatement prest = null;
List<AuditDataInfo> list = new ArrayList<AuditDataInfo>();
try
{
if (null == connection || connection.isClosed()) {
connection = getConnection();
}
String sql = (new StringBuilder("select stat_date,item_type,source_id,incoming_audit_cnt," +
"firstaudited_cnt,againaudited_cnt,passed_audit_cnt,firstpassed_audit_cnt," +
"againpassed_audit_cnt,nopassed_audit_cnt from ")).append(tableName).append(" where stat_date = ? and item_type = ? and source_id = ?").toString();
prest = connection.prepareStatement(sql);
prest.setString(1, stat_date);
prest.setInt(2, item_type);
prest.setInt(3, source_id);
rs = prest.executeQuery();
while(rs.next()){
AuditDataInfo auditDataInfo = new AuditDataInfo();
auditDataInfo.setStatDate(rs.getString(1));
auditDataInfo.setItemType(rs.getInt(2));
auditDataInfo.setSourceId(rs.getInt(3));
auditDataInfo.setInComing(rs.getInt(4));
auditDataInfo.setFirstHasAudited(rs.getInt(5));
auditDataInfo.setAgainHasAudited(rs.getInt(6));
auditDataInfo.setPassAudited(rs.getInt(7));
auditDataInfo.setFirstPassAudited(rs.getInt(8));
auditDataInfo.setAgainPassAudited(rs.getInt(9));
auditDataInfo.setNoPassAudited(rs.getInt(10));
list.add(auditDataInfo);
}
rs.close();
prest.close();
}catch(ConnectionIsClosedException closedException) {
closedException.printStackTrace();
connection = getConnection();
getOneDayByTypeAuditData(tableName, stat_date,item_type,source_id, ++retryCount);
}catch(SQLException e){
e.printStackTrace();
if(rs != null)
try
{
rs.close();
}catch(SQLException sqlexception) { }
if(prest != null)
try
{
prest.close();
}
catch(SQLException sqlexception1) { }
getOneDayByTypeAuditData(tableName, stat_date,item_type,source_id, ++retryCount);
}catch(Exception e){
if(rs != null)
try
{
rs.close();
}catch(SQLException sqlexception2) { }
if(prest != null)
try
{
prest.close();
}
catch(SQLException sqlexception3) { }
e.printStackTrace();
}
return list;
}
@Override
public List<DepAuditDataInfo> getOneDayByTypeDepAuditData(String tableName,
String stat_date,int item_type,int department, int retryCount) throws Exception {
if(retryCount > 3)
throw new Exception("retry count > 3");
ResultSet rs = null;
PreparedStatement prest = null;
List<DepAuditDataInfo> list = new ArrayList<DepAuditDataInfo>();
try
{
if (null == connection || connection.isClosed()) {
connection = getConnection();
}
String sql = (new StringBuilder("select stat_date,item_type,department_id,incoming_audit_cnt," +
"firstaudited_cnt,againaudited_cnt,passed_audit_cnt,firstpassed_audit_cnt," +
"againpassed_audit_cnt,nopassed_audit_cnt from ")).append(tableName).append(" where stat_date = ? and department_id = ? and item_type = ? ").toString();
prest = connection.prepareStatement(sql);
prest.setString(1, stat_date);
prest.setInt(2, department);
prest.setInt(3, item_type);
rs = prest.executeQuery();
while(rs.next()){
DepAuditDataInfo depAuditDataInfo = new DepAuditDataInfo();
depAuditDataInfo.setStatDate(rs.getString(1));
depAuditDataInfo.setItemType(rs.getInt(2));
depAuditDataInfo.setDepartment(rs.getInt(3));
depAuditDataInfo.setInComing(rs.getInt(4));
depAuditDataInfo.setFirstHasAudited(rs.getInt(5));
depAuditDataInfo.setAgainHasAudited(rs.getInt(6));
depAuditDataInfo.setPassAudited(rs.getInt(7));
depAuditDataInfo.setFirstPassAudited(rs.getInt(8));
depAuditDataInfo.setAgainPassAudited(rs.getInt(9));
depAuditDataInfo.setNoPassAudited(rs.getInt(10));
list.add(depAuditDataInfo);
}
rs.close();
prest.close();
}catch(ConnectionIsClosedException closedException) {
closedException.printStackTrace();
connection = getConnection();
getOneDayByTypeDepAuditData(tableName, stat_date,item_type,department, ++retryCount);
}catch(SQLException e){
e.printStackTrace();
if(rs != null)
try
{
rs.close();
}catch(SQLException sqlexception) { }
if(prest != null)
try
{
prest.close();
}
catch(SQLException sqlexception1) { }
getOneDayByTypeDepAuditData(tableName, stat_date,item_type,department, ++retryCount);
}catch(Exception e){
if(rs != null)
try
{
rs.close();
}catch(SQLException sqlexception2) { }
if(prest != null)
try
{
prest.close();
}
catch(SQLException sqlexception3) { }
e.printStackTrace();
}
return list;
}
//团队成员
public List<DepMemAuditDataInfo> getOneDayByTypeDepMemAuditData(String tableName,
String stat_date,int item_type,int department,int member_id ,int retryCount) throws Exception {
if(retryCount > 3)
throw new Exception("retry count > 3");
ResultSet rs = null;
PreparedStatement prest = null;
List<DepMemAuditDataInfo> list = new ArrayList<DepMemAuditDataInfo>();
try
{
if (null == connection || connection.isClosed()) {
connection = getConnection();
}
String sql = (new StringBuilder("select stat_date,item_type,department_id,member_id,audit_cnt," +
"firstaudited_cnt,againaudited_cnt,firstpassed_audit_cnt," +
"againpassed_audit_cnt,firstnopassed_audit_cnt,nopassed_audit_cnt from ")).append(tableName).append(" where stat_date = ? and department_id = ? and item_type = ? and member_id = ? ").toString();
prest = connection.prepareStatement(sql);
prest.setString(1, stat_date);
prest.setInt(2, department);
prest.setInt(3, item_type);
prest.setInt(4, member_id);
rs = prest.executeQuery();
while(rs.next()){
DepMemAuditDataInfo depMemAuditDataInfo = new DepMemAuditDataInfo();
depMemAuditDataInfo.setStatDate(rs.getString(1));
depMemAuditDataInfo.setItemType(rs.getInt(2));
depMemAuditDataInfo.setDepartment(rs.getInt(3));
depMemAuditDataInfo.setMember_id(rs.getInt(4));
depMemAuditDataInfo.setAudited(rs.getInt(5));
depMemAuditDataInfo.setFirstHasAudited(rs.getInt(6));
depMemAuditDataInfo.setAgainHasAudited(rs.getInt(7));
depMemAuditDataInfo.setFirstPassAudited(rs.getInt(8));
depMemAuditDataInfo.setAgainPassAudited(rs.getInt(9));
depMemAuditDataInfo.setFirstNoPassAudited(rs.getInt(10));
depMemAuditDataInfo.setNoPassAudited(rs.getInt(11));
list.add(depMemAuditDataInfo);
}
rs.close();
prest.close();
}catch(ConnectionIsClosedException closedException) {
closedException.printStackTrace();
connection = getConnection();
getOneDayByTypeDepMemAuditData(tableName, stat_date,item_type,department,member_id, ++retryCount);
}catch(SQLException e){
e.printStackTrace();
if(rs != null)
try
{
rs.close();
}catch(SQLException sqlexception) { }
if(prest != null)
try
{
prest.close();
}
catch(SQLException sqlexception1) { }
getOneDayByTypeDepMemAuditData(tableName, stat_date,item_type,department,member_id, ++retryCount);
}catch(Exception e){
if(rs != null)
try
{
rs.close();
}catch(SQLException sqlexception2) { }
if(prest != null)
try
{
prest.close();
}
catch(SQLException sqlexception3) { }
e.printStackTrace();
}
return list;
}
public static void main(String[] args) throws Exception {
String confDir = "D:/conf_test/configure/client/client_storeservice_conf.properties";
MysqlDao mysqlDao = new MysqlDaoImpl(confDir);
String audit_daily_table = "idl_zq_mty_audit_data_sdt0";
List<AuditDataInfo> list = (List<AuditDataInfo>) mysqlDao.getOneDayByTypeAuditData(audit_daily_table, "2019-05-29", 1,1,1);
for (int i = 0; i < list.size(); i++) {
AuditDataInfo auditDataInfo = list.get(i);
System.out.println(auditDataInfo.getInComing());
}
System.out.println(list.size());
}
}<file_sep>/src/main/java/com/zbcmdata/flink/FlinkApplications/functions/sink/redis/RedisVideoRecommendSink.java
package com.zbcmdata.flink.FlinkApplications.functions.sink.redis;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import com.zbcmdata.flink.FlinkApplications.bean.ItemInfo;
import com.zbcmdata.flink.FlinkApplications.model.recommend.video.VideoOnLineRecommend;
import com.zbcmdata.flink.FlinkApplications.streaming.rongcloudBI.service.dao.impl.MysqlDaoImpl;
public class RedisVideoRecommendSink extends RichSinkFunction<String>{
private static VideoOnLineRecommend videoOnLineRecommend = null;
private static final Log LOGGER = LogFactory.getLog(RedisVideoRecommendSink.class);
@Override
public void invoke(String value) throws Exception {
// TODO Auto-generated method stub
try {
ItemInfo videoInfo = ItemInfo.parseFromJson(value);
boolean result = videoOnLineRecommend.getRecommendVideos(videoInfo);
} catch (Exception e) {
// TODO: handle exception
LOGGER.error("redis sink exception, value: " + value + "\n");
e.printStackTrace();
}
}
@Override
public void open(Configuration configuration)throws Exception{
videoOnLineRecommend = new VideoOnLineRecommend();
LOGGER.info("initial VideoOnLineRecommend............");
super.open(configuration);
}
@Override
public void close()throws Exception{
videoOnLineRecommend.close();
LOGGER.info("close mysql connection server");
}
}
<file_sep>/src/main/java/com/zbcmdata/flink/service/dao/impl/OracleDaoImpl.java
package com.zbcmdata.flink.service.dao.impl;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;
import java.sql.Date;
import org.apache.hadoop.conf.Configuration;
import org.apache.log4j.Logger;
import org.apache.commons.lang.exception.ExceptionUtils;
import com.zbcmdata.flink.service.dao.OracleDao;
import com.zbcmdata.flink.util.PropertiesFileUtil;
import java.text.SimpleDateFormat;
/**
* @author michael.shentu
* @since 2015-05-01
*
* */
public class OracleDaoImpl
implements OracleDao
{
public OracleDaoImpl(String conf)
throws Exception
{
properties = null;
connection = null;
connection = getConnection(conf);
}
public OracleDaoImpl(Configuration conf)
throws Exception
{
properties = null;
connection = null;
connection = getConnection(conf);
}
public OracleDaoImpl()
{
properties = null;
connection = null;
}
public Connection getConnection()
throws Exception
{
Connection connection = null;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
properties = PropertiesFileUtil.load("classpath:configure/client/client_storeservice_conf.properties");
oracle_url = properties.getProperty("db.oracle.jdbcUrl");
oracle_user = properties.getProperty("db.oracle.user");
oracle_passwd = <PASSWORD>.getProperty("db.<PASSWORD>");
schema = properties.getProperty("db.oracle.schema");
connection = DriverManager.getConnection(oracle_url, oracle_user, oracle_passwd);
connection.setAutoCommit(true);
}
catch(Exception e)
{
LOG.error(ExceptionUtils.getFullStackTrace(e));
return null;
}
return connection;
}
public Connection getConnection(String conf)
throws Exception
{
Connection connection = null;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
properties = PropertiesFileUtil.load(conf);
oracle_url = properties.getProperty("db.oracle.jdbcUrl");
oracle_user = properties.getProperty("db.oracle.user");
oracle_passwd = <PASSWORD>("<PASSWORD>");
schema = properties.getProperty("db.oracle.schema");
connection = DriverManager.getConnection(oracle_url, oracle_user, oracle_passwd);
connection.setAutoCommit(true);
}
catch(Exception e)
{
LOG.error(ExceptionUtils.getFullStackTrace(e));
return null;
}
return connection;
}
public Connection getConnection(Configuration conf)
throws Exception
{
Connection connection = null;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
oracle_url = conf.get("db.oracle.jdbcUrl");
oracle_user = conf.get("db.oracle.user");
oracle_passwd = <PASSWORD>.get("<PASSWORD>");
schema = conf.get("db.oracle.schema");
connection = DriverManager.getConnection(oracle_url, oracle_user, oracle_passwd);
connection.setAutoCommit(true);
}
catch(Exception e)
{
LOG.error(ExceptionUtils.getFullStackTrace(e));
return null;
}
return connection;
}
public void setSchema(String schema)
{
this.schema = schema;
}
public String getSchema()
{
return schema;
}
@Override
public void clearContentRecRecordById(String tableName, String id,
int retryCount) throws Exception {
// TODO Auto-generated method stub
if(retryCount > 3)
throw new Exception("retry count > 3");
if(tableName == null)
throw new IllegalArgumentException((new StringBuilder("argument is null, tableName: ")).append(tableName).toString());
PreparedStatement prest = null;
try
{
if(connection == null)
connection = getConnection();
String sql = (new StringBuilder("delete from ")).append(schema).append(".").append(tableName).append(" where text_id = ?").toString();
prest = connection.prepareStatement(sql);
prest.setString(1, id);
prest.executeUpdate();
prest.close();
}
catch(SQLException e)
{
System.out.println(e.getMessage());
LOG.error(ExceptionUtils.getFullStackTrace(e));
try
{
if(prest != null)
prest.close();
}
catch(SQLException e2)
{
LOG.error(ExceptionUtils.getFullStackTrace(e));
}
clearOneUserTopicRecRecord(tableName, id, ++retryCount);
}
catch(Exception e)
{
System.out.println(e.getMessage());
LOG.error(ExceptionUtils.getFullStackTrace(e));
try
{
if(prest != null)
prest.close();
}
catch(SQLException e2)
{
LOG.error(ExceptionUtils.getFullStackTrace(e));
}
clearOneUserTopicRecRecord(tableName, id, ++retryCount);
}
}
@Override
public void clearOneUserTopicRecRecord(String tableName, String uid, int retryCount)
throws Exception
{
if(retryCount > 3)
throw new Exception("retry count > 3");
if(tableName == null)
throw new IllegalArgumentException((new StringBuilder("argument is null, tableName: ")).append(tableName).toString());
PreparedStatement prest = null;
try
{
if(connection == null)
connection = getConnection();
String sql = (new StringBuilder("delete from ")).append(schema).append(".").append(tableName).append(" where userid = ?").toString();
prest = connection.prepareStatement(sql);
prest.setString(1, uid);
prest.executeUpdate();
prest.close();
}
catch(SQLException e)
{
System.out.println(e.getMessage());
LOG.error(ExceptionUtils.getFullStackTrace(e));
try
{
if(prest != null)
prest.close();
}
catch(SQLException e2)
{
LOG.error(ExceptionUtils.getFullStackTrace(e));
}
clearOneUserTopicRecRecord(tableName, uid, ++retryCount);
}
catch(Exception e)
{
System.out.println(e.getMessage());
LOG.error(ExceptionUtils.getFullStackTrace(e));
try
{
if(prest != null)
prest.close();
}
catch(SQLException e2)
{
LOG.error(ExceptionUtils.getFullStackTrace(e));
}
clearOneUserTopicRecRecord(tableName, uid, ++retryCount);
}
}
public void clearOneContentRecRecord(String tableName, String newsId, String recommendId, int retryCount)
throws Exception
{
if(retryCount > 3)
throw new Exception("retry count > 3");
if(tableName == null)
throw new IllegalArgumentException((new StringBuilder("argument is null, tableName: ")).append(tableName).toString());
PreparedStatement prest = null;
try
{
if(connection == null)
connection = getConnection();
String sql = (new StringBuilder("delete from ")).append(schema).append(".").append(tableName).append(" where text_id = ? and similar_text_id = ?").toString();
prest = connection.prepareStatement(sql);
prest.setString(1, newsId);
prest.setString(2, recommendId);
prest.executeUpdate();
prest.close();
}
catch(SQLException e)
{
System.out.println(e.getMessage());
LOG.error(ExceptionUtils.getFullStackTrace(e));
try
{
if(prest != null)
prest.close();
}
catch(SQLException e2)
{
LOG.error(ExceptionUtils.getFullStackTrace(e));
}
clearOneContentRecRecord(tableName, newsId, recommendId, ++retryCount);
}
catch(Exception e)
{
System.out.println(e.getMessage());
LOG.error(ExceptionUtils.getFullStackTrace(e));
try
{
if(prest != null)
prest.close();
}
catch(SQLException e2)
{
LOG.error(ExceptionUtils.getFullStackTrace(e));
}
clearOneContentRecRecord(tableName, newsId, recommendId, ++retryCount);
}
}
public void clearOneWordCountInfo(String tableName, String word, int retryCount)
throws Exception
{
if(retryCount > 3)
throw new Exception("retry count > 3");
if(tableName == null)
throw new IllegalArgumentException((new StringBuilder("argument is null, tableName: ")).append(tableName).toString());
PreparedStatement prest = null;
try
{
if(connection == null)
connection = getConnection();
String sql = (new StringBuilder("delete from ")).append(schema).append(".").append(tableName).append(" where word = ?").toString();
prest = connection.prepareStatement(sql);
prest.setString(1, word);
prest.executeUpdate();
prest.close();
}
catch(SQLException e)
{
System.out.println(e.getMessage());
LOG.error(ExceptionUtils.getFullStackTrace(e));
try
{
if(prest != null)
prest.close();
}
catch(SQLException e2)
{
LOG.error(ExceptionUtils.getFullStackTrace(e));
}
clearOneWordCountInfo(tableName, word, ++retryCount);
}
catch(Exception e)
{
System.out.println(e.getMessage());
LOG.error(ExceptionUtils.getFullStackTrace(e));
try
{
if(prest != null)
prest.close();
}
catch(SQLException e2)
{
LOG.error(ExceptionUtils.getFullStackTrace(e));
}
clearOneWordCountInfo(tableName, word, ++retryCount);
}
}
public void clearAllForRecalculation(String tableName, int retryCount)
throws Exception
{
if(retryCount > 3)
throw new Exception("retry count > 3");
if(tableName == null)
throw new IllegalArgumentException((new StringBuilder("argument is null, tableName: ")).append(tableName).toString());
try
{
if(connection == null)
connection = getConnection();
String sql = (new StringBuilder("truncate table ")).append(schema).append(".").append(tableName).toString();
PreparedStatement prest = connection.prepareStatement(sql);
prest.executeUpdate();
prest.close();
}
catch(SQLException e)
{
System.out.println(e.getMessage());
LOG.error(ExceptionUtils.getFullStackTrace(e));
clearAllForRecalculation(tableName, ++retryCount);
}
catch(Exception e)
{
System.out.println(e.getMessage());
LOG.error(ExceptionUtils.getFullStackTrace(e));
clearAllForRecalculation(tableName, ++retryCount);
}
}
public void updateOneWordCountRecord(String tableName, String word, int totalNum, int retryCount)
throws Exception
{
if(retryCount > 3)
return;
if(tableName == null || word == null)
throw new IllegalArgumentException("word is null!");
if(connection == null)
connection = getConnection();
String sql = "update " + schema + "." + tableName + " set totalNum = ?" +
" where word = ?";
PreparedStatement ps = null;
try
{
ps = connection.prepareStatement(sql);
ps.setInt(1, totalNum);
ps.setString(2, word);
ps.executeUpdate();
ps.close();
}catch(SQLException e)
{
System.out.println(e.getMessage());
LOG.error(ExceptionUtils.getFullStackTrace(e));
if (ps != null) {
ps.close();
}
updateOneWordCountRecord(tableName, word, totalNum, ++retryCount);
}catch(Exception e)
{
System.out.println(e.getMessage());
LOG.error(ExceptionUtils.getFullStackTrace(e));
if (ps != null) {
ps.close();
}
updateOneWordCountRecord(tableName, word, totalNum, ++retryCount);
}
}
public void insertOneWordCountRecord(String tableName, String word, int totalNum, int retryCount)
throws Exception
{
if(retryCount > 3)
return;
if(tableName == null || word == null)
throw new IllegalArgumentException("word is null!");
if(connection == null)
connection = getConnection();
String sql = "insert into " + schema + "." + tableName + " (word,totalNum) values(?,?)";
PreparedStatement ps = null;
try
{
ps = connection.prepareStatement(sql);
ps.setString(1, word);
ps.setInt(2, totalNum);
ps.executeUpdate();
ps.close();
}catch(SQLException e)
{
System.out.println(e.getMessage());
LOG.error(ExceptionUtils.getFullStackTrace(e));
if (ps != null) {
ps.close();
}
insertOneWordCountRecord(tableName, word, totalNum, ++retryCount);
}catch(Exception e)
{
System.out.println(e.getMessage());
LOG.error(ExceptionUtils.getFullStackTrace(e));
if (ps != null) {
ps.close();
}
insertOneWordCountRecord(tableName, word, totalNum, ++retryCount);
}
}
private static Logger LOG = Logger.getLogger(OracleDaoImpl.class);
private String schema;
private Properties properties;
private Connection connection;
private String oracle_url;
private String oracle_user;
private String oracle_passwd;
}
<file_sep>/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zbcmdata.flink</groupId>
<artifactId>FlinkApplications</artifactId>
<version>v1.0</version>
<packaging>jar</packaging>
<name>FlinkApplications</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<flink.version>1.6.0</flink.version>
<scala.binary.version>2.11</scala.binary.version>
<scala.version>2.11.12</scala.version>
<drools.version>6.5.0.Final</drools.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-streaming-java_2.11</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-cep_2.11</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-streaming-scala_2.11</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>${scala.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-table_2.11</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-streaming-java_2.11</artifactId>
<version>${flink.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-connector-kafka-0.8_2.11</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-hbase_2.11</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-connector-filesystem_2.11</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-jdbc</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>com.hankcs</groupId>
<artifactId>hanlp</artifactId>
<version>1.7.2</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-core</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-clients_2.11</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>172.16.58.3</version>
</dependency>
<!-- drools -->
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-compiler</artifactId>
<version>${drools.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.drools/drools-core -->
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-core</artifactId>
<version>${drools.version}</version>
</dependency>
<!-- hbase-client -->
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>1.2.6</version>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<dependency>
<groupId>org.htmlparser</groupId>
<artifactId>htmlparser</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>jdk.tools</groupId>
<artifactId>jdk.tools</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-connector-elasticsearch5_2.11</artifactId>
<version>1.6.0</version>
</dependency>
</dependencies>
<profiles>
<profile>
<id>test</id>
<properties>
<package.environment>test</package.environment>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>product</id>
<properties>
<package.environment>product</package.environment>
</properties>
</profile>
</profiles>
<build>
<resources>
<resource>
<directory>src/resources/${package.environment}</directory>
<includes>
<include>**/*.properties</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<!-- Use the shade plugin to build a fat jar for the kafka example -->
<!-- Java Compiler -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- Scala Compiler -->
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<id>fat-jar-kafka-example</id>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadeTestJar>false</shadeTestJar>
<shadedArtifactAttached>false</shadedArtifactAttached>
<createDependencyReducedPom>false</createDependencyReducedPom>
<finalName>mtyBiSystem-flink-application2</finalName>
<filters>
<filter>
<artifact>*</artifact>
<includes>
<include>oracle/**</include>
<include>com/zbcmdata/**</include>
<include>org/apache/flink/streaming/**</include>
<include>org/apache/kafka/**</include>
<include>org/apache/curator/**</include>
<include>org/apache/jute/**</include>
<include>org/I0Itec/**</include>
<include>jline/**</include>
<include>com/yammer/**</include>
<include>kafka/**</include>
<include>com/alibaba/fastjson/**</include>
<include>com/hankcs/hanlp/**</include>
<include>org/apache/flink/flink-cep/**</include>
<include>org/apache/flink/cep/**</include>
</includes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
| bbdc9230c2cb726e311d430ddbd4dd2bde20478e | [
"Markdown",
"Java",
"Maven POM",
"INI"
] | 31 | Java | ZBNLP/FlinkApplications | fcc582f643f49dcf856189ba94301bc96fc37fd7 | 91bfddfa566b82b9e6106fb85f97eb67b6b2562a |
refs/heads/master | <file_sep># HelloWorld
First App made for android
<file_sep>package cbpos1989.com.helloworld;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import cbpos1989.com.person.Person;
import cbpos1989.com.sqlitedatabase.DBHandler;
public class PersonActivity extends AppCompatActivity {
private Person person;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_person);
Intent intent = getIntent();
String name = intent.getStringExtra("PERSON_NAME");
String phone = intent.getStringExtra("PERSON_PHONE");
String email = intent.getStringExtra("PERSON_EMAIL");
int id = intent.getIntExtra("PERSON_ID",1);
TextView name_field = (TextView) findViewById(R.id.person_name_field);
TextView phone_field = (TextView) findViewById(R.id.person_phone_field);
TextView email_field = (TextView) findViewById(R.id.person_email_field);
name_field.setText(name_field.getText().toString() + name);
phone_field.setText(phone_field.getText().toString() + phone);
email_field.setText(email_field.getText().toString() + email);
person = new Person(id,name,phone,email);
}
public void onRemoveClicked(View view){
DBHandler dbHandler = new DBHandler(getApplicationContext());
if (person != null) {
dbHandler.removePerson(person.getId());
setResult(1);
finish();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_person, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
<file_sep>package cbpos1989.com.person;
/**
* Class to hold state and behaviour for a Person object.
*
* Created by <NAME> on 07/10/2015.
*/
public class Person {
private int id;
private String name;
private String phoneNumber;
private String email;
public Person(){
this(0,null,null,null);
}
public Person(int id, String name, String phoneNumber, String email) {
setId(id);
setName(name);
setPhoneNumber(phoneNumber);
setEmail(email);
}
public Person(String name, String phoneNumber, String email){
setName(name);
setPhoneNumber(phoneNumber);
setEmail(email);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString(){
return getName();
}
}
<file_sep>package cbpos1989.com.helloworld;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import cbpos1989.com.person.Person;
import cbpos1989.com.sqlitedatabase.DBHandler;
public class AddPersonActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_person);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_add_person, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onSubmitClicked(View view){
EditText nameField = (EditText) findViewById(R.id.enter_name);
EditText phoneField = (EditText) findViewById(R.id.enter_phone);
EditText emailField = (EditText) findViewById(R.id.enter_email);
final Person person = new Person(nameField.getText().toString(),phoneField.getText().toString(),emailField.getText().toString());
new Thread(new Runnable() {
@Override
public void run() {
DBHandler dbHandler = new DBHandler(getApplicationContext());
dbHandler.addPerson(person);
}
}).start();
setResult(1);
finish();
}
}
<file_sep>package cbpos1989.com.sqlitedatabase;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by <NAME> on 07/10/2015.
*/
public class DBOpenHelper extends SQLiteOpenHelper{
public static final String DATABASE_NAME = "person_database";
public static final int DATABASE_VERSION = 1;
public static final String TEXT_TYPE = " TEXT";
public static final String SQL_CREATE_PERSON_TABLE =
"CREATE TABLE " + DBFeederContract.PersonTable.TABLE_NAME + " ("
+ DBFeederContract.PersonTable._ID + " INTEGER PRIMARY KEY,"
+ DBFeederContract.PersonTable.COLUMN_NAME + TEXT_TYPE + ","
+ DBFeederContract.PersonTable.COLUMN_PHONE_NUMBER + TEXT_TYPE + ","
+ DBFeederContract.PersonTable.COLUMN_EMAIL + TEXT_TYPE + ")";
public DBOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_PERSON_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
| 4ce89628a073ac19547bd35c1db4dbedbfbf4e22 | [
"Markdown",
"Java"
] | 5 | Markdown | cbpos1989/HelloWorld | d91eb43abbf596f33d9500fe8e3207a315a3f6da | 12ab6f988efed2e4c345ad80026238aeddc4a3b5 |
refs/heads/master | <file_sep>//const mongoose = require("mongoose");
//const Waterwalk = require("../models/waterwalk");
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
function validatePhone(number) {
var re = /^\d{10}$/;
return re.test(number);
}
function validateName(name) {
var re = /^[a-zA-Z ]+$/;
return re.test(name);
}
exports.verifyData = (req, res, next) => {
const { email, phone, input } = req.body;
let validEmail = validateEmail(email);
let validPhone = validatePhone(phone);
let validName = validateName(input);
if (validName) {
if (validEmail) {
if (validPhone) {
res.status(201).json({
success: true,
message: "Proper data form was given",
email,
phone,
name: input
});
} else {
res.status(500).json({
message: `Invalid Phonenumber ${phone}`
});
}
} else {
res.status(500).json({
message: `Invalid email ${email}`
});
}
} else {
res.status(500).json({
message: `Invalid name ${input}`
});
}
};
| 1d513be28e0804242722ef7fac0d278e646b8eba | [
"JavaScript"
] | 1 | JavaScript | Ultraman82/REST_API_NODEJS | b5db9d8c7e7fa9f7dd397a784f50e902535fd986 | 192e0be61a70806922e93c87f982af131675f1fc |
refs/heads/master | <repo_name>punkish/winston-better-sqlite3<file_sep>/README.md
# winston-better-sqlite3
*aka wbs*
`sqite3` Transport for [Winston](https://github.com/winstonjs/winston)
## Install
```bash
$ npm install winston-better-sqlite3
```
## Use
```js
const winston = require('winston');
const wbs = require('winston-better-sqlite3');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new wbs({
// 'db' is required, and should include the full
// path to the sqlite3 database file on the disk
db: '<name of sqlite3 database file>',
// The name of the table to use in the database.
// Defaults to 'log'
table: 'log',
// A list of the log params to log. Defaults to
// ['level, 'message']. These params are used as
// columns in the sqlite3 table
params: ['level', 'resource', 'query', 'message']
})
]
});
```
There are a couple of `sqlite3` transports for Winston out there, but this one is different. For one, it uses Josuha Wise's most excellent [better-sqlite3](https://www.npmjs.com/package/better-sqlite3) package. Second, in my biased opinion, `wbs` is also better because it uses no ORMs or any such middleware. It is just a plain, no-nonsense transport that writes the logs to a `sqlite3` database. You have to provide the name of (and path to) the database file and optionally the table name (defaults to `log`), but the module creates the table (if it doesn't already exist) with the following four columns by default
```sql
CREATE TABLE IF NOT EXISTS log (
id INTEGER PRIMARY KEY,
timestamp INTEGER DEFAULT (strftime('%s','now')),
level TEXT,
message TEXT
);
```
Later on, in your program where you want to log something
```js
// the following two messages will be logged
logger.log({
level: 'info',
resource: 'collaborators',
query: 'q=punkish',
message: 'searching for folks'
});
logger.log({
level: 'error',
resource: 'collaboratoradoras',
query: 'q=normal',
message: 'searching for state'
});
// the following message will not be logged because
// its level is less important than the log level
logger.log({
level: 'verbose',
resource: 'funding',
query: 'q=normal&something',
message: 'searching for habbine'
});
```
**Note:** The user has to provide only the name of the `sqlite3` database file. The module will create a database if it doesn't already exist (as `sqlite3` always does), and will create a table of a given name (`log` by default) inside the database if the table doesn't already exist.
The `id` and `timestamp` columns are automatically inserted by `sqlite3`. The user can provide whatever others columns needed for tracking logging info. For example, I use `level`, `resource`, `query` and `message` in one of my projects (as shown in the example above). All logging params are stored in columns of datatype `TEXT`.
<file_sep>/index.js
const Transport = require('winston-transport');
const Database = require('better-sqlite3');
// Inherit from `winston-transport` so you can take advantage
// of the base functionality and `.exceptions.handle()`.
//
module.exports = class Sqlite3 extends Transport {
constructor(options) {
super(options);
if (!options.hasOwnProperty('db')) {
throw new Error('"db" is required');
}
this.db = new Database(options.db);
this.params = options.params || ['level', 'message'];
const table = options.table || 'log';
// the 'log' table always has 'id' and 'timestamp'
const cols = [
"id INTEGER PRIMARY KEY",
"timestamp INTEGER DEFAULT (strftime('%s','now'))"
];
// add user-provided columns to the table and create the table
this.params.forEach(p => cols.push(`${p} TEXT`));
this.db.prepare(`CREATE TABLE IF NOT EXISTS ${table} (${cols.join(', ')})`).run();
// prepare the insert statement to be used while logging
this.insert = this.db.prepare(`INSERT INTO ${table} (${this.params.join(', ')}) VALUES (${this.params.map(p => `@${p}`).join(', ')})`);
}
log(info, callback) {
const logparams = Object.assign({}, info);
setImmediate(() => this.emit('logged', info));
// Perform the writing to the remote service
this.insert.run(logparams);
callback();
}
};<file_sep>/index.d.ts
/** Declaration file generated by dts-gen */
declare module 'winston-better-sqlite3';
declare class winston_better_sqlite3 {
constructor(...args: any[]);
log(...args: any[]): void;
}
declare namespace winston_better_sqlite3 {
class LegacyTransportStream {
constructor(options: any);
close(): void;
}
}
| 7d22957c7748bbffa50c2ca26eb35bff4a253886 | [
"Markdown",
"TypeScript",
"JavaScript"
] | 3 | Markdown | punkish/winston-better-sqlite3 | 30625d8043559858257358277cca6faa3485312e | 96a8700d8cc344a9c3de5958954e6514a1c492cd |
refs/heads/master | <repo_name>fandrade8/Pong<file_sep>/settings.py
class Settings:
def __init__(self):
self.FPS = 200
self.window_width = 400
self.window_height = 300
self.line_thickness = 10
self.paddle_size = 50
self.paddle_offset = 20
self.blk = (0, 0, 0)
self.wht = (255, 255, 255)
<file_sep>/Ping_Pong.py
import random
import sys
import pygame
from pygame.locals import *
from settings import Settings
def draw_paddle(paddle, screen):
settings = Settings()
if paddle.bottom > settings.window_height - settings.line_thickness:
paddle.bottom = settings.window_height - settings.line_thickness
elif paddle.top < settings.line_thickness:
paddle.top = settings.line_thickness
pygame.draw.rect(screen, settings.wht, paddle)
def draw_ball(ball, screen):
settings = Settings()
pygame.draw.rect(screen, settings.wht, ball)
def arena(screen):
settings = Settings()
screen.fill((0, 0, 0))
pygame.draw.rect(screen, settings.wht,
((0, 0), (settings.window_width, settings.window_height)),
settings.line_thickness * 2)
pygame.draw.line(screen, settings.wht, ((settings.window_width / 2), 0),
((settings.window_width / 2), settings.window_height),
(settings.line_thickness // 4))
def ball_movement(ball, ball_dir_x, ball_dir_y):
ball.x += ball_dir_x
ball.y += ball_dir_y
return ball
def edge_collision(ball, ball_dir_x, ball_dir_y):
settings = Settings()
if ball.top == settings.line_thickness or ball.bottom == (settings.window_height - settings.line_thickness):
ball_dir_y = ball_dir_y * -1
if ball.left == settings.line_thickness or ball.right == (settings.window_width - settings.line_thickness):
ball_dir_x = ball_dir_x * -1
return ball_dir_x, ball_dir_y
def ai(ball, ball_dir_x, paddle2):
st = Settings()
if ball_dir_x == -1:
if paddle2.centery < (st.window_height/2):
paddle2.y += 1
elif paddle2.centery > (st.window_height/2):
paddle2.y -= 1
elif ball_dir_x == 1:
if paddle2.centery < ball.y:
paddle2.y += 1
else:
paddle2.y -= 1
return paddle2
def ball_collision(ball, paddle1, paddle2, ball_dir_x):
if ball_dir_x == -1 and paddle1.right == ball.left and paddle1.top < ball.top and paddle1.bottom > ball.bottom:
return -1
elif ball_dir_x == 1 and paddle2.left == ball.right and paddle2.top < ball.top and paddle2.bottom > ball.bottom:
return -1
else:
return 1
def get_score(paddle1, ball, score, ball_dir_x):
st = Settings()
if ball.left == st.line_thickness:
return 0
elif ball_dir_x == -1 and paddle1.right == ball.left and paddle1.top < ball.top and paddle1.bottom > ball.bottom:
score += 1
return score
elif ball.right == st.window_width - st.line_thickness:
score += 5
else:
return score
def display_score(score, screen):
st = Settings()
resultSurf = BASICFONT.render("Score = %s" % score, True, st.wht)
result_Rect = resultSurf.get_rect()
result_Rect.topleft = (st.window_width - 150, 25)
screen.blit(resultSurf, result_Rect)
def main():
pygame.init()
settings = Settings()
global BASICFONT, BASICFONTSIZE
BASICFONTSIZE = 20
BASICFONT = pygame.font.Font("freesansbold.ttf", BASICFONTSIZE)
fps_clock = pygame.time.Clock()
screen = pygame.display.set_mode((settings.window_width, settings.window_height))
pygame.display.set_caption("Pong")
ball_x = settings.window_width / 2 - settings.line_thickness / 2
ball_y = settings.window_height / 2 - settings.line_thickness / 2
p1_pos = (settings.window_height - settings.paddle_size) / 2
p2_pos = (settings.window_height - settings.paddle_size) / 2
score = 0
paddle1 = pygame.Rect(settings.paddle_offset, p1_pos, settings.line_thickness, settings.paddle_size)
paddle2 = pygame.Rect(settings.window_width - settings.paddle_offset - settings.line_thickness, p2_pos,
settings.line_thickness, settings.paddle_size)
ball = pygame.Rect(ball_x, ball_y, settings.line_thickness, settings.line_thickness)
ball_dir_x = -1
ball_dir_y = -1
arena(screen)
draw_paddle(paddle1, screen)
draw_paddle(paddle2, screen)
draw_ball(ball, screen)
pygame.mouse.set_visible(0)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEMOTION:
mouse_x, mouse_y = event.pos
paddle1.y = mouse_y
arena(screen)
draw_paddle(paddle1, screen)
draw_paddle(paddle2, screen)
draw_ball(ball, screen)
ball = ball_movement(ball, ball_dir_x, ball_dir_y)
ball_dir_x, ball_dir_y = edge_collision(ball, ball_dir_x, ball_dir_y)
score = get_score(paddle1, ball, score, ball_dir_x)
ball_dir_x = ball_dir_x * ball_collision(ball, paddle1, paddle2, ball_dir_x)
paddle2 = ai(ball, ball_dir_x, paddle2)
display_score(score, screen)
pygame.display.update()
fps_clock.tick(settings.FPS)
if __name__ == "__main__":
main()
| 064cca88c2537c4858f3be6cdfc755f9ecfdd298 | [
"Python"
] | 2 | Python | fandrade8/Pong | 65b09528e9c3748cb8e6272fee90fa6705c0f7c6 | dd8b93a48d9267a0008f18cc3864222754f0b1d3 |
refs/heads/master | <repo_name>Befors/demo-project<file_sep>/src/main/java/com/haulmont/demoproject/mapper/CreditMapper.java
package com.haulmont.demoproject.mapper;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingTarget;
import com.haulmont.demoproject.dto.request.CreateCreditDtoRequest;
import com.haulmont.demoproject.dto.request.UpdateCreditDtoRequest;
import com.haulmont.demoproject.dto.response.CreditDtoResponse;
import com.haulmont.demoproject.model.Credit;
import java.util.List;
@Mapper
public interface CreditMapper {
@Mapping(target = "active", constant = "true")
Credit toEntity(CreateCreditDtoRequest dtoRequest);
CreditDtoResponse toDto(Credit credit);
Credit update(@MappingTarget Credit credit, UpdateCreditDtoRequest dtoRequest);
List<CreditDtoResponse> toDtoList(List<Credit> credits);
}
<file_sep>/src/main/java/com/haulmont/demoproject/service/SecurityService.java
package com.haulmont.demoproject.service;
import org.springframework.security.core.userdetails.UserDetails;
public interface SecurityService {
void autoLogin(UserDetails userDetails, String password);
}
<file_sep>/src/main/java/com/haulmont/demoproject/model/Client.java
package com.haulmont.demoproject.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.haulmont.demoproject.model.enums.Role;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.UUID;
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Client implements Serializable, UserDetails, Activated {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;
private String firstName;
private String lastName;
private String patronymic;
private String phoneNumber;
private String email;
private String password;
private String passportSeries;
@Enumerated(EnumType.STRING)
private Role role;
private boolean active;
@OneToMany(mappedBy = "client", cascade = CascadeType.ALL)
@EqualsAndHashCode.Exclude
private Set<CreditOffer> creditOffers;
public void addCreditOffer(CreditOffer creditOffer) {
creditOffers.add(creditOffer);
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return Collections.singletonList(role);
}
@Override
public String getPassword() {
return <PASSWORD>;
}
@Override
public String getUsername() {
return email;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return active;
}
}
<file_sep>/src/main/java/com/haulmont/demoproject/dto/response/PaymentDtoResponse.java
package com.haulmont.demoproject.dto.response;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
import java.util.UUID;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PaymentDtoResponse {
private UUID id;
private LocalDate date;
private double total;
private double bodySum;
private double interestSum;
}
<file_sep>/src/main/java/com/haulmont/demoproject/model/Activated.java
package com.haulmont.demoproject.model;
public interface Activated {
boolean isActive();
}
<file_sep>/README.md
### How to start the app
1. Build project using command `mvn clean install`
1. Start application with command `java -jar {project.location}/haulmont-demo-project/target/demo-project-0.0.1-SNAPSHOT.jar`
1. Open http://localhost:8080 in a web browser
### Credentials
1. Admin credentials:
email: <EMAIL>
password: <PASSWORD>
1. Client credentials:
email: <EMAIL>
password: <PASSWORD>
<file_sep>/src/main/java/com/haulmont/demoproject/api/BankRestController.java
package com.haulmont.demoproject.api;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.haulmont.demoproject.dto.request.CreateBankDtoRequest;
import com.haulmont.demoproject.dto.request.UpdateBankDtoRequest;
import com.haulmont.demoproject.dto.response.BankDtoResponse;
import com.haulmont.demoproject.service.BankService;
import javax.validation.Valid;
import java.util.UUID;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/banks")
@PreAuthorize("hasRole('ADMIN')")
public class BankRestController {
private final BankService bankService;
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public UUID create(@Valid @RequestBody CreateBankDtoRequest dtoRequest) {
BankDtoResponse dtoResponse = bankService.create(dtoRequest);
return dtoResponse.getId();
}
@PutMapping("/{id}")
public void update(@Valid @RequestBody UpdateBankDtoRequest dtoRequest,
@PathVariable UUID id) {
bankService.update(dtoRequest, id);
}
@PostMapping("/{id}/activity")
public void updateActivity(@PathVariable UUID id) {
bankService.updateActivity(id);
}
}
<file_sep>/src/main/java/com/haulmont/demoproject/mapper/CreditOfferMapper.java
package com.haulmont.demoproject.mapper;
import org.mapstruct.DecoratedWith;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import com.haulmont.demoproject.dto.request.CreateCreditOfferDtoRequest;
import com.haulmont.demoproject.dto.response.CreditOfferDtoResponse;
import com.haulmont.demoproject.model.Bank;
import com.haulmont.demoproject.model.Client;
import com.haulmont.demoproject.model.Credit;
import com.haulmont.demoproject.model.CreditOffer;
import com.haulmont.demoproject.service.BankService;
import com.haulmont.demoproject.service.ClientService;
import com.haulmont.demoproject.service.CreditService;
import java.time.LocalDate;
import java.util.List;
@Mapper(uses = {ClientService.class, CreditService.class, BankService.class,
PaymentMapper.class}, imports = LocalDate.class)
@DecoratedWith(CreditOfferDecorator.class)
public interface CreditOfferMapper {
@Mappings({
@Mapping(target = "id", ignore = true),
@Mapping(target = "client", source = "client"),
@Mapping(target = "bank", source = "bank"),
@Mapping(target = "credit", source = "credit"),
@Mapping(target = "startDate", expression = "java(LocalDate.now())")
})
CreditOffer toEntity(CreateCreditOfferDtoRequest dtoRequest, Client client,
Bank bank, Credit credit);
@Mapping(target = "bankName", expression = "java(creditOffer.getBank().getName())")
CreditOfferDtoResponse toDto(CreditOffer creditOffer);
List<CreditOfferDtoResponse> toDtoList(List<CreditOffer> creditOffers);
}
<file_sep>/src/main/java/com/haulmont/demoproject/mvc/CreditController.java
package com.haulmont.demoproject.mvc;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.SortDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.haulmont.demoproject.service.CreditService;
@Controller
@RequestMapping("/admin/credits")
@RequiredArgsConstructor
public class CreditController {
private final CreditService creditService;
@GetMapping
public String getAll(Model model, @SortDefault({"limit", "interestRate"}) Sort sort) {
model.addAttribute("credits", creditService.findAll(sort));
return "credits";
}
}
<file_sep>/src/main/java/com/haulmont/demoproject/dto/response/BankDtoResponse.java
package com.haulmont.demoproject.dto.response;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import com.haulmont.demoproject.model.Credit;
import java.util.Set;
import java.util.UUID;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BankDtoResponse {
private UUID id;
private String name;
private Set<Credit> credits;
}
<file_sep>/src/main/java/com/haulmont/demoproject/mapper/CreditOfferDecorator.java
package com.haulmont.demoproject.mapper;
import org.springframework.beans.factory.annotation.Autowired;
import com.haulmont.demoproject.dto.request.CreateCreditOfferDtoRequest;
import com.haulmont.demoproject.model.*;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public abstract class CreditOfferDecorator implements CreditOfferMapper {
@Autowired
private CreditOfferMapper delegate;
@Override
public CreditOffer toEntity(CreateCreditOfferDtoRequest dtoRequest, Client client,
Bank bank, Credit credit) {
CreditOffer creditOffer = delegate.toEntity(dtoRequest, client, bank, credit);
LocalDate startDate = creditOffer.getStartDate();
LocalDate endDate = creditOffer.getEndDate();
double total = creditOffer.getTotal();
int numberOfMonths = (int) ChronoUnit.MONTHS.between(startDate, endDate);
double interestRate = creditOffer.getCredit().getInterestRate() / 100 / numberOfMonths;
double bodySum = total / numberOfMonths;
Queue<Double> interestSums = Stream.iterate(total, currTotal -> currTotal - bodySum)
.limit(numberOfMonths)
.map(currTotal -> currTotal * interestRate)
.collect(Collectors.toCollection(LinkedList::new));
List<Payment> payments = Stream.iterate(startDate.plusMonths(1),
date -> date.compareTo(endDate) <= 0,
date -> date.plusMonths(1))
.map(date -> Payment.builder()
.creditOffer(creditOffer)
.date(date)
.total(interestSums.element() + bodySum)
.bodySum(bodySum)
.interestSum(interestSums.remove())
.build())
.collect(Collectors.toList());
creditOffer.setPayments(payments);
return creditOffer;
}
}
<file_sep>/src/main/java/com/haulmont/demoproject/repository/BankRepository.java
package com.haulmont.demoproject.repository;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import com.haulmont.demoproject.model.Bank;
import java.util.List;
import java.util.UUID;
public interface BankRepository extends JpaRepository<Bank, UUID> {
List<Bank> findAllByActiveIsTrue(Sort sort);
}
<file_sep>/src/main/java/com/haulmont/demoproject/service/CreditOfferService.java
package com.haulmont.demoproject.service;
import org.springframework.data.domain.Sort;
import com.haulmont.demoproject.dto.request.CreateCreditOfferDtoRequest;
import com.haulmont.demoproject.dto.response.CreditOfferDtoResponse;
import com.haulmont.demoproject.model.Client;
import com.haulmont.demoproject.model.CreditOffer;
import java.util.Collection;
public interface CreditOfferService {
CreditOffer create(CreateCreditOfferDtoRequest dtoRequest, Client client);
Collection<CreditOfferDtoResponse> findAllByClient(Client client, Sort sort);
}
<file_sep>/src/main/java/com/haulmont/demoproject/model/enums/Role.java
package com.haulmont.demoproject.model.enums;
import org.springframework.security.core.GrantedAuthority;
public enum Role implements GrantedAuthority {
CLIENT, ADMIN;
@Override
public String getAuthority() {
return "ROLE_" + toString();
}
}
<file_sep>/src/main/java/com/haulmont/demoproject/api/CreditRestController.java
package com.haulmont.demoproject.api;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.haulmont.demoproject.dto.request.CreateCreditDtoRequest;
import com.haulmont.demoproject.dto.request.UpdateCreditDtoRequest;
import com.haulmont.demoproject.service.CreditService;
import javax.validation.Valid;
import java.util.UUID;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/credits")
@PreAuthorize("hasRole('ADMIN')")
public class CreditRestController {
private final CreditService creditService;
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public void create(@Valid @RequestBody CreateCreditDtoRequest dtoRequest) {
creditService.create(dtoRequest);
}
@PutMapping("/{id}")
public void update(@Valid @RequestBody UpdateCreditDtoRequest dtoRequest,
@PathVariable UUID id) {
creditService.update(dtoRequest, id);
}
@PostMapping("/{id}/activity")
public void updateActivity(@PathVariable UUID id) {
creditService.updateActivity(id);
}
}
<file_sep>/src/main/java/com/haulmont/demoproject/service/impl/CreditServiceImpl.java
package com.haulmont.demoproject.service.impl;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.haulmont.demoproject.dto.request.CreateCreditDtoRequest;
import com.haulmont.demoproject.dto.request.UpdateCreditDtoRequest;
import com.haulmont.demoproject.dto.response.CreditDtoResponse;
import com.haulmont.demoproject.mapper.CreditMapper;
import com.haulmont.demoproject.model.Credit;
import com.haulmont.demoproject.repository.CreditRepository;
import com.haulmont.demoproject.service.CreditService;
import java.util.Collection;
import java.util.Set;
import java.util.UUID;
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class CreditServiceImpl implements CreditService {
private final CreditRepository creditRepository;
private final CreditMapper creditMapper;
@Override
@Transactional
public CreditDtoResponse create(CreateCreditDtoRequest dtoRequest) {
Credit credit = creditMapper.toEntity(dtoRequest);
return creditMapper.toDto(creditRepository.save(credit));
}
@Override
@Transactional
public CreditDtoResponse update(UpdateCreditDtoRequest dtoRequest, UUID id) {
Credit credit = findCreditById(id);
creditMapper.update(credit, dtoRequest);
return creditMapper.toDto(creditRepository.save(credit));
}
@Override
public Set<Credit> findAllByIds(Iterable<UUID> ids) {
return creditRepository.findAllActiveByIds(ids);
}
@Override
public Credit findByIdLocal(UUID id) {
return findCreditById(id);
}
@Override
public Collection<CreditDtoResponse> findAll(Sort sort) {
return creditMapper.toDtoList(creditRepository.findAllByActiveIsTrue(sort));
}
@Override
@Transactional
public CreditDtoResponse updateActivity(UUID id) {
Credit credit = findCreditById(id);
credit.setActive(!credit.isActive());
return creditMapper.toDto(creditRepository.save(credit));
}
private Credit findCreditById(UUID id) {
return creditRepository.findById(id)
.orElseThrow();
}
}
<file_sep>/src/main/java/com/haulmont/demoproject/model/CreditOffer.java
package com.haulmont.demoproject.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.List;
import java.util.UUID;
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CreditOffer implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;
@ManyToOne
@JoinColumn(name = "client_id")
private Client client;
@ManyToOne
@JoinColumn(name = "credit_id")
private Credit credit;
@ManyToOne
@JoinColumn(name = "bank_id")
private Bank bank;
private double total;
private LocalDate startDate;
private LocalDate endDate;
@OneToMany(mappedBy = "creditOffer", cascade = CascadeType.ALL)
@EqualsAndHashCode.Exclude
private List<Payment> payments;
@PrePersist
public void prePersist() {
bank.addClient(client);
}
}
<file_sep>/src/main/java/com/haulmont/demoproject/service/impl/SecurityServiceImpl.java
package com.haulmont.demoproject.service.impl;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import com.haulmont.demoproject.service.SecurityService;
@Service
@RequiredArgsConstructor
public class SecurityServiceImpl implements SecurityService {
private final AuthenticationManager authenticationManager;
@Override
public void autoLogin(UserDetails userDetails, String password) {
UsernamePasswordAuthenticationToken token =
new UsernamePasswordAuthenticationToken(userDetails, password,
userDetails.getAuthorities());
authenticationManager.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(token);
}
}
<file_sep>/src/main/java/com/haulmont/demoproject/dto/request/CreateClientDtoRequest.java
package com.haulmont.demoproject.dto.request;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CreateClientDtoRequest {
@NotBlank
@Size(max = 50)
private String firstName;
@NotBlank
@Size(max = 100)
private String lastName;
@NotBlank
@Size(max = 100)
private String patronymic;
@NotBlank
@Pattern(regexp = "[\\d]{11}")
private String phoneNumber;
@NotBlank
@Size(max = 255)
private String email;
@NotBlank
@Size(min = 6, max = 50)
private String password;
@NotBlank
@Pattern(regexp = "[\\d]{6}")
private String passportSeries;
}
<file_sep>/src/main/java/com/haulmont/demoproject/repository/ClientRepository.java
package com.haulmont.demoproject.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.haulmont.demoproject.model.Client;
import java.util.Optional;
import java.util.UUID;
public interface ClientRepository extends JpaRepository<Client, UUID> {
Optional<Client> findByEmail(String email);
}
<file_sep>/src/main/resources/application.properties
spring.datasource.driver-class-name=org.hsqldb.jdbc.JDBCDriver
spring.datasource.url=jdbc:hsqldb:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=
spring.liquibase.change-log=classpath:/db.changelog/db.changelog-master.xml
<file_sep>/src/main/java/com/haulmont/demoproject/config/SecurityConfig.java
package com.haulmont.demoproject.config;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.haulmont.demoproject.model.Client;
import com.haulmont.demoproject.model.enums.Role;
import javax.servlet.http.Cookie;
import java.util.UUID;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final UserDetailsService userDetailsService;
private static final String USERNAME_PARAMETER = "email";
private static final String CLIENT_ID_COOKIE_NAME = "uuid";
public SecurityConfig(@Lazy @Qualifier("clientServiceImpl") UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
@Override
@SneakyThrows
protected void configure(HttpSecurity http) {
http
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/admin/**").hasRole(Role.ADMIN.name())
.antMatchers("/login", "/registration").anonymous()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.usernameParameter(USERNAME_PARAMETER)
.successHandler(((httpServletRequest, httpServletResponse, authentication) -> {
UUID id = ((Client) authentication.getPrincipal()).getId();
httpServletResponse.addCookie(new Cookie(CLIENT_ID_COOKIE_NAME, id.toString()));
httpServletResponse.sendRedirect("/");
}))
.and()
.logout()
.deleteCookies(CLIENT_ID_COOKIE_NAME)
.clearAuthentication(true)
.invalidateHttpSession(true);
}
@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
@Bean
@Override
@SneakyThrows
public AuthenticationManager authenticationManagerBean() {
return super.authenticationManagerBean();
}
@Override
@SneakyThrows
protected void configure(AuthenticationManagerBuilder auth) {
auth.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
}
| 613e7e2fa82af85a50e45a5cd78485d6ad3e464f | [
"Markdown",
"Java",
"INI"
] | 22 | Java | Befors/demo-project | 0bf261c5b03c6672727e9d9d78a20008bb2c2194 | b7649eb6187332e24d4dc4353f2bc35b4ec33d16 |
refs/heads/master | <repo_name>LailaZou/TestUnitaire1<file_sep>/exo3/Repositories/EtudiantRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using exo3.Models;
namespace exo3.Repositories
{
public class EtudiantRepository : IEtudiantRepository
{
private EcoleEntities db = new EcoleEntities();
public void CreateNewEtudiant(etudiant etud)
{
db.etudiants.Add(etud);
db.SaveChanges();
}
public IEnumerable<etudiant> GetAllEtudiant()
{
return db.etudiants.ToList();
}
}
}<file_sep>/Exo2/Service/IService1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exo2.Service
{
public interface IService1
{
int GetDonnee(int cle);
}
}
<file_sep>/Exo2/Service/Service1Imp.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Exo2.Service
{
public class Service1Imp:IService1
{
private static Dictionary<int, int> ValeurParametre = new Dictionary<int, int>
{
{1,10 },
{3,100},
{4,27 },
{5,31 }
};
public int GetDonnee(int cle)
{
return (ValeurParametre.ContainsKey(cle) ? ValeurParametre[cle] : 1);
}
}
}<file_sep>/Exo2/Service/Service2Imp.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Exo2.Service
{
public class Service2Imp : IService2
{
IService1 S1;
public Service2Imp(IService1 s1)
{
S1 = s1;
}
public int calcul(int cle, int x)
{
return x * (S1.GetDonnee(cle));
}
}
}<file_sep>/exo3/Repositories/IEtudiantRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using exo3.Models;
namespace exo3.Repositories
{
public interface IEtudiantRepository
{
IEnumerable<etudiant> GetAllEtudiant();
void CreateNewEtudiant(etudiant etud);
}
}
<file_sep>/exo3.Tests/Controllers/UnitTest1.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using exo3.Repositories;
using exo3.Controllers;
using NSubstitute;
using System.Web.Mvc;
using System.Collections.Generic;
using exo3.Models;
using System.Collections;
namespace exo3.Tests.Controllers
{
[TestClass]
public class UnitTest1
{
IEtudiantRepository _stubMock;
public UnitTest1()
{
_stubMock = Substitute.For<IEtudiantRepository>();
}
[TestMethod]
public void TestIndex()
{
EtudiantController contro = new EtudiantController(_stubMock);
ViewResult r = contro.Index() as ViewResult;
Assert.AreEqual("exo3.Controllers.EtudiantController", r.ViewData["ControllerName"]);
Assert.AreEqual("Index", r.ViewName);
Assert.IsNotNull(r.ViewData.Model);
Assert.AreEqual(r.ViewData.Model,_stubMock.GetAllEtudiant() );
// IsType<IEtudiantRepository>(r.ViewData.Model);
// Assert.AreEqual( r.ViewData.Model,"Etudiant");
}
[TestMethod]
public void TestIndexIsCalled()
{
EtudiantController contro = new EtudiantController(_stubMock);
var resultat = contro.Index();
_stubMock.Received().GetAllEtudiant();// tester si Getdonnee a ete appele
}
[TestMethod]
public void TestCreateForRedirect()
{
EtudiantController contro = new EtudiantController(_stubMock);
etudiant et = new etudiant();
var result = contro.Create(et) as RedirectToRouteResult;
Assert.AreEqual("Index", result.RouteValues["Action"]);
}
[TestMethod]
public void TestCreateIsCalled()
{
EtudiantController contro = new EtudiantController(_stubMock);
etudiant et = new etudiant();
var result = contro.Create(et);
_stubMock.Received().CreateNewEtudiant(et);// tester si Getdonnee a ete appele
}
}
}
<file_sep>/Exo1/Controllers/FirstController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Exo1.Controllers
{
public class FirstController : Controller
{
// GET: test
public ActionResult Index()
{
return View();
}
public int Somme(int nb1, int nb2)
{
return nb1 + nb2;
}
public ActionResult Action2()
{
ViewData["Name"] = "xxx";
return View();
}
public ActionResult Details(int id)
{
if (id < 1)
return RedirectToAction("Index", "HomeController");
return View("Details");
}
public ActionResult GetView(int id)
{
if (id == 0)
return View("View1");
else
return View("View2");
}
public int Devide(int a, int b)
{
return a / b;
}
public List<int> SommeCollection(List<int> l1, List<int> l2)
{
List<int> somList = new List<int>();
if (l1.Count == l2.Count)
{
for (int i = 0; i < l1.Count; i++)
somList.Add(l1[i] + l2[i]);
}
return somList;
}
}
}<file_sep>/Exo2/Service/IService2.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exo2.Service
{
public interface IService2
{
int calcul(int cle, int x);
}
}
<file_sep>/Exo2/Service/Mock.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Exo2.Service
{
public class Mock : IService1
{
public bool IsCalled = false;
public int GetDonnee(int cle)
{
IsCalled = true;
return 1;
}
}
}<file_sep>/Exo2/Service/Stub.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Exo2.Service
{
public class Stub : IService1
{
public int GetDonnee(int cle)
{
if (cle == 1)
return 10;
return 1;
}
}
}<file_sep>/Exo2.Tests/Controllers/UnitTest2.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Exo2.Controllers;
using Exo2.Service;
using NSubstitute;
namespace Exo2.Tests.Controllers
{
[TestClass]
public class UnitTest2
{
IService1 _stub;
public UnitTest2()
{
_stub = Substitute.For<IService1>();
}
[TestMethod]
public void Testcalcul()
{
const int cle = 1;
_stub.GetDonnee(cle).Returns(10);// set a return value
var x = new Service2Imp(_stub);
var resultat = x.calcul(cle, 3);
Assert.AreEqual(30, resultat);
}
[TestMethod]
public void TestcalculMock()
{
const int cle = 1;
var x = new Service2Imp(_stub);
var resultat = x.calcul(cle, 3);
_stub.Received().GetDonnee(cle);// tester si Getdonnee a ete appele
}
}
}
<file_sep>/Exo2.Tests/Controllers/UnitTest1.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Exo2.Controllers;
using Exo2.Service;
namespace Exo2.Tests.Controllers
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
}
[TestMethod]
public void Testcalcul()
{
const int cle = 1;
var stub = new Stub();
var x = new Service2Imp(stub);
var resultat = x.calcul(cle, 3);
Assert.AreEqual(30, resultat);
}
[TestMethod]
public void TestcalculMock()
{
const int cle = 1;
var m = new Mock();
var x = new Service2Imp(m);
var resultat = x.calcul(cle, 3);
Assert.IsTrue(m.IsCalled);
}
}
}
<file_sep>/Exo1.Tests/Controllers/UnitTest1.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Exo1.Controllers;
using System.Web.Mvc;
using System.Collections.Generic;
namespace Exo1.Tests.Controllers
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
}
[TestMethod]
public void TestSomme()
{
FirstController c = new FirstController();
int nb1 = 10;
int nb2 = 30;
int som = 0;
int valeurAttendue = 40;
som = c.Somme(nb1, nb2);
Assert.AreEqual(som, valeurAttendue);
}
[TestMethod]
[ExpectedException(typeof(DivideByZeroException))]
public void TestDivision()
{
FirstController objMath = new FirstController();
int Result = objMath.Devide(10, 0);
Assert.AreEqual(10, Result);
}
[TestMethod]
public void TestGetViewWith0()
{
FirstController r = new FirstController();
ViewResult v = r.GetView(0) as ViewResult;
Assert.AreEqual("View1", v.ViewName);
}
[TestMethod]
public void TestGetViewWithOtherValue()
{
FirstController r = new FirstController();
ViewResult v = r.GetView(1) as ViewResult;
Assert.AreEqual("View2", v.ViewName);
}
[TestMethod]
public void TestAction2()
{
FirstController t = new FirstController();
ViewResult r = t.Action2() as ViewResult;
Assert.AreEqual("xxx", r.ViewData["Name"]);
}
[TestMethod]
public void TestDetailsForRedirect()
{
FirstController contro = new FirstController();
var result = contro.Details(-1) as RedirectToRouteResult;
Assert.AreEqual("Index",result.RouteValues["Action"]);
Assert.AreEqual("HomeController",result.RouteValues["Controller"]);
}
[TestMethod]
public void TestDetailsForViewResult()
{
FirstController contro1 = new FirstController();
var result1 = contro1.Details(2) as ViewResult;
Assert.AreEqual("Details",result1.ViewName);
}
[TestMethod]
public void TestSommeCollection()
{
List<int> l1 = new List<int> { 1, 2, 3 };
List<int> l2 = new List<int> { 1, 1, 1 };
List<int> listPrevu = new List<int> { 2, 3, 4 };
List<int> listresultant = new List<int>();
FirstController cont = new FirstController();
listresultant= cont.SommeCollection(l1, l2);
CollectionAssert.AreEqual(listPrevu, listresultant);
}
}
}
<file_sep>/exo3/Controllers/EtudiantController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using exo3.Models;
using exo3.Repositories;
namespace exo3.Controllers
{
public class EtudiantController : Controller
{
IEtudiantRepository rep;
public EtudiantController(IEtudiantRepository repository)
{
rep = repository;
}
// GET: Etudiant
public ActionResult Index()
{
ViewData["ControllerName"] = this.ToString();
return View("Index",rep.GetAllEtudiant());
}
public ActionResult Create(etudiant et)
{
if (ModelState.IsValid)
{
rep.CreateNewEtudiant(et);
return RedirectToAction("Index");
}
return View("Create");
}
}
} | e7ece617020b49d655d52ed65413e2496a59623d | [
"C#"
] | 14 | C# | LailaZou/TestUnitaire1 | 51d23a12e64a17052f183df23ec26a40e54e7c03 | 4c79fca4f7e770553cdecf59d6a4b7dcf4eeaf3e |
refs/heads/master | <file_sep>#include "esp-ui.h"
#include "epdpaint.h"
#include "epd2in9.h"
#include "epdfont.h"
#include "esp_log.h"
#include "esp_spiffs.h"
#include <string.h>
#include <time.h>
#include <sys/time.h>
#define ROTATE ROTATE_270
static const char *TAG = "ESP-UI";
ui_data_t ui_data;
static epd_font_t hzk;
int esp_ui_init() {
// init hzk chinese gb2312 font
FILE* f = fopen("/spiffs/HZK12", "r");
if (f == NULL) {
ESP_LOGE(TAG, "Failed to open file /spiffs/HZK12");
return false;
}
hzk.width = 16;
hzk.height = 12;
hzk.file = f;
return true;
}
void esp_ui_full_paint() {
ui_data.refresh_counter++;
// init display
epd_init(EPD_2IN9_LUT_UPDATE_FULL);
// create painter
esp_painter_handle_t painter = epdpaint_init(ROTATE, 0, 0, EPD_HEIGHT, EPD_WIDTH);
if (!painter) return;
// start paint
epdpaint_clear(painter, WHITE);
// paint time
time_t now = 0;
time(&now);
struct tm timeinfo = { 0 };
localtime_r(&now, &timeinfo);
char strftime_buf[6];
strftime(strftime_buf, 6, "%H:%M", &timeinfo);
epdpaint_draw_utf8_string(painter,
EPD_HEIGHT-5*epd_font_asc_16.width,
EPD_WIDTH-epd_font_asc_16.height,
5*epd_font_asc_16.width,
epd_font_asc_16.height,
strftime_buf,
&epd_font_asc_16, 0, BLACK);
// paint pushbullet message
epdpaint_draw_utf8_string(painter, 0, 0, 296, 128, ui_data.message, &epd_font_asc_16, &hzk, BLACK);
epd_set_frame_memory(painter->buffer);
epd_display_frame();
epd_set_frame_memory(painter->buffer);
epd_sleep();
epdpaint_destroy(painter);
return;
}
// partial display format: 23:23
void esp_ui_paint_time() {
// check refresh mode
ESP_LOGI(TAG, "refresh_counter(%d)", ui_data.refresh_counter);
if (ui_data.refresh_counter % 10 == 0) {
return esp_ui_full_paint();
}
ui_data.refresh_counter++;
epd_init(EPD_2IN9_LUT_UPDATE_PART);
epd_font_t *time_fnt = &epd_font_asc_16;
// create painter
esp_painter_handle_t painter = epdpaint_init(ROTATE, EPD_HEIGHT-5*time_fnt->width, EPD_WIDTH-time_fnt->height, (time_fnt->width*5), time_fnt->height);
if (!painter) {
ESP_LOGE(TAG, "no memory for painter");
return;
}
// start paint
epdpaint_clear(painter, WHITE);
// paint time
time_t now = 0;
time(&now);
struct tm timeinfo = { 0 };
localtime_r(&now, &timeinfo);
char strftime_buf[6];
strftime(strftime_buf, 6, "%H:%M", &timeinfo);
epdpaint_draw_utf8_string(painter, 0, 0,
5*time_fnt->width,
time_fnt->height,
strftime_buf,
time_fnt, 0, BLACK);
epd_set_image_memory(painter->buffer, painter->abs_x, painter->abs_y, painter->abs_width, painter->abs_height);
epd_display_frame();
epd_sleep();
epdpaint_destroy(painter);
}<file_sep>#include "epdif.h"
#include "epd2in9.h"
#include "esp-ui.h"
#include "ws_client.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_heap_caps.h"
#include "esp_spiffs.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "esp_event_loop.h"
#include "esp_http_client.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "lwip/err.h"
#include "lwip/sys.h"
#include "lwip/apps/sntp.h"
#include "cJSON.h"
#include <string.h>
#include <time.h>
#include <sys/time.h>
static const char *TAG = "ESP-EPD";
static EventGroupHandle_t s_event_group;
static const int WIFI_CONNECTED_BIT = BIT0;
static const int PUSHBULLET_MSG_BIT = BIT1;
static int s_wifi_retry_num = 0;
static esp_err_t wifi_event_handler(void *ctx, system_event_t *event);
static void wifi_init_sta();
static void initialize_sntp(void);
static void ui_task(void *pvParameter);
static esp_err_t spiffs_init();
static esp_err_t ws_handler(ws_event_t *event);
static void pushbullet_mirror_msg(char *json);
void app_main() {
s_event_group = xEventGroupCreate();
esp_err_t ret;
// init NVS and WIFI
ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
ESP_LOGI(TAG, "ESP_WIFI_MODE_STA");
wifi_init_sta();
// init NTP
initialize_sntp();
// init epd spi interface
epdif_pin_config_t epd_pin_cfg = {
.mosi_io_num = 14,
.sclk_io_num = 13,
.dc_io_num = 27,
.cs_io_num = 15,
.busy_io_num = 25,
.rst_io_num = 26,
.vcc_io_num = 0,
};
epdif_init(&epd_pin_cfg, EPD_WIDTH, EPD_HEIGHT);
// init spiffs
spiffs_init();
// init esp-ui
esp_ui_init();
// start tasks
xEventGroupSetBits(s_event_group, PUSHBULLET_MSG_BIT);
xTaskCreate(&ui_task, "ui_task", 1024*5, NULL, tskIDLE_PRIORITY + 1, NULL);
xEventGroupWaitBits(s_event_group, WIFI_CONNECTED_BIT, false, true, portMAX_DELAY);
ws_client_config_t ws_cfg = {
.uri = "wss://stream.pushbullet.com/websocket/"CONFIG_PUSHBULLET_TOKEN,
.event_handle = ws_handler,
.out_buffer = calloc(1, 5*1024),
.out_buffer_size = 5*1024,
};
ws_client_handle_t ws_client = ws_client_init(&ws_cfg);
ret = ws_client_start(ws_client);
ESP_ERROR_CHECK(ret);
}
static esp_err_t wifi_event_handler(void *ctx, system_event_t *event)
{
switch(event->event_id) {
case SYSTEM_EVENT_STA_START:
esp_wifi_connect();
break;
case SYSTEM_EVENT_STA_GOT_IP:
ESP_LOGI(TAG, "got ip:%s",
ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));
s_wifi_retry_num = 0;
xEventGroupSetBits(s_event_group, WIFI_CONNECTED_BIT);
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
{
esp_wifi_connect();
xEventGroupClearBits(s_event_group, WIFI_CONNECTED_BIT);
s_wifi_retry_num++;
ESP_LOGI(TAG,"retry to connect to the AP, retry_counter=%d", s_wifi_retry_num);
break;
}
default:
break;
}
return ESP_OK;
}
void wifi_init_sta()
{
tcpip_adapter_init();
ESP_ERROR_CHECK(esp_event_loop_init(wifi_event_handler, NULL) );
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
wifi_config_t wifi_config = {
.sta = {
.ssid = CONFIG_ESP_WIFI_SSID,
.password = <PASSWORD>
},
};
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) );
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config) );
ESP_ERROR_CHECK(esp_wifi_start() );
ESP_LOGI(TAG, "wifi_init_sta finished.");
ESP_LOGI(TAG, "connect to ap SSID:%s", CONFIG_ESP_WIFI_SSID);
}
static void initialize_sntp(void)
{
ESP_LOGI(TAG, "Initializing SNTP");
sntp_setoperatingmode(SNTP_OPMODE_POLL);
sntp_setservername(0, "cn.pool.ntp.org");
sntp_init();
// Set timezone to China Standard Time
setenv("TZ", "CST-8", 1); tzset();
}
void ui_task(void *pvParameter) {
EventBits_t uxBits;
const TickType_t xTicksToWait = 60*1000 / portTICK_PERIOD_MS; // refresh time every 60s.
while (1) {
uxBits = xEventGroupWaitBits(s_event_group, PUSHBULLET_MSG_BIT | 0, pdTRUE, pdFALSE, xTicksToWait);
//printf("%02hhX ", uxBits);
if ( (uxBits & (PUSHBULLET_MSG_BIT|0)) != 0) {
// got new message
esp_ui_full_paint();
} else {
// no new message, refresh time
esp_ui_paint_time();
}
}
}
static esp_err_t spiffs_init() {
esp_err_t ret;
esp_vfs_spiffs_conf_t conf = {
.base_path = "/spiffs",
.partition_label = NULL,
.max_files = 5,
.format_if_mount_failed = false,
};
ret = esp_vfs_spiffs_register(&conf);
if (ret != ESP_OK) {
if (ret == ESP_FAIL) {
ESP_LOGE(TAG, "Failed to mount or format filesystem");
} else if (ret == ESP_ERR_NOT_FOUND) {
ESP_LOGE(TAG, "Failed to find SPIFFS partition");
} else {
ESP_LOGE(TAG, "Failed to initialize SPIFFS (%s)", esp_err_to_name(ret));
}
}
return ret;
}
static esp_err_t ws_handler(ws_event_t *event) {
switch (event->event_id) {
case WS_EVENT_ERROR:
ESP_LOGE(TAG, "WS_EVENT_ERROR");
break;
case WS_EVENT_CONNECTED:
ESP_LOGI(TAG, "WS_EVENT_CONNECTED");
break;
case WS_EVENT_DISCONNECTED:
ESP_LOGW(TAG, "WS_EVENT_DISCONNECTED");
break;
case WS_EVENT_DATA_FIN:
ESP_LOGI(TAG, "WS_EVENT_DATA_FIN");
//print_bytes(event->data, event->data_len);
ESP_LOGI(TAG, "TEXT LEN: %d", event->data_len);
ESP_LOGI(TAG, "TEXT: %.*s", event->data_len, event->data);
pushbullet_mirror_msg((char *)event->data);
break;
default:
break;
}
return ESP_OK;
}
static void pushbullet_mirror_msg(char *json) {
cJSON *root = cJSON_Parse(json);
if (!root) return;
cJSON *root_type = cJSON_GetObjectItemCaseSensitive(root, "type");
if (!root_type || strncmp(root_type->valuestring, "push", 4) != 0) {cJSON_Delete(root); return;}
cJSON *push = cJSON_GetObjectItemCaseSensitive(root, "push");
if (!push) {cJSON_Delete(root); return;}
cJSON *push_type = cJSON_GetObjectItemCaseSensitive(push, "type");
if (push_type && strncmp(push_type->valuestring ,"dismissal", 9) == 0) {
ui_data.message[0] = 0;
xEventGroupSetBits(s_event_group, PUSHBULLET_MSG_BIT);
cJSON_Delete(root); return;
}
if (!push_type || strncmp(push_type->valuestring ,"mirror", 6) != 0) {cJSON_Delete(root); return;}
cJSON *body = cJSON_GetObjectItemCaseSensitive(push, "body");
if (!body || body->type != cJSON_String) {cJSON_Delete(root); return;}
//printf(body->valuestring);
strncpy(ui_data.message, body->valuestring, 128*3);
xEventGroupSetBits(s_event_group, PUSHBULLET_MSG_BIT);
cJSON_Delete(root); return;
}<file_sep>#ifndef _UTF8_GB2312_H_
#define _UTF8_GB2312_H_
#include <stdint.h>
uint16_t utf8_to_gb2312(const char* utf8);
#endif<file_sep>https://github.com/aguegu/BitmapFont
ASC12 ' 8x12 ASCII点阵 一个字符12Byte
ASC16 ' 8x16 ASCII点阵 一个字符16Byte
ASC48 '24x48 ASCII点阵 一个字符144Byte
HZK12 '16x12 宋体汉字点阵 一个汉字24Byte
HZK14 '16x14 宋体汉字点阵 一个汉字28Byte
HZK16 '16x16 宋体汉字点阵 一个汉字32Byte
HZK16F '16x16 繁体宋体汉字点阵 一个汉字32Byte
<file_sep>#include "ws_client.h"
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <sys/random.h>
#include <arpa/inet.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_err.h"
#include "esp_log.h"
#include "mbedtls/base64.h"
#include "mbedtls/sha1.h"
#include "esp_transport.h"
#include "esp_transport_tcp.h"
#ifdef WS_CLIENT_ENABLE_WSS
#include "esp_transport_ssl.h"
#endif
/* using uri parser */
#include "http_parser.h"
typedef struct ws_data
{
ws_header_t ws_header;
uint8_t *rcv_buff;
int rcv_buff_len;
uint8_t *out_buff;
int out_buff_len;
int out_buff_cur;
} ws_data_t;
typedef struct {
char *host;
char *path;
char *scheme;
int port;
bool auto_reconnect;
int network_timeout_ms;
esp_transport_list_handle_t transport_list;
esp_transport_handle_t transport;
} ws_connection_info_t;
typedef enum {
WS_STATE_ERROR = -1,
WS_STATE_UNKNOWN = 0,
WS_STATE_INIT,
WS_STATE_CONNECTED,
WS_STATE_WAIT_TIMEOUT,
} ws_client_state_t;
typedef struct ws_client {
ws_connection_info_t connection_info;
ws_data_t ws_data;
ws_client_state_t state;
void *user_context;
ws_event_t event;
ws_event_callback_t event_handle;
int task_stack;
int task_prio;
bool run;
EventGroupHandle_t status_bits;
} ws_client_t;
const static int STOPPED_BIT = BIT0;
static const char *TAG = "WS_CLIENT";
#define WS_TASK_PRIORITY 5
#define WS_TASK_STACK (4*1024)
#define WS_NETWORK_TIMEOUT_MS (10*1000)
#define WS_RECONNECT_TIMEOUT_MS (10*1000)
#define WS_BUFFER_SIZE_BYTE 5*1024
#define WS_DEFAULT_PORT 80
#define WSS_DEFAULT_PORT 443
#define WS_MEM_CHECK(TAG, a, action) if (!(a)) { \
ESP_LOGE(TAG,"%s:%d (%s): %s", __FILE__, __LINE__, __FUNCTION__, "Memory exhausted"); \
action; \
}
static char *create_string(const char *ptr, int len);
static esp_err_t ws_abort_connection(ws_client_handle_t client);
static esp_err_t ws_dispatch_event(ws_client_handle_t client);
static esp_err_t ws_connect(ws_client_handle_t client);
static esp_err_t ws_process_receive_frame(ws_client_handle_t client);
static char *get_http_header(const char *buffer, const char *key);
static char *trimwhitespace(const char *str);
static void ws_task(void *pv);
ws_client_handle_t ws_client_init(const ws_client_config_t *config) {
ws_client_handle_t client = calloc(1, sizeof(ws_client_t));
WS_MEM_CHECK(TAG, client, return NULL);
// set configs
client->state = WS_STATE_UNKNOWN;
client->event_handle = config->event_handle;
client->user_context = config->user_context;
client->task_prio = config->task_prio;
if (client->task_prio <= 0) {
client->task_prio = WS_TASK_PRIORITY;
}
client->task_stack = config->task_stack;
if (client->task_stack == 0) {
client->task_stack = WS_TASK_STACK;
}
client->connection_info.auto_reconnect = true;
if (config->disable_auto_reconnect) {
client->connection_info.auto_reconnect = false;
}
client->connection_info.network_timeout_ms = WS_NETWORK_TIMEOUT_MS;
struct http_parser_url puri;
http_parser_url_init(&puri);
if (http_parser_parse_url(config->uri, strlen(config->uri), 0, &puri) != 0) {
ESP_LOGE(TAG, "Error parse uri = %s", config->uri);
return NULL;
}
client->connection_info.scheme = create_string(config->uri + puri.field_data[UF_SCHEMA].off, puri.field_data[UF_SCHEMA].len);
client->connection_info.host = create_string(config->uri + puri.field_data[UF_HOST].off, puri.field_data[UF_HOST].len);
client->connection_info.path = create_string(config->uri + puri.field_data[UF_PATH].off, puri.field_data[UF_PATH].len);
if (puri.field_data[UF_PORT].len) {
client->connection_info.port = strtol((const char*)(config->uri + puri.field_data[UF_PORT].off), NULL, 10);
}
client->connection_info.transport_list = esp_transport_list_init();
WS_MEM_CHECK(TAG, client->connection_info.transport_list, goto _ws_init_failed);
if (strncmp(client->connection_info.scheme, "wss", 3) == 0) {
#if WS_CLIENT_ENABLE_WSS
esp_transport_handle_t ssl = esp_transport_ssl_init();
WS_MEM_CHECK(TAG, ssl, goto _ws_init_failed);
if (config->cert_pem) {
esp_transport_ssl_set_cert_data(ssl, config->cert_pem, strlen(config->cert_pem));
}
if (config->client_cert_pem) {
esp_transport_ssl_set_client_cert_data(ssl, config->client_cert_pem, strlen(config->client_cert_pem));
}
if (config->client_key_pem) {
esp_transport_ssl_set_client_key_data(ssl, config->client_key_pem, strlen(config->client_key_pem));
}
esp_transport_list_add(client->connection_info.transport_list, ssl, "ssl");
esp_transport_set_default_port(ssl, WSS_DEFAULT_PORT);
client->connection_info.transport = ssl;
if (client->connection_info.port == 0) {
client->connection_info.port = WSS_DEFAULT_PORT;
}
#endif
} else {
esp_transport_handle_t tcp = esp_transport_tcp_init();
WS_MEM_CHECK(TAG, tcp, goto _ws_init_failed);
esp_transport_list_add(client->connection_info.transport_list, tcp, "tcp");
esp_transport_set_default_port(tcp, WS_DEFAULT_PORT);
client->connection_info.transport = tcp;
if (client->connection_info.port == 0) {
client->connection_info.port = WS_DEFAULT_PORT;
}
}
// init buffers
client->ws_data.out_buff = config->out_buffer;
client->ws_data.out_buff_len = config->out_buffer_size;
int buffer_size = config->buffer_size;
if (buffer_size <= 0) {
buffer_size = WS_BUFFER_SIZE_BYTE;
}
client->ws_data.rcv_buff = (uint8_t *)malloc(buffer_size);
WS_MEM_CHECK(TAG, client->ws_data.rcv_buff, goto _ws_init_failed);
client->ws_data.rcv_buff_len = buffer_size;
client->status_bits = xEventGroupCreate();
WS_MEM_CHECK(TAG, client->status_bits, goto _ws_init_failed);
return client;
_ws_init_failed:
ws_client_destroy(client);
return NULL;
}
esp_err_t ws_client_start(ws_client_handle_t client) {
if (client->state >= WS_STATE_INIT) {
ESP_LOGE(TAG, "Client has started");
return ESP_FAIL;
}
if (xTaskCreate(ws_task, "ws_task", client->task_stack, client, client->task_prio, NULL) != pdTRUE) {
ESP_LOGE(TAG, "Error create ws task");
return ESP_FAIL;
}
return ESP_OK;
}
static void ws_task(void *pv) {
ws_client_handle_t client = (ws_client_handle_t)pv;
client->run = true;
client->state = WS_STATE_INIT;
xEventGroupClearBits(client->status_bits, STOPPED_BIT);
while (client->run) {
switch ((int)client->state) {
case WS_STATE_INIT:
if (client->connection_info.transport == NULL) {
ESP_LOGE(TAG, "There are no transport");
client->run = false;
break;
}
if (ws_connect(client) < 0) {
ESP_LOGE(TAG, "Error ws_connect");
ws_abort_connection(client);
break;
}
ESP_LOGD(TAG, "Transport connected to %s://%s:%d", client->connection_info.scheme, client->connection_info.host, client->connection_info.port);
client->event.event_id = WS_EVENT_CONNECTED;
client->state = WS_STATE_CONNECTED;
ws_dispatch_event(client);
break;
case WS_STATE_CONNECTED:
// receive and process data
if (ws_process_receive_frame(client) == ESP_FAIL) {
ws_abort_connection(client);
break;
}
break;
case WS_STATE_WAIT_TIMEOUT:
if (!client->connection_info.auto_reconnect) {
client->run = false;
break;
}
vTaskDelay(client->connection_info.network_timeout_ms / portTICK_RATE_MS);
client->state = WS_STATE_INIT;
ESP_LOGD(TAG, "Reconnecting...");
break;
}
}
esp_transport_close(client->connection_info.transport);
xEventGroupSetBits(client->status_bits, STOPPED_BIT);
vTaskDelete(NULL);
}
void print_bytes(void *ptr, int size)
{
unsigned char *p = ptr;
int i;
for (i=0; i<size; i++) {
printf("%02hhX ", p[i]);
}
printf("\n");
}
static esp_err_t ws_process_receive_frame(ws_client_handle_t client)
{
int received_header_len = 0; // total received header len
int rlen = 0; // esp_transport_read() returned len
int real_head_len = 2; // real header len for this frame. <= 10 sizeof(ws_header_t)
int read_tries = 0;
// wait for data
int poll_read = esp_transport_poll_read(client->connection_info.transport, client->connection_info.network_timeout_ms);
if ( poll_read < 0) {
ESP_LOGE(TAG, "esp_transport_poll_read() failed.");
return ESP_FAIL;
} else if (poll_read == 0) {
return ESP_OK;
}
// handle header
memset(&client->ws_data.ws_header, 0, sizeof(ws_header_t));
while (received_header_len < real_head_len) {
ESP_LOGI(TAG, "received_header_len(%d), real_head_len(%d)", received_header_len, real_head_len);
if ((read_tries++) > 5) {
ESP_LOGE(TAG, "ws_process_receive not finished in 5 transport_read()");
return ESP_FAIL;
}
rlen = esp_transport_read(client->connection_info.transport, (char *)&client->ws_data.ws_header+received_header_len, real_head_len - received_header_len, client->connection_info.network_timeout_ms);
ESP_LOGI(TAG, "rlen(%d)", rlen);
if (rlen < 0) {
ESP_LOGE(TAG, "Read error or end of stream");
return ESP_FAIL;
}
if (rlen == 0 && received_header_len == 0) return ESP_OK; // no header, continue main loop.
if (rlen == 0) continue; // got header, continue receive data.
received_header_len += rlen;
// calc real_head_len from minimal header
if (received_header_len == 2) {
if (client->ws_data.ws_header.payload_len < 126) {
continue; // header complete
} else if (client->ws_data.ws_header.payload_len == 126) {
real_head_len += 2;
} else if (client->ws_data.ws_header.payload_len == 127) {
real_head_len += 8;
}
}
}
print_bytes(&client->ws_data.ws_header, sizeof(ws_header_t));
// handle payload_len
int payload_len = 0;
int received_payload_len = 0;
if (client->ws_data.ws_header.payload_len < 126) {
payload_len = client->ws_data.ws_header.payload_len;
} else if (client->ws_data.ws_header.payload_len == 126) {
payload_len = ntohs(*(uint16_t *)client->ws_data.ws_header.ext_payload_len);
} else if (client->ws_data.ws_header.payload_len == 127) {
ESP_LOGE(TAG, "payload_len > 0xFFFF");
return ESP_FAIL;
}
ESP_LOGI(TAG, "payload_len(%d)", payload_len);
// handle payload
if (payload_len > client->ws_data.rcv_buff_len) {
ESP_LOGE(TAG, "payload_len(%d) > rcv_buff_len(%d)", payload_len, client->ws_data.rcv_buff_len);
// return ESP_FAIL, re-connect to server.
return ESP_FAIL;
}
memset(client->ws_data.rcv_buff, 0, client->ws_data.rcv_buff_len);
while (received_payload_len < payload_len) {
ESP_LOGI(TAG, "received_payload_len(%d), payload_len(%d)", received_payload_len, payload_len);
if ((read_tries++) > 5) {
ESP_LOGE(TAG, "ws_process_receive not finished in 5 transport_read()");
return ESP_FAIL;
}
rlen = esp_transport_read(client->connection_info.transport, (char *)client->ws_data.rcv_buff+received_payload_len, client->ws_data.rcv_buff_len-received_payload_len, client->connection_info.network_timeout_ms);
ESP_LOGI(TAG, "rlen(%d)", rlen);
if (rlen < 0) {
ESP_LOGE(TAG, "Read error or end of stream");
return ESP_FAIL;
}
if (rlen == 0) { continue; }
received_payload_len += rlen;
}
// handle opcode
ws_header_t pong_ws_header;
int n_copy = 0;
ESP_LOGI(TAG, "opcode(%d)", client->ws_data.ws_header.opcode);
switch(client->ws_data.ws_header.opcode) {
case 0: /* FRAGMENT */
case 1: /* TEXT */
case 2: /* BINARY */
client->event.event_id = WS_EVENT_DATA;
client->event.data = client->ws_data.rcv_buff;
client->event.data_len = payload_len;
client->event.ws_header = &(client->ws_data.ws_header);
ws_dispatch_event(client);
// handle fragment
if (client->ws_data.out_buff) {
ESP_LOGI(TAG, "out_buff_len(%d), out_buff_cur(%d)", client->ws_data.out_buff_len, client->ws_data.out_buff_cur);
n_copy = (client->ws_data.out_buff_len - client->ws_data.out_buff_cur) > payload_len ? payload_len : (client->ws_data.out_buff_len - client->ws_data.out_buff_cur);
memcpy(client->ws_data.out_buff + client->ws_data.out_buff_cur, client->ws_data.rcv_buff, n_copy);
client->ws_data.out_buff_cur += n_copy;
if (client->ws_data.ws_header.fin) {
client->event.event_id = WS_EVENT_DATA_FIN;
client->event.data = client->ws_data.out_buff;
client->event.data_len = client->ws_data.out_buff_cur;
client->event.ws_header = &(client->ws_data.ws_header);
ws_dispatch_event(client);
client->ws_data.out_buff_cur = 0;
memset(client->ws_data.out_buff, 0, client->ws_data.out_buff_len);
}
}
break;
case 9: /* PING */
memcpy(&pong_ws_header, &(client->ws_data.ws_header), 2);
pong_ws_header.opcode = 10;
pong_ws_header.mask = 1;
esp_transport_write(client->connection_info.transport, (char *)&pong_ws_header, 2, client->connection_info.network_timeout_ms);
if (pong_ws_header.payload_len > 0) {
char mask[4] = {0};
getrandom(mask, 4, 0);
esp_transport_write(client->connection_info.transport, mask, 4, client->connection_info.network_timeout_ms);
for (int i = 0; i < pong_ws_header.payload_len; i++) {
client->ws_data.rcv_buff[i] = (client->ws_data.rcv_buff[i] ^ mask[i % 4]);
}
esp_transport_write(client->connection_info.transport, (char *)client->ws_data.rcv_buff, pong_ws_header.payload_len, client->connection_info.network_timeout_ms);
}
break;
case 8: /* CLOSE */
case 10: /* PONG */
default:
break;
}
return ESP_OK;
}
static int ws_connect(ws_client_handle_t client) {
if (esp_transport_connect(client->connection_info.transport, client->connection_info.host, client->connection_info.port, client->connection_info.network_timeout_ms) < 0) {
ESP_LOGE(TAG, "Error connect to ther server esp_transport_connect");
return -1;
}
unsigned char random_key[16];
getrandom(random_key, sizeof(random_key), 0);
// Size of base64 coded string is equal '((input_size * 4) / 3) + (input_size / 96) + 6' including Z-term
unsigned char client_key[28] = {0};
size_t outlen = 0;
mbedtls_base64_encode(client_key, sizeof(client_key), &outlen, random_key, sizeof(random_key));
int len = snprintf((char *)client->ws_data.rcv_buff, client->ws_data.rcv_buff_len,
"GET %s HTTP/1.1\r\n"
"Connection: Upgrade\r\n"
"Host: %s:%d\r\n"
"Upgrade: websocket\r\n"
"Sec-WebSocket-Version: 13\r\n"
"Sec-WebSocket-Protocol: mqtt\r\n"
"Sec-WebSocket-Key: %s\r\n"
"User-Agent: ESP32 Websocket Client\r\n\r\n",
client->connection_info.path,
client->connection_info.host,
client->connection_info.port,
client_key);
if (len <= 0 || len >= client->ws_data.rcv_buff_len) {
ESP_LOGE(TAG, "Error in request generation, %d", len);
return -1;
}
ESP_LOGD(TAG, "Write upgrate request\r\n%s", client->ws_data.rcv_buff);
if (esp_transport_write(client->connection_info.transport, (char *)client->ws_data.rcv_buff, len, client->connection_info.network_timeout_ms) <= 0) {
ESP_LOGE(TAG, "Error write Upgrade header %s", client->ws_data.rcv_buff);
return -1;
}
if ((len = esp_transport_read(client->connection_info.transport, (char *)client->ws_data.rcv_buff, client->ws_data.rcv_buff_len, client->connection_info.network_timeout_ms)) <= 0) {
ESP_LOGE(TAG, "Error read response for Upgrade header %s", client->ws_data.rcv_buff);
return -1;
}
char *server_key = get_http_header((char *)client->ws_data.rcv_buff, "Sec-WebSocket-Accept:");
if (server_key == NULL) {
ESP_LOGE(TAG, "Sec-WebSocket-Accept not found");
return -1;
}
// See mbedtls_sha1_ret() arg size
unsigned char expected_server_sha1[20];
// Size of base64 coded string see above
unsigned char expected_server_key[33] = {0};
// If you are interested, see https://tools.ietf.org/html/rfc6455
const char expected_server_magic[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
unsigned char expected_server_text[sizeof(client_key) + sizeof(expected_server_magic) + 1];
strcpy((char*)expected_server_text, (char*)client_key);
strcat((char*)expected_server_text, expected_server_magic);
size_t key_len = strlen((char*)expected_server_text);
mbedtls_sha1_ret(expected_server_text, key_len, expected_server_sha1);
mbedtls_base64_encode(expected_server_key, sizeof(expected_server_key), &outlen, expected_server_sha1, sizeof(expected_server_sha1));
expected_server_key[ (outlen < sizeof(expected_server_key)) ? outlen : (sizeof(expected_server_key) - 1) ] = 0;
ESP_LOGD(TAG, "server key=%s, send_key=%s, expected_server_key=%s", (char *)server_key, (char*)client_key, expected_server_key);
if (strcmp((char*)expected_server_key, (char*)server_key) != 0) {
ESP_LOGE(TAG, "Invalid websocket key");
return -1;
}
return 0;
}
esp_err_t ws_client_write_data(ws_client_handle_t client, char *buff, int len)
{
int poll_write;
if ((poll_write = esp_transport_poll_write(client->connection_info.transport, client->connection_info.network_timeout_ms)) <= 0) {
ESP_LOGE(TAG, "socket not ready for writing");
return ESP_FAIL;
}
ws_header_t ws_header;
int header_len = 2;
ws_header.fin = 1;
ws_header.opcode = 8; // binary
ws_header.mask = 1;
if (len < 126) {
ws_header.payload_len = len;
} else if (len >= 126 && len < 0xFFFF) {
ws_header.payload_len = 126;
*(uint16_t *)&ws_header.ext_payload_len = htons(len);
header_len += 2;
} else {
ws_header.payload_len = 127;
/* TOO BIG, we don't support */
ESP_LOGE(TAG, "payload too big.");
return ESP_FAIL;
}
char mask[4] = {0};
getrandom(mask, 4, 0);
for (int i = 0; i < len; i++) {
buff[i] = (buff[i] ^ mask[i % 4]);
}
if (esp_transport_write(client->connection_info.transport, (char *)&ws_header, header_len, client->connection_info.network_timeout_ms) != header_len) {
ESP_LOGE(TAG, "Error write header");
return ESP_FAIL;
}
if (esp_transport_write(client->connection_info.transport, mask, 4, client->connection_info.network_timeout_ms) != 4) {
ESP_LOGE(TAG, "Error write mask");
return ESP_FAIL;
}
int write_len = 0;
int write_tries = 0;
int rlen = 0;
while (write_len < len) {
ESP_LOGI(TAG, "write_len(%d), len(%d)", write_len, len);
if ((write_tries++) > 5) {
ESP_LOGE(TAG, "ws_client_write_data not finished in 5 esp_transport_write()");
return ESP_FAIL;
}
rlen = esp_transport_write(client->connection_info.transport, buff, len, client->connection_info.network_timeout_ms);
if (rlen < 0) {
ESP_LOGE(TAG, "Error write data or timeout, rlen = %d", rlen);
return ESP_FAIL;
}
write_len += rlen;
}
return ESP_OK;
}
esp_err_t ws_client_destroy(ws_client_handle_t client) {
ws_client_stop(client);
free(client->connection_info.host);
free(client->connection_info.path);
free(client->connection_info.scheme);
esp_transport_list_destroy(client->connection_info.transport_list);
vEventGroupDelete(client->status_bits);
free(client->ws_data.rcv_buff);
free(client);
return ESP_OK;
}
esp_err_t ws_client_stop(ws_client_handle_t client) {
if (client->run) {
client->run = false;
xEventGroupWaitBits(client->status_bits, STOPPED_BIT, false, true, portMAX_DELAY);
client->state = WS_STATE_UNKNOWN;
return ESP_OK;
} else {
ESP_LOGW(TAG, "Client asked to stop, but was not started");
return ESP_FAIL;
}
}
static esp_err_t ws_abort_connection(ws_client_handle_t client)
{
esp_transport_close(client->connection_info.transport);
client->state = WS_STATE_WAIT_TIMEOUT;
ESP_LOGI(TAG, "Reconnect after %d ms", client->connection_info.network_timeout_ms);
client->event.event_id = WS_EVENT_DISCONNECTED;
ws_dispatch_event(client);
return ESP_OK;
}
static esp_err_t ws_dispatch_event(ws_client_handle_t client)
{
client->event.user_context = client->user_context;
client->event.client = client;
if (client->event_handle) {
return client->event_handle(&client->event);
}
return ESP_FAIL;
}
static char *create_string(const char *ptr, int len)
{
char *ret;
if (len <= 0) {
return NULL;
}
ret = calloc(1, len + 1);
WS_MEM_CHECK(TAG, ret, return NULL);
memcpy(ret, ptr, len);
return ret;
}
static char *trimwhitespace(const char *str)
{
char *end;
// Trim leading space
while (isspace((unsigned char)*str)) str++;
if (*str == 0) {
return (char *)str;
}
// Trim trailing space
end = (char *)(str + strlen(str) - 1);
while (end > str && isspace((unsigned char)*end)) end--;
// Write new null terminator
*(end + 1) = 0;
return (char *)str;
}
static char *get_http_header(const char *buffer, const char *key)
{
char *found = strstr(buffer, key);
if (found) {
found += strlen(key);
char *found_end = strstr(found, "\r\n");
if (found_end) {
found_end[0] = 0;//terminal string
return trimwhitespace(found);
}
}
return NULL;
}<file_sep>#include "epdpaint.h"
#include "epd2in9.h"
#include "utf8_gb2312.h"
#include "esp_log.h"
#include "esp_heap_caps.h"
#include <string.h>
#include <stdlib.h>
static const char *TAG = "EPD-PAINT";
esp_painter_handle_t epdpaint_init(int rotate, int x, int y, int width, int height) {
esp_painter_handle_t painter = malloc(sizeof(esp_painter_t));
if (!painter) {
ESP_LOGE(TAG, "no memory for painter");
return 0;
}
painter->rotate = rotate;
switch (rotate) {
case ROTATE_0:
painter->abs_width = width % 8 ? width + 8 - (width % 8) : width;
painter->abs_height = height;
painter->abs_x = x;
painter->abs_y = y;
break;
case ROTATE_90:
painter->abs_width = height % 8 ? height + 8 - (height % 8) : height;
painter->abs_height = width;
painter->abs_x = EPD_WIDTH - y - painter->abs_width;
painter->abs_y = x;
break;
case ROTATE_180:
painter->abs_width = width % 8 ? width + 8 - (width % 8) : width;
painter->abs_height = height;
painter->abs_x = EPD_WIDTH - x - painter->abs_width;
painter->abs_y = EPD_HEIGHT - y - painter->abs_height;
break;
case ROTATE_270:
painter->abs_width = height % 8 ? height + 8 - (height % 8) : height;
painter->abs_height = width;
painter->abs_x = y;
painter->abs_y = EPD_HEIGHT - x - painter->abs_height;
break;
default:
ESP_LOGE(TAG, "not a valid rotate(%d)", rotate);
break;
}
painter->buffer = heap_caps_malloc((painter->abs_width/8) * painter->abs_height, MALLOC_CAP_DMA);
if (!painter->buffer) {
ESP_LOGE(TAG, "no memory for paint buffer");
free(painter);
return 0;
}
return painter;
}
void epdpaint_destroy(esp_painter_handle_t painter) {
free(painter->buffer);
free(painter);
}
void epdpaint_draw_absolute_pixel(esp_painter_handle_t painter, int x, int y, int colored) {
if (x < 0 || x >= painter->abs_width || y < 0 || y >= painter->abs_height) {
return;
}
if (IF_INVERT_COLOR) {
if (colored) {
painter->buffer[(x + y * painter->abs_width) / 8] |= 0x80 >> (x % 8); //set bit
} else {
painter->buffer[(x + y * painter->abs_width) / 8] &= ~(0x80 >> (x % 8)); //clear bit
}
} else {
if (colored) {
painter->buffer[(x + y * painter->abs_width) / 8] &= ~(0x80 >> (x % 8)); //clear bit
} else {
painter->buffer[(x + y * painter->abs_width) / 8] |= 0x80 >> (x % 8); //set bit
}
}
}
void epdpaint_clear(esp_painter_handle_t painter, int colored) {
for (int x = 0; x < painter->abs_width; x++) {
for (int y = 0; y < painter->abs_height; y++) {
epdpaint_draw_absolute_pixel(painter, x, y, colored);
}
}
}
void epdpaint_draw_pixel(esp_painter_handle_t painter, int x, int y, int colored) {
int point_temp;
if (painter->rotate == ROTATE_0) {
if(x < 0 || x >= painter->abs_width || y < 0 || y >= painter->abs_height) {
return;
}
epdpaint_draw_absolute_pixel(painter, x, y, colored);
} else if (painter->rotate == ROTATE_90) {
if(x < 0 || x >= painter->abs_height || y < 0 || y >= painter->abs_width) {
return;
}
point_temp = x;
x = painter->abs_width - y;
y = point_temp;
epdpaint_draw_absolute_pixel(painter, x, y, colored);
} else if (painter->rotate == ROTATE_180) {
if(x < 0 || x >= painter->abs_width || y < 0 || y >= painter->abs_height) {
return;
}
x = painter->abs_width - x;
y = painter->abs_height - y;
epdpaint_draw_absolute_pixel(painter, x, y, colored);
} else if (painter->rotate == ROTATE_270) {
if(x < 0 || x >= painter->abs_height || y < 0 || y >= painter->abs_width) {
return;
}
point_temp = x;
x = y;
y = painter->abs_height - point_temp;
epdpaint_draw_absolute_pixel(painter, x, y, colored);
}
}
void epdpaint_draw_asc_char(esp_painter_handle_t painter, int x, int y, char asc_char, epd_font_t* font, int colored) {
unsigned int char_offset = (asc_char - ' ') * font->height * (font->width / 8 + (font->width % 8 ? 1 : 0));
const unsigned char* ptr = &font->table[char_offset];
for (int j = 0; j < font->height; j++) {
for (int i = 0; i < font->width; i++) {
if (*ptr & (0x80 >> (i % 8))) {
epdpaint_draw_pixel(painter, x + i, y + j, colored);
}
if (i % 8 == 7) {
ptr++;
}
}
if (font->width % 8 != 0) {
ptr++;
}
}
}
void epdpaint_draw_gb2312_char(esp_painter_handle_t painter, int x, int y, uint16_t gb2312_char, epd_font_t* font, int colored) {
int gb2312_row = (gb2312_char >> 8) - 0xA0;
int gb2312_col = (gb2312_char & 0xFF) - 0xA0;
uint8_t buffer[(font->width/8) * font->height];
unsigned int char_offset = (94 * (gb2312_row - 1) + (gb2312_col - 1)) * sizeof(buffer);
if (gb2312_char == 0) {
char_offset = 0;
}
fseek(font->file, char_offset, SEEK_SET);
fread(buffer, sizeof(buffer), 1, font->file);
const uint8_t* ptr = buffer;
for (int j = 0; j < font->height; j++) {
for (int i = 0; i < font->width; i++) {
if (*ptr & (0x80 >> (i % 8))) {
epdpaint_draw_pixel(painter, x + i, y + j, colored);
}
if (i % 8 == 7) {
ptr++;
}
}
if (font->width % 8 != 0) {
ptr++;
}
}
}
void epdpaint_draw_utf8_string(esp_painter_handle_t painter, int x, int y, int width, int height, const char* text, epd_font_t* en_font, epd_font_t* zh_font, int colored) {
const char* p_text = text;
int x_offset = x;
int y_offset = y;
int x_painted = 0;
int y_painted = 0;
while (*p_text != 0) {
// line wrap
if (x_painted + (zh_font?zh_font->width:en_font->width) > width) {
x_painted = 0;
x_offset = x;
y_painted += zh_font?zh_font->height:en_font->height;
y_offset += zh_font?zh_font->height:en_font->height;
}
// out of height
if (y_painted + (zh_font?zh_font->height:en_font->height) > height) {
return;
}
if ((*p_text & 0x80) == 0) { // ascii
epdpaint_draw_asc_char(painter, x_offset, y_offset, *p_text, en_font, colored);
x_offset += en_font->width;
x_painted += en_font->width;
p_text++;
} else if ((*p_text & 0xE0) == 0xE0) { // chinese
epdpaint_draw_gb2312_char(painter, x_offset, y_offset, utf8_to_gb2312(p_text), zh_font, colored);
x_offset += zh_font->width;
x_painted += zh_font->width;
p_text+=3;
} else {
p_text++;
}
}
}
void epdpaint_draw_img(esp_painter_handle_t painter, int x, int y, int width, int height, const uint8_t *img, int colored) {
const uint8_t* ptr = img;
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
if (*ptr & (0x80 >> (i % 8))) {
epdpaint_draw_pixel(painter, x + i, y + j, colored);
}
if (i % 8 == 7) {
ptr++;
}
}
if (width % 8 != 0) {
ptr++;
}
}
}
void epdpaint_draw_line(esp_painter_handle_t painter, int x0, int y0, int x1, int y1, int colored) {
/* Bresenham algorithm */
int dx = x1 - x0 >= 0 ? x1 - x0 : x0 - x1;
int sx = x0 < x1 ? 1 : -1;
int dy = y1 - y0 <= 0 ? y1 - y0 : y0 - y1;
int sy = y0 < y1 ? 1 : -1;
int err = dx + dy;
while((x0 != x1) && (y0 != y1)) {
epdpaint_draw_pixel(painter, x0, y0 , colored);
if (2 * err >= dy) {
err += dy;
x0 += sx;
}
if (2 * err <= dx) {
err += dx;
y0 += sy;
}
}
}
void epdpaint_draw_horizontal_line(esp_painter_handle_t painter, int x, int y, int width, int colored) {
for (int i = x; i < x + width; i++) {
epdpaint_draw_pixel(painter, i, y, colored);
}
}
void epdpaint_draw_vertical_line(esp_painter_handle_t painter, int x, int y, int height, int colored) {
for (int i = y; i < y + height; i++) {
epdpaint_draw_pixel(painter, x, i, colored);
}
}
void epdpaint_draw_rectangle(esp_painter_handle_t painter, int x0, int y0, int x1, int y1, int colored) {
int min_x = x1 > x0 ? x0 : x1;
int max_x = x1 > x0 ? x1 : x0;
int min_y = y1 > y0 ? y0 : y1;
int max_y = y1 > y0 ? y1 : y0;
epdpaint_draw_horizontal_line(painter, min_x, min_y, max_x - min_x + 1, colored);
epdpaint_draw_horizontal_line(painter, min_x, max_y, max_x - min_x + 1, colored);
epdpaint_draw_vertical_line(painter, min_x, min_y, max_y - min_y + 1, colored);
epdpaint_draw_vertical_line(painter, max_x, min_y, max_y - min_y + 1, colored);
}
void epdpaint_draw_filled_rectangle(esp_painter_handle_t painter, int x0, int y0, int x1, int y1, int colored) {
int min_x = x1 > x0 ? x0 : x1;
int max_x = x1 > x0 ? x1 : x0;
int min_y = y1 > y0 ? y0 : y1;
int max_y = y1 > y0 ? y1 : y0;
for (int i = min_x; i <= max_x; i++) {
epdpaint_draw_vertical_line(painter, i, min_y, max_y - min_y + 1, colored);
}
}
void epdpaint_draw_circle(esp_painter_handle_t painter, int x, int y, int radius, int colored) {
/* Bresenham algorithm */
int x_pos = -radius;
int y_pos = 0;
int err = 2 - 2 * radius;
int e2;
do {
epdpaint_draw_pixel(painter, x - x_pos, y + y_pos, colored);
epdpaint_draw_pixel(painter, x + x_pos, y + y_pos, colored);
epdpaint_draw_pixel(painter, x + x_pos, y - y_pos, colored);
epdpaint_draw_pixel(painter, x - x_pos, y - y_pos, colored);
e2 = err;
if (e2 <= y_pos) {
err += ++y_pos * 2 + 1;
if(-x_pos == y_pos && e2 <= x_pos) {
e2 = 0;
}
}
if (e2 > x_pos) {
err += ++x_pos * 2 + 1;
}
} while (x_pos <= 0);
}
void epdpaint_draw_filled_circle(esp_painter_handle_t painter, int x, int y, int radius, int colored) {
/* Bresenham algorithm */
int x_pos = -radius;
int y_pos = 0;
int err = 2 - 2 * radius;
int e2;
do {
epdpaint_draw_pixel(painter, x - x_pos, y + y_pos, colored);
epdpaint_draw_pixel(painter, x + x_pos, y + y_pos, colored);
epdpaint_draw_pixel(painter, x + x_pos, y - y_pos, colored);
epdpaint_draw_pixel(painter, x - x_pos, y - y_pos, colored);
epdpaint_draw_horizontal_line(painter, x + x_pos, y + y_pos, 2 * (-x_pos) + 1, colored);
epdpaint_draw_horizontal_line(painter, x + x_pos, y - y_pos, 2 * (-x_pos) + 1, colored);
e2 = err;
if (e2 <= y_pos) {
err += ++y_pos * 2 + 1;
if(-x_pos == y_pos && e2 <= x_pos) {
e2 = 0;
}
}
if(e2 > x_pos) {
err += ++x_pos * 2 + 1;
}
} while(x_pos <= 0);
}
<file_sep>#ifndef _EPDFONT_H_
#define _EPDFONT_H_
#include <stdint.h>
#include <stdio.h>
typedef struct epd_font
{
int width;
int height;
FILE* file;
const uint8_t* table;
} epd_font_t;
extern epd_font_t epd_font_asc_8;
extern epd_font_t epd_font_asc_12;
extern epd_font_t epd_font_asc_16;
/*
extern epd_font_t epd_font_asc_20;
extern epd_font_t epd_font_asc_24;
*/
#endif<file_sep>#!/bin/bash
# backtrace deocder
for addr in "$1"; do
xtensa-esp32-elf-addr2line -e build/*.elf ${addr%:*}
done
<file_sep>#include "epdif.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "driver/spi_master.h"
#include "esp_system.h"
#include <string.h>
static epdif_pin_config_t epd_pin_cfg;
static spi_device_handle_t epd_spi;
void epdif_init(epdif_pin_config_t *pin_cfg, uint32_t width, uint32_t height) {
memcpy(&epd_pin_cfg, pin_cfg, sizeof(epdif_pin_config_t));
gpio_set_direction(epd_pin_cfg.rst_io_num, GPIO_MODE_OUTPUT);
gpio_set_level(epd_pin_cfg.rst_io_num, 0);
gpio_set_direction(epd_pin_cfg.dc_io_num, GPIO_MODE_OUTPUT);
gpio_set_level(epd_pin_cfg.dc_io_num, 1);
gpio_set_direction(epd_pin_cfg.busy_io_num, GPIO_MODE_INPUT);
gpio_set_pull_mode(epd_pin_cfg.busy_io_num, GPIO_PULLUP_ONLY);
esp_err_t ret;
spi_bus_config_t buscfg={
.miso_io_num = -1,
.mosi_io_num = epd_pin_cfg.mosi_io_num,
.sclk_io_num = epd_pin_cfg.sclk_io_num,
.quadwp_io_num = -1,
.quadhd_io_num = -1,
.max_transfer_sz = (width/8) * height,
};
spi_device_interface_config_t devcfg={
.clock_speed_hz = 40*1000*1000, //Clock out at 40 MHz
.mode = 0, //SPI mode 0
.spics_io_num = epd_pin_cfg.cs_io_num,
.flags = SPI_DEVICE_HALFDUPLEX,
.queue_size = 1,
};
//Initialize the SPI bus
ret=spi_bus_initialize(HSPI_HOST, &buscfg, 1);
ESP_ERROR_CHECK(ret);
//Attach the LCD to the SPI bus
ret=spi_bus_add_device(HSPI_HOST, &devcfg, &epd_spi);
ESP_ERROR_CHECK(ret);
printf("SPI: display device added to spi bus\r\n");
}
void epdif_reset() {
gpio_set_level(epd_pin_cfg.rst_io_num, 0);
epdif_delay_ms(200);
gpio_set_level(epd_pin_cfg.rst_io_num, 1);
epdif_delay_ms(200);
}
void epdif_delay_ms(uint32_t delaytime) {
vTaskDelay(delaytime / portTICK_PERIOD_MS);
}
void epdif_wait_until_idle() {
while(gpio_get_level(epd_pin_cfg.busy_io_num) == 1) { //LOW: idle, HIGH: busy
epdif_delay_ms(100);
}
}
void epdif_send_command(uint8_t cmd) {
gpio_set_level(epd_pin_cfg.dc_io_num, 0);
esp_err_t ret;
spi_transaction_t t;
memset(&t, 0, sizeof(t)); //Zero out the transaction
t.length=8; //Len is in bytes, transaction length is in bits.
t.tx_data[0]=cmd; //Data
t.flags=SPI_TRANS_USE_TXDATA;
ret=spi_device_polling_transmit(epd_spi, &t); //Transmit!
ESP_ERROR_CHECK(ret);
}
void epdif_send_byte_data(uint8_t data) {
gpio_set_level(epd_pin_cfg.dc_io_num, 1);
esp_err_t ret;
spi_transaction_t t;
memset(&t, 0, sizeof(t)); //Zero out the transaction
t.length=8; //Len is in bytes, transaction length is in bits.
t.tx_data[0]=data; //Data
t.flags=SPI_TRANS_USE_TXDATA;
ret=spi_device_polling_transmit(epd_spi, &t); //Transmit!
ESP_ERROR_CHECK(ret);
}
void epdif_send_data(const uint8_t *data, uint32_t len) {
gpio_set_level(epd_pin_cfg.dc_io_num, 1);
esp_err_t ret;
spi_transaction_t t;
if (len==0) return; //no need to send anything
memset(&t, 0, sizeof(t)); //Zero out the transaction
t.length=len*8; //Len is in bytes, transaction length is in bits.
t.tx_buffer=data; //Data
ret=spi_device_polling_transmit(epd_spi, &t); //Transmit!
ESP_ERROR_CHECK(ret);
}<file_sep>#include "epd2in9.h"
#include "epdif.h"
// EPD2IN9 commands
#define DRIVER_OUTPUT_CONTROL 0x01
#define BOOSTER_SOFT_START_CONTROL 0x0C
#define GATE_SCAN_START_POSITION 0x0F
#define DEEP_SLEEP_MODE 0x10
#define DATA_ENTRY_MODE_SETTING 0x11
#define SW_RESET 0x12
#define TEMPERATURE_SENSOR_CONTROL 0x1A
#define MASTER_ACTIVATION 0x20
#define DISPLAY_UPDATE_CONTROL_1 0x21
#define DISPLAY_UPDATE_CONTROL_2 0x22
#define WRITE_RAM 0x24
#define WRITE_VCOM_REGISTER 0x2C
#define WRITE_LUT_REGISTER 0x32
#define SET_DUMMY_LINE_PERIOD 0x3A
#define SET_GATE_TIME 0x3B
#define BORDER_WAVEFORM_CONTROL 0x3C
#define SET_RAM_X_ADDRESS_START_END_POSITION 0x44
#define SET_RAM_Y_ADDRESS_START_END_POSITION 0x45
#define SET_RAM_X_ADDRESS_COUNTER 0x4E
#define SET_RAM_Y_ADDRESS_COUNTER 0x4F
#define TERMINATE_FRAME_READ_WRITE 0xFF
static const uint8_t lut_full_update[] =
{
0x02, 0x02, 0x01, 0x11, 0x12, 0x12, 0x22, 0x22,
0x66, 0x69, 0x69, 0x59, 0x58, 0x99, 0x99, 0x88,
0x00, 0x00, 0x00, 0x00, 0xF8, 0xB4, 0x13, 0x51,
0x35, 0x51, 0x51, 0x19, 0x01, 0x00
};
static const uint8_t lut_partial_update[] =
{
0x10, 0x18, 0x18, 0x08, 0x18, 0x18, 0x08, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x13, 0x14, 0x44, 0x12,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
static void epd_set_lut(const uint8_t* lut) {
epdif_send_command(WRITE_LUT_REGISTER);
/* the length of look-up table is 30 bytes */
epdif_send_data(lut, 30);
}
void epd_init(int lut_update_mode) {
/* EPD hardware init start */
epdif_reset();
epdif_send_command(DRIVER_OUTPUT_CONTROL);
epdif_send_byte_data((EPD_HEIGHT - 1) & 0xFF);
epdif_send_byte_data(((EPD_HEIGHT - 1) >> 8) & 0xFF);
epdif_send_byte_data(0x00); // GD = 0; SM = 0; TB = 0;
epdif_send_command(BOOSTER_SOFT_START_CONTROL);
epdif_send_byte_data(0xD7);
epdif_send_byte_data(0xD6);
epdif_send_byte_data(0x9D);
epdif_send_command(WRITE_VCOM_REGISTER);
epdif_send_byte_data(0xA8); // VCOM 7C
epdif_send_command(SET_DUMMY_LINE_PERIOD);
epdif_send_byte_data(0x1A); // 4 dummy lines per gate
epdif_send_command(SET_GATE_TIME);
epdif_send_byte_data(0x08); // 2us per line
epdif_send_command(DATA_ENTRY_MODE_SETTING);
epdif_send_byte_data(0x03); // X increment; Y increment
if (lut_update_mode == EPD_2IN9_LUT_UPDATE_FULL) {
epd_set_lut(lut_full_update);
} else if (lut_update_mode == EPD_2IN9_LUT_UPDATE_PART) {
epd_set_lut(lut_partial_update);
}
/* EPD hardware init end */
}
void epd_sleep() {
epdif_send_command(DEEP_SLEEP_MODE);
epdif_wait_until_idle();
}
void epd_set_memory_pointer(int x, int y) {
epdif_send_command(SET_RAM_X_ADDRESS_COUNTER);
/* x point must be the multiple of 8 or the last 3 bits will be ignored */
epdif_send_byte_data((x >> 3) & 0xFF);
epdif_send_command(SET_RAM_Y_ADDRESS_COUNTER);
epdif_send_byte_data(y & 0xFF);
epdif_send_byte_data((y >> 8) & 0xFF);
epdif_wait_until_idle();
}
void epd_set_memory_area(int x_start, int y_start, int x_end, int y_end) {
epdif_send_command(SET_RAM_X_ADDRESS_START_END_POSITION);
/* x point must be the multiple of 8 or the last 3 bits will be ignored */
epdif_send_byte_data((x_start >> 3) & 0xFF);
epdif_send_byte_data((x_end >> 3) & 0xFF);
epdif_send_command(SET_RAM_Y_ADDRESS_START_END_POSITION);
epdif_send_byte_data(y_start & 0xFF);
epdif_send_byte_data((y_start >> 8) & 0xFF);
epdif_send_byte_data(y_end & 0xFF);
epdif_send_byte_data((y_end >> 8) & 0xFF);
}
void epd_set_image_memory(const uint8_t* image_buffer, int x, int y, int width, int height) {
int x_end;
int y_end;
/* x point must be the multiple of 8 or the last 3 bits will be ignored */
x &= 0xF8;
width &= 0xF8;
if (!image_buffer || x < 0 || width < 1 || y < 0 || height < 1) {
return;
}
if (x + width >= EPD_WIDTH) {
x_end = EPD_WIDTH - 1;
} else {
x_end = x + width - 1;
}
if (y + height >= EPD_HEIGHT) {
y_end = EPD_HEIGHT - 1;
} else {
y_end = y + height - 1;
}
epd_set_memory_area(x, y, x_end, y_end);
epd_set_memory_pointer(x, y);
epdif_send_command(WRITE_RAM);
/* send the image data */
for (int j = 0; j < y_end - y + 1; j++) {
for (int i = 0; i < (x_end - x + 1) / 8; i++) {
epdif_send_byte_data(image_buffer[i + j * (width / 8)]);
}
}
}
void epd_set_frame_memory(const uint8_t* frame_buffer) {
if (!frame_buffer) {
return;
}
epd_set_memory_area(0, 0, EPD_WIDTH - 1, EPD_HEIGHT - 1);
epd_set_memory_pointer(0, 0);
epdif_send_command(WRITE_RAM);
epdif_send_data(frame_buffer, (EPD_WIDTH/8) * EPD_HEIGHT);
}
void epd_display_frame() {
epdif_send_command(DISPLAY_UPDATE_CONTROL_2);
epdif_send_byte_data(0xC4);
epdif_send_command(MASTER_ACTIVATION);
epdif_send_command(TERMINATE_FRAME_READ_WRITE);
epdif_wait_until_idle();
}
<file_sep>#ifndef _EPDIF_H_
#define _EPDIF_H_
#include <stdint.h>
typedef struct epdif_pin_config {
int mosi_io_num;
int sclk_io_num;
int dc_io_num;
int cs_io_num;
int busy_io_num;
int rst_io_num;
int vcc_io_num;
} epdif_pin_config_t;
void epdif_init(epdif_pin_config_t* pin_cfg, uint32_t width, uint32_t height);
void epdif_reset();
void epdif_delay_ms(uint32_t delaytime);
void epdif_wait_until_idle();
void epdif_send_command(uint8_t cmd);
void epdif_send_byte_data(uint8_t data);
void epdif_send_data(const uint8_t* data, uint32_t len);
#endif
<file_sep>#ifndef _EPD_UI_H_
#define _EPD_UI_H_
typedef struct ui_data {
int refresh_counter;
char message[128*3+1];
} ui_data_t;
extern ui_data_t ui_data;
int esp_ui_init();
void esp_ui_full_paint();
void esp_ui_paint_time();
#endif<file_sep>// https://www.waveshare.com/wiki/2.9inch_e-Paper_Module
#ifndef _EPD2IN9_H_
#define _EPD2IN9_H_
#include <stdint.h>
// Display resolution
#define EPD_WIDTH 128
#define EPD_HEIGHT 296
#define EPD_2IN9_LUT_UPDATE_FULL 0
#define EPD_2IN9_LUT_UPDATE_PART 1
void epd_init(int lut_update_mode);
void epd_sleep();
void epd_set_image_memory(const uint8_t* image_buffer, int x, int y, int width, int height);
void epd_set_frame_memory(const uint8_t* frame_buffer);
void epd_display_frame();
#endif /* _EPD2IN9_H_ */
/* END OF FILE */
<file_sep>#ifndef _WS_CLIENT_H_
#define _WS_CLIENT_H_
#include <stdint.h>
#include <stdbool.h>
#include "esp_err.h"
#ifdef __cplusplus
extern "C" {
#endif
#define WS_CLIENT_ENABLE_WSS CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS
typedef struct ws_client* ws_client_handle_t;
/* header without masking-key(4 bytes) */
typedef struct ws_header
{
uint8_t opcode : 4;
uint8_t srv_3 : 1;
uint8_t srv_2 : 1;
uint8_t srv_1 : 1;
uint8_t fin : 1;
uint8_t payload_len : 7;
uint8_t mask : 1;
uint8_t ext_payload_len[8];
} ws_header_t;
typedef enum {
WS_EVENT_ERROR = 0,
WS_EVENT_CONNECTED, /*!< connected event, additional context: session_present flag */
WS_EVENT_DISCONNECTED, /*!< disconnected event */
WS_EVENT_DATA, /*!< data event */
WS_EVENT_DATA_FIN, /*!< data event, for fragment, use out_buffer together */
} ws_event_id_t;
/**
* WS event configuration structure
*/
typedef struct {
ws_event_id_t event_id; /*!< WS event type */
ws_client_handle_t client; /*!< WS client handle for this event */
void *user_context; /*!< User context passed from WS client config */
ws_header_t *ws_header; /*!< WS header */
uint8_t *data; /*!< Data asociated with this event */
int data_len; /*!< Lenght of the data for this event */
} ws_event_t;
typedef esp_err_t (* ws_event_callback_t)(ws_event_t *event);
typedef struct {
ws_event_callback_t event_handle; /*!< handle for WS events */
const char *uri; /*!< Complete WS URI */
bool disable_auto_reconnect; /*!< this ws client will reconnect to server (when errors/disconnect). Set disable_auto_reconnect=true to disable */
void *user_context; /*!< pass user context to this option, then can receive that context in ``event->user_context`` */
int task_prio; /*!< WS task priority, default is 5, can be changed in ``make menuconfig`` */
int task_stack; /*!< WS task stack size, default is 6144 bytes, can be changed in ``make menuconfig`` */
int buffer_size; /*!< size of WS send/receive buffer*/
uint8_t *out_buffer;
int out_buffer_size;
const char *cert_pem; /*!< Pointer to certificate data in PEM format for server verify (with SSL), default is NULL, not required to verify the server */
const char *client_cert_pem; /*!< Pointer to certificate data in PEM format for SSL mutual authentication, default is NULL, not required if mutual authentication is not needed. If it is not NULL, also `client_key_pem` has to be provided. */
const char *client_key_pem; /*!< Pointer to private key data in PEM format for SSL mutual authentication, default is NULL, not required if mutual authentication is not needed. If it is not NULL, also `client_cert_pem` has to be provided. */
} ws_client_config_t;
ws_client_handle_t ws_client_init(const ws_client_config_t *config);
esp_err_t ws_client_start(ws_client_handle_t client);
esp_err_t ws_client_stop(ws_client_handle_t client);
esp_err_t ws_client_destroy(ws_client_handle_t client);
esp_err_t ws_client_write_data(ws_client_handle_t client, char *buff, int len);
#ifdef __cplusplus
}
#endif //__cplusplus
#endif
<file_sep>#ifndef _EPDPAINT_H_
#define _EPDPAINT_H_
#include "epdfont.h"
#include <stdint.h>
// Display orientation
#define ROTATE_0 0
#define ROTATE_90 1
#define ROTATE_180 2
#define ROTATE_270 3
// Color inverse. 1 or 0 = set or reset a bit if set a colored pixel
#define IF_INVERT_COLOR 0
#define WHITE 0
#define BLACK 1
typedef struct esp_painter
{
uint8_t *buffer;
uint8_t rotate;
int abs_x;
int abs_y;
int abs_width;
int abs_height;
} esp_painter_t;
typedef esp_painter_t* esp_painter_handle_t;
esp_painter_handle_t epdpaint_init(int rotate, int x, int y, int width, int height);
void epdpaint_destroy(esp_painter_handle_t painter);
void epdpaint_draw_absolute_pixel(esp_painter_handle_t painter, int x, int y, int colored);
void epdpaint_clear(esp_painter_handle_t painter, int colored);
void epdpaint_draw_pixel(esp_painter_handle_t painter, int x, int y, int colored);
void epdpaint_draw_line(esp_painter_handle_t painter, int x0, int y0, int x1, int y1, int colored);
void epdpaint_draw_horizontal_line(esp_painter_handle_t painter, int x, int y, int width, int colored);
void epdpaint_draw_vertical_line(esp_painter_handle_t painter, int x, int y, int height, int colored);
void epdpaint_draw_rectangle(esp_painter_handle_t painter, int x0, int y0, int x1, int y1, int colored);
void epdpaint_draw_filled_rectangle(esp_painter_handle_t painter, int x0, int y0, int x1, int y1, int colored);
void epdpaint_draw_circle(esp_painter_handle_t painter, int x, int y, int radius, int colored);
void epdpaint_draw_filled_circle(esp_painter_handle_t painter, int x, int y, int radius, int colored);
void epdpaint_draw_asc_char(esp_painter_handle_t painter, int x, int y, char asc_char, epd_font_t* font, int colored);
void epdpaint_draw_gb2312_char(esp_painter_handle_t painter, int x, int y, uint16_t gb2312_char, epd_font_t* font, int colored);
void epdpaint_draw_utf8_string(esp_painter_handle_t painter, int x, int y, int width, int height, const char* text, epd_font_t* en_font, epd_font_t* zh_font, int colored);
void epdpaint_draw_img(esp_painter_handle_t painter, int x, int y, int width, int height, const uint8_t *img, int colored);
#endif | d83c8560008cb898f234670c4ad287914f14d071 | [
"Markdown",
"C",
"Shell"
] | 15 | C | jejer/esp-epd | 8447a582095025ea8e39ac5347659c2bd31fde5f | 28d7bb4a526c45c1ef805eb6c06e09d99a23128b |
refs/heads/main | <file_sep>#include "game.h"
#include <iostream>
#include "SDL.h"
#include <future>
// #include "MessageQueue.h"
// random generator could generate food outside of grid due to random_w/h range from 0-32, which 32 is should not be included, hence grid_width/height - 1
Game::Game(std::size_t grid_width, std::size_t grid_height,Obstacle &obstacle)
: snake(grid_width, grid_height,obstacle),
engine(dev()),
random_w(0, static_cast<int>(grid_width-1)),
random_h(0, static_cast<int>(grid_height-1)),
obstacle(obstacle) {
PlaceFood();
}
// void Game::Run(Controller &controller, Renderer &renderer,
// std::size_t target_frame_duration)
void Game::Run(Controller const &controller, Renderer &renderer,
std::size_t target_frame_duration) {
Uint32 title_timestamp = SDL_GetTicks();
Uint32 frame_start;
Uint32 frame_end;
Uint32 frame_duration;
int frame_count = 0;
bool running = true;
rampUp_counter = 0;
// renderer.Render(snake, food);
// std::getchar();
queue = std::make_shared<MessageQueue<int>>();
while (running) {
frame_start = SDL_GetTicks();
// Input, Update, Render - the main game loop.
// controller.SpeedInput(running, snake);
controller.HandleInput(running, snake);
// std::cout<< " i am here " << std::endl;
Update();
renderer.Render(snake, food);
frame_end = SDL_GetTicks();
// Keep track of how long each loop through the input/update/render cycle
// takes.
frame_count++;
frame_duration = frame_end - frame_start;
// After every second, update the window title.
if (frame_end - title_timestamp >= 1000) {
renderer.UpdateWindowTitle(score, frame_count);
frame_count = 0;
title_timestamp = frame_end;
}
// If the time for this frame is too small (i.e. frame_duration is
// smaller than the target ms_per_frame), delay the loop to
// achieve the correct frame rate.
if (frame_duration < target_frame_duration) {
SDL_Delay(target_frame_duration - frame_duration);
}
if (score - counter ==2)
{
//start timer
rampUp_counter ++;
std::future<void> t1 = std::async(std::launch::async,&MessageQueue<int>::send, queue, std::move(rampUp_counter));
rampUp_counter = queue->receive();//permission granted
RampUp();
std::cout << "speed increased! "<< std::endl;
std::cout<< "rampUp counter is "<< rampUp_counter << std::endl;
counter = score;}
}
// t1.join();
}
void Game::RampUp(){
std::lock_guard<std::mutex> Speed_lock(_mtxSpped);
snake.speed = snake.speed + 0.05;
}
void Game::PlaceFood() {
int x, y;
while (true) {
x = random_w(engine);
y = random_h(engine);
// Check that the location is not occupied by a snake item before placing
// food.
// also check location is not occupied by obstacle
if (!snake.SnakeCell(x, y) & !obstacle.ObstacleCell(x, y)) {
food.x = x;
food.y = y;
return;
}
// if (!obstacle.ObstacleCell(x, y)) {
// food.x = x;
// food.y = y;
// return;
// }
}
}
void Game::Update() {
if (!snake.alive) return;
snake.Update();
int new_x = static_cast<int>(snake.head_x);
int new_y = static_cast<int>(snake.head_y);
// Check if there's food over here
if (food.x == new_x && food.y == new_y) {
score++;
PlaceFood();
// Grow snake and increase speed.
snake.GrowBody();
snake.speed += 0.02;
}
}
int Game::GetScore() const { return score; }
int Game::GetSize() const { return snake.size; }<file_sep>#ifndef CONTROLLER_H
#define CONTROLLER_H
#include "snake.h"
class Controller {
public:
void HandleInput(bool &running, Snake &snake) const;
void SpeedInput(bool &running, Snake &snake) const;
private:
void ChangeDirection(Snake &snake, Snake::Direction input,Snake::Direction opposite) const;
void ChangeSpeed(Snake &snake, Snake::Direction input) const;
};
#endif<file_sep>#include <mutex>
#include <deque>
#include <iostream>
#include <condition_variable>
#include <thread>
template <class T>
class MessageQueue
{
public:
// MessageQueue<T>();
T receive();
void send(T &&msg);
private:
std::deque<T> _queue; // currently only one element in the queue
std::condition_variable _cond;
std::mutex _mutex;
};
// for template class, you need to implement definition in header file instead of cpp file.
// more info: https://stackoverflow.com/questions/1111440/undefined-reference-error-for-template-method
template <typename T>
T MessageQueue<T>::receive()
{
std::unique_lock<std::mutex>uLock(_mutex); // modify the speed info under the lock
_cond.wait(uLock,[this]{return !_queue.empty();}); // lambda function pass to conditional variable to wait for notification
T msg = std::move(_queue.front());
_queue.pop_front();
return std::move(msg);
}
template <typename T>
void MessageQueue<T>::send(T &&msg)
{
std::lock_guard<std::mutex> uLock(_mutex);
_queue.emplace_back(msg);
std::cout<<"count down to increase speed -3 Seconds"<<std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(3000));
_cond.notify_one();
}<file_sep>#include "controller.h"
#include <iostream>
#include "SDL.h"
#include "snake.h"
void Controller::ChangeDirection(Snake &snake, Snake::Direction input,
Snake::Direction opposite) const {
// std::cout<< " snake direction is " << snake.speed << std::endl;
if (snake.direction != opposite || snake.size == 1) snake.direction = input;
return;
}
void Controller::ChangeSpeed(Snake &snake , Snake::Direction input) const
{
// std::cout<< " snake speed is " << snake.speed << std::endl;
if (snake.speed >= 0.02 && input == Snake::Direction::kS)
{snake.speed = snake.speed - 0.01;}
else if (input == Snake::Direction::kW)
{snake.speed = snake.speed + 0.01;}
return;
}
void Controller::HandleInput(bool &running, Snake &snake) const {
SDL_Event e;
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
running = false;
} else if (e.type == SDL_KEYDOWN) {
switch (e.key.keysym.sym) {
case SDLK_UP:
ChangeDirection(snake, Snake::Direction::kUp,
Snake::Direction::kDown);
break;
case SDLK_DOWN:
ChangeDirection(snake, Snake::Direction::kDown,
Snake::Direction::kUp);
break;
case SDLK_LEFT:
ChangeDirection(snake, Snake::Direction::kLeft,
Snake::Direction::kRight);
break;
case SDLK_RIGHT:
ChangeDirection(snake, Snake::Direction::kRight,
Snake::Direction::kLeft);
break;
case SDLK_w:
ChangeSpeed(snake,Snake::Direction::kW);
break;
case SDLK_s:
ChangeSpeed(snake, Snake::Direction::kS);
break;
}
}
}
}<file_sep># Snake Game Project
<img src="/snake_game.gif"/>
## Basic Build Instructions for Ubuntu 19.04
This program requires *SDL2, SDL2_image* and *SDL2_mixer* libraries. we can use the `apt-get` method to install them for Linux OS.
```
sudo apt-get install libsdl2-dev
sudo apt-get install libsdl2-image-dev
sudo apt-get install libsdl2-mixer-dev
```
To build the executable, we can follow the steps below:
1. Clone the starter repository.
2. Make a build directory in the top level directory: `mkdir build_Linux && cd build_Linux`
3. Compile: `cmake .. && make`
4. Run it: `cd .. && ./build_Linux/SnakeGame`
## Project Description
I modified starter codes in the [CppND-Capstone-Snake-Game](https://github.com/udacity/CppND-Capstone-Snake-Game) GitHub repository to add some obstacles on the map, so when the
Snake hits it, Snake dies. Program will check and make sure spawned food on on obstacle as well
The Snake game code consists of four main classes: `Game`, `Snake`, `Controller`, `MessageQueue`, `Renderer` and `Obstacle`.
1. To begin, `main` creates a `Controller`, a `Game`, a `Renderer`, and a `Obstacle` object. `Game` stores a `Snake` object as part of the state.
2. `main` calls `Game::Run` to start the background music and game loop.
3. `Controller` accepts directional input as well as speed input
4. `MessageQueue` acts as signal channel to send signal to thread and starts the `RampUp` and `RampUp_counter`, it will counts down 3 seconds before speed increase
# 5 total criteria from the rest of the rubric are addressed
1. A variety of control structures are used in the project.
2. The project accepts input from a user.
3. The project code is organized into classes.
4. All class data members are explicitly specified.
5. Class constructors utilize member initialization lists.
6. At least one class that uses unmanaged dynamically allocated memory, along with any class that otherwise needs to modify state upon the termination of an object, uses a destructor.
7. For classes with move constructors, the project returns objects of that class by value, and relies on the move constructor, instead of copying the object.
8. The project uses at least one smart pointer: unique_ptr, shared_ptr, or weak_ptr. The project does not use raw pointers.
9. A std::condition_variable is used in the project code to synchronize thread execution.
Criterion `1` is implemented in `renderer.cpp` at line `55 `, in `Obstacle` at line `10`,`17`,`33`, and `35`
Criterion `2` is implemented in `snake.cpp` at line `107 `.
Criterion `3` is implemented that the Snake game code consists of four main classes: `Game`, `Snake`, `Controller`, `Renderer` and `Obstacle`.
Criterion `4` is implemented in `obstacle.h` in line `9` and `20`.
Criterion `5` is implemented in `obstacle.h` in line `10` through `15`.
Criterion `6` is implemented in `game.cpp` in line `28`.
Criterion `7` is implemented in `snake.cpp` in line `7` through `24`.
Criterion `8` is implemented in `game.cpp` in line `28`.
Criterion `9` is implemented in `game.cpp` in line `63` through `64`.
`Additional knowledge : ` template class definition has to be in header files.[ Templated code implementation should never be in a .cpp file: your compiler has to see them at the same time as it sees the code that calls them] (https://stackoverflow.com/questions/1111440/undefined-reference-error-for-template-method)
<file_sep>#include <cmath>
#include <iostream>
#include "MessageQueue.h"
// create MessageQueue class to pass speed information into snake class to update snake moving speed
// template <typename T>
// T MessageQueue<T>::receive()
// {
// std::unique_lock<std::mutex>uLock(_mutex); // modify the speed info under the lock
// _cond.wait(uLock,[this]{return !_queue.empty();}); // lambda function pass to conditional variable to wait for notification
// T msg = std::move(_queue.front());
// _queue.pop_front();
// return std::move(msg);
// }
// template <typename T>
// void MessageQueue<T>::send(T &&msg)
// {
// std::lock_guard<std::mutex> uLock(_mutex);
// _queue.emplace_back(msg);
// std::cout<<"count down to increase speed -3 Seconds"<<std::endl;
// std::this_thread::sleep_for(std::chrono::milliseconds(3000));
// _cond.notify_one();
// }
<file_sep>#include "obstacle.h"
#include <iostream>
#include "SDL.h"
void Obstacle:: placeObstacle(){
SDL_Point point;
// place 2 parallel obstacle lines
for(int i=0; i<grid_width/2; i++)
{
point.x = i + (grid_width/4);
point.y = grid_height/3;
obstaclePoints.push_back(point);
}
for(int i=0; i<grid_width/2; i++)
{
point.x = i + (grid_width/4);
point.y = 2*(grid_height/3);
obstaclePoints.push_back(point);
}
}
// return obstacle points
std::vector<SDL_Point> Obstacle:: get_obstecle(){
return obstaclePoints;
}
// check if hit obstacle
bool Obstacle::ObstacleCell(int x, int y)
{
for (auto const &item : obstaclePoints)
{
if (x == item.x && y == item.y)
{
return true;
}
}
return false;
}<file_sep>
#ifndef OBSTACLE_H
#define OBSTACLE_H
#include "SDL.h"
#include <vector>
class Obstacle {
public:
Obstacle(int grid_width, int grid_height){
this->grid_width = grid_width;
this->grid_height = grid_height;
placeObstacle();
}
std::vector<SDL_Point> get_obstecle();
bool ObstacleCell(int x, int y);
private:
void placeObstacle();
std::vector <SDL_Point> obstaclePoints;
size_t grid_width;
size_t grid_height;
};
#endif | ddd8beb4dd4e96386acfc18920e392d0ebb312e8 | [
"Markdown",
"C++"
] | 8 | C++ | JasonTryharder/snake_game | 364e314ded1c963bd9fe37fc5809d07cf1012241 | 2c75d076a89e1fe40c97fcfd339cdb6947b9ae95 |
refs/heads/master | <repo_name>mkrcah/random-text-detector<file_sep>/README.md
Random text detector
====================
[](https://travis-ci.org/mkrcah/random-text-detector)
Unsupervised automatic detector of random text based on the algorithm described in [this blog post](http://marcelkrcah.net/blog/random-word-detector/). The interactive version is available on [random-text-detector.herokuapp.com](http://random-text-detector.herokuapp.com). Sample training and result data is in the `data` dictionary.
## How to run
- Install sbt with `brew install sbt` or [in any other way]((http://www.scala-sbt.org/0.13/tutorial/Setup.html))
- `git clone https://github.com/mkrcah/random-text-detector.git`
- `cd random-text-detect`
- `sbt stage`
- Run `./target/universal/stage/bin/random-text-detector`
## Usage
Usage: `random-text-detector start-server|batch filename`
Options:
- `batch` Compute suspicious score for each word in a given list and print the result to stdin.
- `start-server` Start an http server on the port specified by the PORT env property or 8080 if not specified. Call `GET /api/detect?q=your-word` to get a suspicious score for your-word. Navigate your browser to `/` or `/index.html` for the interactive version.
- `filename` File containing a list of words, each word on a separate line.
## Heroku
The code should be directly deployable to Heroku.
<file_sep>/src/main/resources/webapp/app.js
var app = angular.module('app', []);
app.controller('myCtrl', function ($scope, $http) {
$scope.checkWord = function(name) {
$http({ url: '/api/detect', method: "GET", params: {q: name} })
.success(function(data) {
$scope.result = data;
$("input").focus().select();
})
}
$scope.identity = angular.identity;
});
| 501bec50ea11a275c3882cbc1608f18c812b8b99 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | mkrcah/random-text-detector | b9fd20c7b49b7aa97dc162cd0237d2dcd3e0a767 | d3c847fae1bce831bb4204928e9e60d316283c91 |
refs/heads/main | <repo_name>AlexTMartins/techlist<file_sep>/src/App.js
import React, { useState } from 'react';
import './App.css';
import ListGroup from 'react-bootstrap/ListGroup'
import Container from 'react-bootstrap/Container'
import Col from 'react-bootstrap/Col'
import Row from 'react-bootstrap/Row'
import ResponsiveEmbed from 'react-bootstrap/ResponsiveEmbed'
var videoUrl="https://www.youtube.com/embed/vlDzYIIOYmM";
function AulaItemListComponent(props){
return props.name;
}
function setVideoLink(){
return alert("sdvs");
}
function VideoBoxComponent(props){
return <div style={{ width: 660, height: 'auto' }}>
<ResponsiveEmbed aspectRatio="16by9">
<embed type="" src={props.url} />
</ResponsiveEmbed>
</div>
}
function App() {
return (
<div className="App">
<Container>
<br></br>
<br></br>
<h1>TRILHA DO FUTURO</h1>
<br></br>
<br></br>
<br></br>
</Container>
<Container>
<Row className="show-grid">
<Col xs={12} md={4}>
<h4>Módulo 1 - Aplicações web com Node.js</h4>
<ListGroup defaultActiveKey="#link3">
<ListGroup.Item action href="#link1" disabled>
Aula 1
</ListGroup.Item>
<ListGroup.Item action href="#link2" disabled>
Aula 2
</ListGroup.Item>
<ListGroup.Item action href="#link3" disabled>
Aula 3
</ListGroup.Item>
<ListGroup.Item action href="#link4" onClick={setVideoLink()}>
<AulaItemListComponent url="link.com" name="Auuula 4" />
</ListGroup.Item>
<ListGroup.Item action href="#link5" >
Aula 5
</ListGroup.Item>
<br></br>
<ListGroup.Item>
Próximo Módulo - Avançando com APIs REST
</ListGroup.Item>
</ListGroup>
</Col>
<Col xs={12} md={8}>
<VideoBoxComponent url="https://www.youtube.com/embed/vlDzYIIOYmM"/>
</Col>
</Row>
</Container>
</div>
);
}
export default App; | e1a981e8a7264ac0bc88d43c4f24b5a293874d45 | [
"JavaScript"
] | 1 | JavaScript | AlexTMartins/techlist | 5d32dede7d60822715275e7874a3eaf19671500c | f3d0e08f87e61870604607996cdbf3b7d4f5386a |
refs/heads/main | <repo_name>bbshark99/TMEDeployment<file_sep>/script.js
// Contracts
const TMEDeployer = artifacts.require("TMEDeployer")
const TMECrowdsale = artifacts.require("TMECrowdsale")
const TME = artifacts.require("TME")
const TMELocker = artifacts.require("TMELocker")
// Utils
const ether = (n) => {
return new web3.utils.BN(
web3.utils.toWei(n.toString(), 'ether')
)
}
const contrib = async (amt, dest, key) => {
const val = web3.utils.toWei(amt, 'ether');
// console.log(val)
const tx = await web3.eth.accounts.signTransaction({
to: dest,
value: val.toString(),
gas: 2000000
}, key);
// console.log(tx)
// var serializedTx = tx.serialize();
return web3.eth.sendSignedTransaction(tx.rawTransaction);
}
module.exports = async function(callback) {
try {
// Fetch accounts from wallet - these are unlocked
const accounts = await web3.eth.getAccounts()
const tmeLocker = await TMELocker.deployed();
const tmeCrowdsale = await TMECrowdsale.deployed();
const tmeToken = await TME.deployed();
const treasuryAdd = await tmeLocker.treasury();
console.log('TMECrowdsale fetched', tmeCrowdsale.address)
console.log('TME fetched', tmeToken.address)
console.log('TMELocker fetched', tmeLocker.address)
console.log('treasuryAdd fetched', treasuryAdd)
// assume TMELocker is already ready and deployed.
r = await tmeLocker.isReadyForSale()
console.log("tmeLocker ready: ", r)
if (!r){
await tmeLocker.getReadyForCrowdSale()
for (var i = 0; i < 11; i+=1){
batches = await tmeLocker.batches(i);
console.log(batches.owner, batches.amount.toString(), batches.time.toString(), batches.spent)
}
}
r = await tmeLocker.isReadyForSale()
console.log("ready", r);
await tmeCrowdsale.setStarted(true);
console.log("started")
return;
if (r){
var balCrowdsale = await tmeToken.balanceOf(tmeCrowdsale.address);
console.log("balCrowdsale",balCrowdsale/1e18);
var buyerEthBalance = await web3.eth.getBalance(accounts[0]);
console.log("buyerEthBalance",buyerEthBalance/1e18)
// var test_keys = process.env.TEST_KEYS.split(",")
// send 1 ether
// var receipt = await contrib("1", tmeCrowdsale.address, test_keys[0]);
// var receipt = await contrib("1", tmeCrowdsale.address, test_keys[1]);
// var receipt = await contrib("1", tmeCrowdsale.address, test_keys[2]);
// var receipt = await contrib("1", tmeCrowdsale.address, test_keys[3]);
// var receipt = await contrib("1", tmeCrowdsale.address, test_keys[4]);
// test contribution of > 1 ether
var send = await web3.eth.sendTransaction({from:accounts[0],
to:tmeCrowdsale.address, value: 1000000000000000000});
console.log("after contrib 1 eth");
var balCrowdsale = await tmeToken.balanceOf(tmeCrowdsale.address);
// var buyerBalance = await tmeToken.balanceOf(accounts[0]);
var buyerEthBalance = await web3.eth.getBalance(accounts[0]);
var tmeLockerEthBalance = await web3.eth.getBalance(tmeLocker.address);
console.log("balCrowdsale",balCrowdsale/1e18)
// console.log("buyerBalance",buyerBalance/1e18)
console.log("buyerEthBalance",buyerEthBalance/1e18)
console.log("tmeLockerEthBalance",tmeLockerEthBalance/1e18)
// await tmeLocker.setPresaleEnded(true);
}
}
catch(error) {
console.log(error)
}
callback()
}
<file_sep>/readme.md
create a .env file with the following:
INFURA_API_KEY=\<fill this in\>
MAINNET_KEY=\<private key of deployer acc\>
TREASURY_ADD=\<treasury wallet\>
UNICRYPT_ADD=0x17e00383A843A9922bCA3B280C0ADE9f8BA48449
UNISWAP_ROUTER_ADD=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
UNISWAP_FACTORY_ADD=0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f
Steps:
1. truffle migrate --reset --network <mainnet|mainnet-fork|ropsten>
2. run truffle exec script.js --network <mainnet|mainnet-fork|ropsten> to begin crowdsale and contrib 1 eth as test
3. run truffle exec end.js --network <mainnet|mainnet-fork|ropsten> to end the crowdsale, claim unsold tokens to treasury, lock liquidity<file_sep>/claimTreasury.js
// Contracts
const TME = artifacts.require("TME")
const TMELocker = artifacts.require("TMELocker")
const TMETimeLock = artifacts.require("TMETimeLock");
const TMECrowdsale = artifacts.require("TMECrowdsale");
// Utils
const ether = (n) => {
return new web3.utils.BN(
web3.utils.toWei(n.toString(), 'ether')
)
}
module.exports = async function(callback) {
try {
// Fetch accounts from wallet - these are unlocked
const accounts = await web3.eth.getAccounts()
console.log(accounts)
const tmeLocker = await TMELocker.deployed();
const tmeCrowdsale = await TMECrowdsale.deployed();
const tmeToken = await TME.deployed();
const tmeTimeLock = await TMETimeLock.deployed();
const treasuryAdd = await tmeLocker.treasury();
console.log('TMECrowdsale fetched', tmeCrowdsale.address)
console.log('TME fetched', tmeToken.address)
console.log('TMELocker fetched', tmeLocker.address)
console.log('tmeTimeLock', tmeTimeLock.address)
console.log('treasuryAdd',treasuryAdd)
let treasuryBal = await tmeToken.balanceOf(treasuryAdd);
console.log("treasuryBal",treasuryBal.toString())
// claim
await tmeTimeLock.claimToken(0);
let treasuryBal2 = await tmeToken.balanceOf(treasuryAdd);
console.log("treasuryBal",treasuryBal2.toString())
callback();
return;
var devBal = await tmeToken.balanceOf(accounts[0]);
console.log("devBal", devBal.toString());
// callback()
// return
// await tmeLocker.claimToken(0);
// await tmeLocker.claimToken(1);
await tmeLocker.claimToken(2);
// send 4 to mf gatchi
await tmeToken.transfer("0x032dA9D10962499Bf8694596d747cb85503eccf8",ether(4));
// send 2 to luk
await tmeToken.transfer("0x7F09373EEACeE72F0EDBd286C609C59cAF155661",ether(2));
// var treasuryBal = await tmeToken.balanceOf(process.env.TREASURY_ADD);
// console.log("treasuryBal", treasuryBal.toString());
var devBal = await tmeToken.balanceOf(accounts[0]);
console.log("devBal", devBal.toString());
// const tmeTimeLock = await TMETimeLock.deployed();
// console.log('TMETimeLock', tmeTimeLock.address);
// await tmeTimeLock.setTokenAdd(tmeToken.address);
// const now = Math.floor(Date.now()/1000);
// console.log("now", now);
// await tmeToken.approve(tmeTimeLock.address, "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
// const allowance = await tmeToken.allowance(accounts[0],tmeTimeLock.address);
// console.log("time lock allowance", allowance.toString());
// await tmeTimeLock.lock(ether(1), now+60);
// console.log("locked");
// var devBal = await tmeToken.balanceOf(accounts[0]);
// console.log("devBal", devBal.toString());
// var timelockBal = await tmeToken.balanceOf(tmeTimeLock.address);
// console.log("timeLockBal", timelockBal.toString());
// var numBatches = await tmeTimeLock.numBatches();
// for (var i = 0; i < numBatches; i+=1){
// batches = await tmeTimeLock.batches(i);
// console.log(batches.owner, batches.amount.toString(), batches.time.toString(), batches.spent)
// }
}
catch(error) {
console.log(error)
}
callback()
}<file_sep>/migrations/3_deploy_crowdsale.js
const TMECrowdsale = artifacts.require('./TMECrowdsale.sol')
const TME = artifacts.require('./TME.sol')
const TMELocker = artifacts.require('./TMELocker.sol')
require('dotenv').config()
module.exports = async (deployer, network, accounts) => {
let deployAddress = accounts[0] // by convention
console.log('Preparing for deployment of TMECrowdsale...')
console.log('deploying from:' + deployAddress)
const token = await TME.deployed();
await deployer.deploy(TMECrowdsale, 3, "1000000000000000000", "60000000000000000000",
token.address, {
from: deployAddress
});
await deployer.deploy(TMELocker,
process.env.UNISWAP_ROUTER_ADD,
process.env.UNISWAP_FACTORY_ADD,
process.env.UNICRYPT_ADD,
// "0x0000000000000000000000000000000000000000",
deployAddress,
process.env.TREASURY_ADD,
token.address, {
from: deployAddress
})
}
<file_sep>/migrations/4_setup.js
const TMELocker = artifacts.require('./TMELocker.sol')
const TMECrowdsale = artifacts.require('./TMECrowdsale.sol')
const TME = artifacts.require('./TME.sol')
require('dotenv').config()
module.exports = async (deployer, network, accounts) => {
let deployAddress = accounts[0] // by convention
console.log('Preparing for setup...')
console.log('setup from:' + deployAddress)
const token = await TME.deployed();
const crowdsale = await TMECrowdsale.deployed();
const locker = await TMELocker.deployed();
console.log(token.address, crowdsale.address, locker.address)
await crowdsale.setTMELocker(locker.address);
await token.transfer(crowdsale.address, "180000000000000000000");
await token.transfer(locker.address, "820000000000000000000");
}
<file_sep>/alpha.js
// Contracts
const TMEDeployer = artifacts.require("TMEDeployer")
const TMECrowdsale = artifacts.require("TMECrowdsale")
const TME = artifacts.require("TME")
const TMELocker = artifacts.require("TMELocker")
const IUniswapPair = artifacts.require("IUniswapPair")
const IUnicrypt = artifacts.require("IUnicrypt")
const TMETimeLock = artifacts.require("TMETimeLock");
// Utils
const ether = (n) => {
return new web3.utils.BN(
web3.utils.toWei(n.toString(), 'ether')
)
}
module.exports = async function(callback) {
try {
// Fetch accounts from wallet - these are unlocked
const accounts = await web3.eth.getAccounts()
console.log(accounts)
const tmeToken = await TME.at("0x<PASSWORD>");
console.log('TME fetched', tmeToken.address)
// await tmeLocker.setPresaleEnded(true);
var bal = await tmeToken.balanceOf(accounts[0]);
console.log("bal", bal.toString());
const addresses = [
"0x46B8FfC41F26cd896E033942cAF999b78d10c277"
// "0x8EF9A1A12e0B7E92f11d112f51Ae1054Ddc0E37D", //signer
// "0x1E18b<KEY>",
// "0<KEY>",
// "0x5ea5cc3A18Ee0E5aAFed07826bfd74<KEY>",
// "<KEY>",
// "<KEY>",
// "<KEY>",
// "<KEY>",
// "<KEY>",
// "0x610C02e213496259DAeF68d8413CF13ce6306511",
// "0x53E92Fb32920a307440b84A4246220093197A28D",
// "0x750A31fA07184CAf87b6Cce251d2F0D7928BADde",
// "<KEY>",
]
let p = []
for (let a of addresses){
p.push(tmeToken.transfer(a, ether(5)));
}
await Promise.all(p).then((r) => {
console.log(r)
})
callback()
return
await tmeLocker.claimToken(0);
await tmeLocker.claimToken(1);
// send 5 to mf gatchi
tmeToken.transfer("0x032dA9D10962499Bf8694596d747cb85503eccf8",ether(5));
var devBal = await tmeToken.balanceOf(accounts[0]);
console.log("devBal", devBal.toString());
// const tmeTimeLock = await TMETimeLock.deployed();
// console.log('TMETimeLock', tmeTimeLock.address);
// await tmeTimeLock.setTokenAdd(tmeToken.address);
// const now = Math.floor(Date.now()/1000);
// console.log("now", now);
// await tmeToken.approve(tmeTimeLock.address, "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
// const allowance = await tmeToken.allowance(accounts[0],tmeTimeLock.address);
// console.log("time lock allowance", allowance.toString());
// await tmeTimeLock.lock(ether(1), now+60);
// console.log("locked");
// var devBal = await tmeToken.balanceOf(accounts[0]);
// console.log("devBal", devBal.toString());
// var timelockBal = await tmeToken.balanceOf(tmeTimeLock.address);
// console.log("timeLockBal", timelockBal.toString());
// var numBatches = await tmeTimeLock.numBatches();
// for (var i = 0; i < numBatches; i+=1){
// batches = await tmeTimeLock.batches(i);
// console.log(batches.owner, batches.amount.toString(), batches.time.toString(), batches.spent)
// }
}
catch(error) {
console.log(error)
}
callback()
} | f4013c0660a19313a38bc9ae856201fec4a77d53 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | bbshark99/TMEDeployment | bd7fca09027864472c2fe18a0dac3bca51b68d04 | 55b39d4d2ec063f6eadaab1e9a87f7f09a0e14ca |
refs/heads/main | <repo_name>HarshMathur86/Telegram-news-bot-using-dialogflow<file_sep>/code/app.py
"""
Simple Bot to reply to Telegram messages.
First, a few handler functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
Then, the bot is started and runs until we press Ctrl-C on the command line.
Usage:
Basic Conversational Bot example, repeats stikers as echo.
and Send News of different languages from whole world.
"""
import logging
import time
from telegram import Update, ForceReply, Bot, ReplyKeyboardMarkup
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext, Dispatcher
from utlis import get_reply, fetch_news, topics_keyboard
# Enable logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
logger = logging.getLogger(__name__)
TOKEN = "YOUR_TELEGRAM_BOT_TOKEN"
# Define a few command handlers. These usually take the two arguments update and
# context.
def start(update: Update, _: CallbackContext) -> None:
"""Send a message when the command /start is issued."""
#send a hi sticker
with open("hi.tgs", "rb") as sticker:
update.message.reply_sticker(sticker)
user = update.effective_user
update.message.reply_markdown_v2(
fr'Hi {user.mention_markdown_v2()}\!',
reply_markup=ForceReply(selective=False),
)
update.message.reply_text("Just click - /news")
def help_command(update: Update, _: CallbackContext) -> None:
"""Send a message when the command /help is issued."""
update.message.reply_text("Here to help you\n\nJust click - /news & you will get suggestions😊\n\nLanguages📚 supported-\n English, Hindi, Tamil, Malayalam, Bengali & foreign languages\n\nSome basic conversation🗣 is possible\n\nAnd for news these are some basic commands for bot-\nIndian news in hindi\nTech news in Malayalam\nBusiness news in Bengali\nNews around the world in hindi\n\nHope you like it\n\nJust type forward slash(/) for more task and GitHub link\n\n -<NAME>")
def news(update: Update, _: CallbackContext) -> None:
"""Send a message when the command /news is issued."""
with open("news.tgs", "rb") as sticker:
update.message.reply_sticker(sticker)
update.message.reply_text('Choose a category!', reply_markup=ReplyKeyboardMarkup(keyboard=topics_keyboard, one_time_keyboard=True) )
def creator(update: Update, _: CallbackContext) -> None:
"""Send a message when the command /creator is issued."""
with open("create.tgs", "rb") as sticker:
update.message.reply_sticker(sticker)
update.message.reply_text('<NAME>\n-Lakshmi Narain College of Technology')
def backend(update: Update, _: CallbackContext) -> None:
"""Send a message when the command /backend is issued."""
with open("duck.tgs", "rb") as sticker:
update.message.reply_sticker(sticker)
update.message.reply_text('This bot uses following tech-tools : \n\n - Python telegram library is heart of this bot\n\n - Dialogflow API for conversation\n\n - More than one dozen python libraries to perform different tasks like finding news, creating echo sticker messages to processing different parameters of test case like language, country etc.\n\n - Heroku Cloud Platform is used to host this bot\n\nand many more.')
def github(update: Update, _: CallbackContext) -> None:
"""Send a message when the command /githu is issued."""
update.message.reply_text('😺😺😺\nhttps://github.com/HarshMathur86/Telegram-news-bot-using-dialogflow')
def reply_text(update: Update, _: CallbackContext) -> None:
"""Reply the message."""
intent, reply = get_reply(update.message.text, update.message.chat_id)
if intent == "get_news":
articles = fetch_news(reply)
if len(articles) == 0:
update.message.reply_text("Sorry news server isn't responding. 🥺\n Try to tell different")
return
for article in articles:
update.message.reply_text(article.get('link'))
else:
update.message.reply_text(reply)
print(CallbackContext)
def echo_sticker(update: Update, _: CallbackContext) -> None:
"""Echo the user message."""
update.message.reply_sticker(update.message.sticker)
update.message.reply_text("Take this back 😆")
print(CallbackContext, end='')
print(" echo_message : ", end='')
print(update.message.sticker, end='\n\n')
def main() -> None:
updater = Updater(TOKEN)
dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler("start", start))
dispatcher.add_handler(CommandHandler("help", help_command))
dispatcher.add_handler(CommandHandler("creator", creator))
dispatcher.add_handler(CommandHandler("news", news))
dispatcher.add_handler(CommandHandler("backend", backend))
dispatcher.add_handler(CommandHandler("github", github))
dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, reply_text))
dispatcher.add_handler(MessageHandler(Filters.sticker & ~Filters.command, echo_sticker))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()<file_sep>/README.md
# Telegram-news-bot-using-dialogflow
<h3>
Python based news telling bot
<a href="https://t.me/Harshs_news_bot">Link to bot</a>
</h3>
<br><br>
<img src="https://github.com/HarshMathur86/Telegram-news-bot-using-dialogflow/blob/main/photo_2021-04-08_12-20-55.jpg" width="225" height="395"/>
<img src="https://github.com/HarshMathur86/Telegram-news-bot-using-dialogflow/blob/main/photo_2021-04-08_12-20-52.jpg" width="225" height="395"/>
<img src="https://github.com/HarshMathur86/Telegram-news-bot-using-dialogflow/blob/main/photo_2021-04-08_12-20-34.jpg" width="225" height="395"/>
<img src="https://github.com/HarshMathur86/Telegram-news-bot-using-dialogflow/blob/main/photo_2021-04-08_12-20-49.jpg" width="225" height="395"/>
<img src="https://github.com/HarshMathur86/Telegram-news-bot-using-dialogflow/blob/main/photo_2021-04-08_12-20-37.jpg" width="225" height="395"/>
<img src="https://github.com/HarshMathur86/Telegram-news-bot-using-dialogflow/blob/main/photo_2021-04-08_12-20-42.jpg" width="225" height="395"/>
<img src="https://github.com/HarshMathur86/Telegram-news-bot-using-dialogflow/blob/main/photo_2021-04-08_12-20-45.jpg" width="225" height="395"/>
<img src="https://github.com/HarshMathur86/Telegram-news-bot-using-dialogflow/blob/main/photo_2021-04-08_12-19-49.jpg" width="225" height="395"/>
<file_sep>/code/requirements.txt
APScheduler==3.6.3
cachetools==4.2.1
certifi==2020.12.5
chardet==4.0.0
click==7.1.2
dialogflow==1.1.0
feedparser==6.0.2
Flask==1.1.2
fuzzywuzzy==0.18.0
gnewsclient==1.12
google-api-core==1.26.3
google-auth==1.28.0
googleapis-common-protos==1.53.0
grpcio==1.36.1
gunicorn==20.1.0
idna==2.10
itsdangerous==1.1.0
Jinja2==2.11.3
MarkupSafe==1.1.1
packaging==20.9
protobuf==3.15.7
pyasn1==0.4.8
pyasn1-modules==0.2.8
pyparsing==2.4.7
python-Levenshtein==0.12.2
python-telegram-bot==13.4.1
pytz==2021.1
requests==2.25.1
rsa==4.7.2
sgmllib3k==1.0.0
six==1.15.0
tornado==6.1
tzlocal==2.1
urllib3==1.26.4
Werkzeug==1.0.1
| 3fc36b129c24f8eb8479d9d8245968d3d909c432 | [
"Markdown",
"Python",
"Text"
] | 3 | Python | HarshMathur86/Telegram-news-bot-using-dialogflow | 9e64dbe525a4254aaf6da93024a48ce2e1b7274d | 96dd2ac2a789c426d512e613c9c80218e7a0a161 |
refs/heads/master | <repo_name>kris-L/BleDemo<file_sep>/src/com/xw/ble/instruct/BtInstructionType.java
package com.xw.ble.instruct;
/**
* @ClassName InstructionType
* @Description 指令类型
* @author kris
* @date 2017-08-28 上午 10:00:04
*/
public enum BtInstructionType {
/**
* 读取外围设备版本号,00-00
*/
Peripheral_Version,
/**
* 心跳包,10-01
*/
MCUMTK_MSG,
/**
* 输入输出设备读取,10-10
*/
InputOutputDevice_Read,
/**
* 读取安全带输入状态,10-30
*/
Safty_Belt_Status,
/**
* 读取ch输入状态,10-31
*/
CH_Status,
/**
* 读取脚刹车输入状态,10-32
*/
Foot_Brake_Status,
/**
* 读取Door负输入状态,10-33
*/
Minus_Door_Status,
/**
* 读取Brake输入状态,10-34
*/
Brake_Status,
/**
* 读取大灯的输入状态输入状态,10-35
*/
Headlight_State,
/**
* 读取F_Light(远光灯)输入状态,10-36
*/
F_Light_Status,
/**
* 读取L_Light(左转向灯)输入状态,10-37
*/
L_Light_Status,
/**
* 读取R_Light(右转向灯)输入状态,10-38
*/
R_Light_Status,
/**
* 读取Speaker输入状态,10-39
*/
Speaker_Status,
/**
* 读取ACC输入状态,10-3A
*/
ACC_Status,
/**
* 读取Reverse(倒车)输入状态,10-3B
*/
Reverse_Status,
/**
* 读取def的输入状态,10-3C
*/
DEF_Status,
/**
* 读取door正输入状态,10-3D
*/
Plus_DOOR_Status,
/**
* 读取hand输入状态,10-3E
*/
Hand_State,
/**
* 读取负触发输入状态,10-3F
*/
Negative_Trigger,
/**
* 油料的数量百分比,10-61
*/
Gasoline_Percent,
/**
* MCU执行指纹比对,10-62
*/
Contrast_Fingerprint,
/**
* MCU给安卓主机提示卡插入或拔出,10-63
*/
Prompt_Card_Status,
/**
* MCU提示读取IC卡故障代码,10-64
*/
IC_Card_ErrorCode,
/**
* MCU读取喊话器和耳机状态,10-65
*/
MegaphoneHeadset_Status,
/**
* MCU给安卓主机提示卡插入或拔出 10-66
*/
IC_Card_Status,
/**
* 非接触式IC卡读指令 10-70
*/
Control_ReadNoncontactIC,
/**
* 接触式IC卡读指令 10-71
*/
Control_ReadContactIC,
/**
* 安卓主机控制功放电源输出,20-4A
*/
Control_AmplifierPower,
/**
* 安卓主机控制高电压Lock输出,20-51
*/
Control_HighVoltageLock,
/**
* 安卓主机控制高电压UnLock输出,20-52
*/
Control_HighVoltageUnlock,
/**
* 安卓主机控制CTRL_ELE输出,20-53
*/
Control_CTRL_ELE,
/**
* 安卓主机控制CuteOFF_L输出,20-54
*/
Control_CuteOFF_L,
/**
* 安卓主机控制CuteOFF_H输出,20-55
*/
Control_CuteOFF_H,
/**
* 安卓主机控制内置电池的供电输出,20-56
*/
Control_CellIn,
/**
* 安卓主机控制UART3电源输出,20-57
*/
Control_PowerUART3,
/**
* 安卓主机控制USB电源输出,20-58
*/
Control_PowerUSB,
/**
* 安卓主机设置指纹比对等级,20-59
*/
Control_FingerprintLevel,
/**
* 安卓主机控制音频功放,20-5A
*/
Control_Audio,
/**
* 安卓主机控制,开启/关闭指纹设备,20-5B
*/
Control_FingerprintDevice,
/**
* 安卓主机控制MCU外围IO输出,20-5F
*/
Control_IOOutputVoltage,
/**
*安卓主机要求读取户的指纹信息,20-61
*/
Control_FingerprintAsk,
/**
* 安卓主机查询喊话器和耳机选择状态,20-62
*/
Control_MegaphoneHeadset,
/**
* 安卓主机查询MCU外围输入接口的状态,20-63
*/
ALL_Above,
/**
* 安卓主机查询引擎转速RPM,20-64
*/
Control_EngineRPM,
/**
* 安卓主机要求MCU把采集的指纹数据上传,20-65
*/
Control_FingerprintUpload,
/**
* 安卓主机下发已有的指纹信息给MCU做比对应用,20-66
*/
Control_FingerprintCompare,
/**
* 安卓主机下发指令(不含指纹信息数)给MCU做比对应用,20-67
*/
Control_FingerprintCompareNo,
/**
* 非接触式IC写指令 20-70
*/
Control_WriteNoncontactIC,
/**
* 接触式IC写指令 20-71
*/
Control_WritecontactIC,
/**
* MCU外围串口1波特率设置,20-80
*/
Control_SerialPort1,
/**
* MCU外围串口2波特率设置,20-81
*/
Control_SerialPort2,
/**
* MCU外围串口3波特率设置,20-82
*/
Control_SerialPort3,
/**
* MCU外围CAN总线波特率设置,20-83
*/
Control_SerialPortCAN,
/**
* MCU外围RS485波特率设置,20-84
*/
Control_SerialPortRS485,
/**
* 输入数据到RS485
*/
RS485_Input,
/**
* MCU外围串口1输出数据,30-20
*/
Control_SendSerialPort1,
/**
* MCU外围串口2输出数据,30-2
*/
Control_SendSerialPort2,
/**
* MCU外围串口3输出数据,30-2
*/
Control_SendSerialPort3,
/**
* MCU外围串口RS485输出数据,30-2
*/
Control_SendSerialPortRS485,
/**
* 发送配对ID
*/
Control_SendPassword,
/**
* 控制小信号负输出,20-5C
*/
Control_Signal_Negative_Output
}
<file_sep>/src/com/xw/ble/utils/MsgHandlerTools.java
package com.xw.ble.utils;
import java.util.ArrayList;
import java.util.List;
public class MsgHandlerTools {
/**
* @Title xorSum
* @Description ���
* @author �����
* @date 2015-9-30 ����2:03:14
* @param dataArray
* @param length
* @return
*/
public static byte xorSum(byte[] dataArray, int length) {
byte sum = (byte) (dataArray[0]^dataArray[1]);
for(int i=2 ;i<length;i++){
sum= (byte) (sum^dataArray[i]);
}
return (byte) ~sum;
}
public static byte checkSum(byte[] dataArray) {
byte sum = 0;
for(int i=0;i<dataArray.length;i++){
sum += dataArray[i];
}
return (byte) ~sum;
}
public static List<byte[]> cutPackage(byte[] data){
int len = data.length/20;
int endLen = data.length%20;
if(endLen>0){
len +=1;
}
int index = 0;
List<byte[]> dataList = new ArrayList<byte[]>();
for(int i=0;i<len;i++){
if(i==len-1&&endLen!=0){
byte[] bytes = new byte[endLen];
System.arraycopy(data, index, bytes, 0, bytes.length);
dataList.add(bytes);
}else{
byte[] bytes = new byte[20];
System.arraycopy(data, index, bytes, 0, bytes.length);
index += bytes.length;
dataList.add(bytes);
}
}
return dataList;
}
}
<file_sep>/src/com/xw/ble/service/BTWorkService.java
package com.xw.ble.service;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.xw.ble.Const;
import com.xw.ble.RecvDataListener;
import com.xw.ble.utils.Hex2ByteUtil;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
/**
* 观察者模式
*
* @author Administrator
*
*/
public class BTWorkService extends Service implements RecvDataListener {
private static final String TAG = "BTWorkService";
// Service和workThread通信用mHandler
public static BTWorkThread workThread = null;
private static Handler mHandler = null;
private static List<Handler> targetsHandler = new ArrayList<Handler>(5);
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
Log.e(TAG, "onCreate");
mHandler = new MHandler(this);
workThread = new BTWorkThread(this, mHandler, this);
workThread.start();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
Message msg = Message.obtain();
msg.what = Const.MSG_ALLTHREAD_READY;
notifyHandlers(msg);
return START_STICKY;
}
@Override
public void onDestroy() {
workThread.unregisterBroadcast();
workThread.disconnect();
workThread.close();
workThread.quit();
workThread = null;
Log.v("DrawerService", "onDestroy");
}
static class MHandler extends Handler {
WeakReference<BTWorkService> mService;
MHandler(BTWorkService service) {
mService = new WeakReference<BTWorkService>(service);
}
@Override
public void handleMessage(Message msg) {
notifyHandlers(msg);
}
}
/**
*
* @param handler
*/
public static void addHandler(Handler handler) {
if (!targetsHandler.contains(handler)) {
targetsHandler.add(handler);
}
}
/**
*
* @param handler
*/
public static void delHandler(Handler handler) {
if (targetsHandler.contains(handler)) {
targetsHandler.remove(handler);
}
}
/**
*
* @param msg
*/
public static void notifyHandlers(Message msg) {
for (int i = 0; i < targetsHandler.size(); i++) {
Message message = Message.obtain(msg);
targetsHandler.get(i).sendMessage(message);
}
}
@Override
public void setData(String hexStr) {
if (!"41542B030110010131470D0A".equals(hexStr)) {
Log.d(TAG, "setData="+hexStr);
}
// TODO Auto-generated method stub
// hexStr 格式:AT+, Source, destination, command, parameter number,parameter, data number, data, checksum,\r\n
// 具体参考 :蓝牙通信协议
}
/**
* @Title getByteArrayOnlyData
* @Description 返回数据,不返回时间(数据为gbk转码)
* @author jw
* @date 2015-12-1 上午9:27:40
* @param bData
* @return
*/
private String getByteArrayOnlyData(byte[] bData) {
String sData = "";
int iCount = getCountD2(bData);
if (iCount >= 5) {
byte[] bOnlyData = new byte[bData.length - 11];
System.arraycopy(bData, 11, bOnlyData, 0, bData.length - 11);
try {
sData = new String(bOnlyData, "GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
try {
sData = new String(bData, "GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return sData;
}
/**
* @Title getByteArrayHexOnlyData
* @Description 返回数据,不返回时间(数据为16进制字符串)
* @author jw
* @date 2015-12-2 上午9:44:36
* @param bData
* @return
*/
private String getByteArrayHexOnlyData(byte[] bData) {
String sData = "";
int iCount = getCountD2(bData);
if (iCount >= 5) {
byte[] bOnlyData = new byte[bData.length - 11];
System.arraycopy(bData, 11, bOnlyData, 0, bData.length - 11);
sData = Hex2ByteUtil.bytesToHexString(bOnlyData);
} else {
sData = Hex2ByteUtil.bytesToHexString(bData);
}
return sData;
}
private int getCountD2(byte[] bData) {
int i = 0;
String str = Hex2ByteUtil.bytesToHexString(bData);
Pattern p = Pattern.compile("(\\w{2})");
Matcher m = p.matcher(str);
while (m.find()) {
if (m.group().equals("2D")) {
i = i + 1;
}
}
return i;
}
}
<file_sep>/src/com/xw/ble/BleServiceActivity.java
package com.xw.ble;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;
import com.xw.ble.utils.Hex2ByteUtil;
import com.xw.ble.utils.MyQueue;
import com.xw.ble.utils.OutputStringUtil;
import com.xw.bledemo.R;
import com.xw.bluetooth.ChatActivity;
import com.xw.bluetooth.DeviceBean;
import com.xw.bluetooth.DeviceListAdapter;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattServer;
import android.bluetooth.BluetoothGattServerCallback;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.BluetoothLeAdvertiser;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
@SuppressLint("NewApi")
public class BleServiceActivity extends Activity implements OnClickListener {
private final static String TAG = "BleServiceActivity";
private static final int STATUS_CONNECT = 0x11;
private ListView mListView;
private ArrayList<DeviceBean> mDatas;
private DeviceListAdapter mDeviceListAdapter;
private BluetoothAdapter mBluetoothAdapter;
private EditText mEtMsg;
private Button mBtnSend;// 发送按钮
private Button mBtnDisconn;// 断开连接
private BluetoothGattServer mGattServer;
private BluetoothLeAdvertiser mLeAdvertiser;
private BluetoothAdapter mAdapter;
private BluetoothManager mManager;
private final String UUID_DATA_SERVICE = "0003cdd0-0000-1000-8000-00805f9b0131";
private final String UUID_READ = "0003cdd1-0000-1000-8000-00805f9b0131";
private final String UUID_WRITE = "0003cdd2-0000-1000-8000-00805f9b0131";
private final static String UUID_CONFIG = "00002902-0000-1000-8000-00805f9b34fb";
// --线程类-----------------
private ServerThread mServerThread;
public MyQueue myQueue;
private BluetoothGattCharacteristic characteristicRead;
private BluetoothGattCharacteristic characteristicWrite;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat);
initViews();
initDatas();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
private void initDatas() {
mDatas = new ArrayList<DeviceBean>();
mDeviceListAdapter = new DeviceListAdapter(this, mDatas);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mListView.setAdapter(mDeviceListAdapter);
mListView.setFastScrollEnabled(true);
if(null == mManager) {
mManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
}
// if(false == getPackageManager().
// hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE))
if(null == mAdapter) {
mAdapter = mManager.getAdapter();
}
//判断支持不支持BLE Peripheral
if(false == mAdapter.isMultipleAdvertisementSupported()){
Log.e(TAG,"不支持BLE Peripheral");
}
myQueue = new MyQueue();
myQueue.setmRecvDataListener(mRecvDataListener);
startAdvertise();
}
private RecvDataListener mRecvDataListener = new RecvDataListener() {
@Override
public void setData(String data) {
// TODO Auto-generated method stub
}
};
private void initViews() {
mListView = (ListView) findViewById(R.id.list);
mEtMsg = (EditText) findViewById(R.id.MessageText);
mEtMsg.clearFocus();
mBtnSend = (Button) findViewById(R.id.btn_msg_send);
mBtnSend.setOnClickListener(this);
mBtnDisconn = (Button) findViewById(R.id.btn_disconnect);
}
// 开启服务器
private class ServerThread extends Thread {
public void run() {
Log.e(TAG,"启动服务监听");
startAdvertise();
}
};
/**
* 信息处理
*/
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
String info = (String) msg.obj;
switch (msg.what) {
case STATUS_CONNECT:
Toast.makeText(BleServiceActivity.this, info, 0).show();
break;
}
if (msg.what == 1) {
mDatas.add(new DeviceBean(info, true));
mDeviceListAdapter.notifyDataSetChanged();
mListView.setSelection(mDatas.size() - 1);
}else {
mDatas.add(new DeviceBean(info, false));
mDeviceListAdapter.notifyDataSetChanged();
mListView.setSelection(mDatas.size() - 1);
}
}
};
@SuppressLint("NewApi")
private AdvertiseCallback mAdvCallback = new AdvertiseCallback() {
@Override
public void onStartFailure(int errorCode) {
Log.e(TAG, "onStartFailure");
Message msg = new Message();
msg = new Message();
msg.obj = "服务端已断开";
msg.what = STATUS_CONNECT;
mHandler.sendMessage(msg);
}
@Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
Log.e(TAG, "onStartSuccess");
Message msg = new Message();
msg = new Message();
msg.obj = "服务端已监听";
msg.what = STATUS_CONNECT;
mHandler.sendMessage(msg);
};
};
@SuppressLint("NewApi")
private final BluetoothGattServerCallback mGattServerCallback = new BluetoothGattServerCallback() {
@Override
public void onConnectionStateChange(BluetoothDevice device, int status,
int newState) {
// Log.e(TAG,
// "Our gatt server connection state changed, new state ");
// Log.e("GattServer", Integer.toString(newState));
super.onConnectionStateChange(device, status, newState);
Log.e(TAG, "Connected to GATT server,status:" + status
+ " newState:" + newState);
if (newState == BluetoothProfile.STATE_CONNECTED)// 连接成功
{
try {
Message msg = new Message();
msg = new Message();
msg.obj = "蓝牙:"+device.getAddress()+"已连接";
msg.what = STATUS_CONNECT;
mHandler.sendMessage(msg);
} catch (Exception e) {
// TODO: handle exception
Log.e(TAG,
" mBluetoothGatt.requestMtu(41) error:"
+ e.getMessage());
}
} else if (newState == BluetoothProfile.STATE_DISCONNECTED)// 连接失败
{
// mBluetoothGatt.requestMtu(20);
if(device != null){
Message msg = new Message();
msg = new Message();
msg.obj = "蓝牙:"+device.getAddress()+"连接失败";
msg.what = STATUS_CONNECT;
mHandler.sendMessage(msg);
}
}
}
@Override
public void onServiceAdded(int status, BluetoothGattService service) {
Log.d(TAG, "Our gatt server service was added.");
super.onServiceAdded(status, service);
}
@Override
public void onCharacteristicReadRequest(BluetoothDevice device,
int requestId, int offset,
BluetoothGattCharacteristic characteristic) {
Log.e(TAG, "Our gatt characteristic was read.");
super.onCharacteristicReadRequest(device, requestId, offset,
characteristic);
mGattServer.sendResponse(device, requestId,
BluetoothGatt.GATT_SUCCESS, offset,
characteristic.getValue());
broadcastUpdateData(characteristic);
}
@Override
public void onCharacteristicWriteRequest(BluetoothDevice device,
int requestId, BluetoothGattCharacteristic characteristic,
boolean preparedWrite, boolean responseNeeded, int offset,
byte[] value) {
Log.e(TAG,
"We have received a write request for one of our hosted characteristics");
// Log.e(TAG, "data = " + value.toString());
super.onCharacteristicWriteRequest(device, requestId,
characteristic, preparedWrite, responseNeeded, offset,
value);
//发送响应,不然会阻塞
mGattServer.sendResponse(device, requestId,
BluetoothGatt.GATT_SUCCESS, offset,
characteristic.getValue());
String data = Hex2ByteUtil.bytesToHexString(value);
Log.e(TAG, "收到:"+data);
// characteristicRead.setValue(value);
// mGattServer.notifyCharacteristicChanged(device, characteristicRead, false);
characteristicWrite.setValue(value);
mGattServer.notifyCharacteristicChanged(device, characteristicWrite, false);
//4.处理响应内容
// onResponseToClient(value, device, requestId, characteristic);
}
@Override
public void onNotificationSent(BluetoothDevice device, int status) {
Log.e(TAG, "onNotificationSent");
super.onNotificationSent(device, status);
}
@Override
public void onDescriptorReadRequest(BluetoothDevice device,
int requestId, int offset, BluetoothGattDescriptor descriptor) {
Log.e(TAG, "Our gatt server descriptor was read.");
super.onDescriptorReadRequest(device, requestId, offset, descriptor);
}
@Override
public void onDescriptorWriteRequest(BluetoothDevice device,
int requestId, BluetoothGattDescriptor descriptor,
boolean preparedWrite, boolean responseNeeded, int offset,
byte[] value) {
Log.e(TAG, "Our gatt server descriptor was written.");
super.onDescriptorWriteRequest(device, requestId, descriptor,
preparedWrite, responseNeeded, offset, value);
}
@Override
public void onExecuteWrite(BluetoothDevice device, int requestId,
boolean execute) {
Log.e(TAG, "Our gatt server on execute write.");
super.onExecuteWrite(device, requestId, execute);
}
};
/* 接收的数据 */
public void broadcastUpdateData(final BluetoothGattCharacteristic characteristic) {
Log.e(TAG, "broadcastUpdateData=");
// 从特征值获取数据
final byte[] sourceData = characteristic.getValue();
if (myQueue != null && sourceData != null) {
myQueue.RecvData(sourceData);
}
String data = Hex2ByteUtil.bytesToHexString(characteristic.getValue());
Log.e(TAG, "接收数据data="+data);
}
@SuppressLint("NewApi")
public void startAdvertise() {
if (null == mAdapter)
return;
if (null == mLeAdvertiser) {
mLeAdvertiser = mAdapter.getBluetoothLeAdvertiser();
}
if (null == mLeAdvertiser)
return;
AdvertiseSettings.Builder settingBuilder;
settingBuilder = new AdvertiseSettings.Builder();
settingBuilder.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY);
settingBuilder.setConnectable(true);
settingBuilder.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH);
AdvertiseData.Builder advBuilder;
advBuilder = new AdvertiseData.Builder();
mAdapter.setName("HUD"); // 8 characters works, 9+ fails
Log.e(TAG, "mAdapter.getAddress()="+mAdapter.getAddress());
advBuilder.setIncludeDeviceName(true);
mGattServer = mManager.openGattServer(this, mGattServerCallback);
// addDeviceInfoService(mGattServer);
characteristicRead = new BluetoothGattCharacteristic(
UUID.fromString(UUID_READ),
BluetoothGattCharacteristic.PROPERTY_READ|BluetoothGattCharacteristic.PROPERTY_NOTIFY,
BluetoothGattCharacteristic.PERMISSION_READ);
characteristicWrite = new BluetoothGattCharacteristic(
UUID.fromString(UUID_WRITE),
BluetoothGattCharacteristic.PROPERTY_WRITE|BluetoothGattCharacteristic.PROPERTY_NOTIFY,
BluetoothGattCharacteristic.PERMISSION_WRITE);
BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor(
UUID.fromString(UUID_CONFIG),
BluetoothGattCharacteristic.PROPERTY_NOTIFY);
characteristicRead.addDescriptor(descriptor);
BluetoothGattService AService = new BluetoothGattService(
UUID.fromString(UUID_DATA_SERVICE),
BluetoothGattService.SERVICE_TYPE_PRIMARY);
AService.addCharacteristic(characteristicRead);
AService.addCharacteristic(characteristicWrite);
if(AService == null){
Log.e(TAG, "AService==null");
}
// Add notify characteristic here !!!
mGattServer.addService(AService);
mLeAdvertiser.startAdvertising(settingBuilder.build(),
advBuilder.build(), mAdvCallback);
}
@SuppressLint("NewApi")
public void stopAdvertise() {
if (null != mLeAdvertiser)
mLeAdvertiser.stopAdvertising(mAdvCallback);
mLeAdvertiser = null;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.btn_msg_send:
break;
}
}
}
<file_sep>/src/com/xw/bluetooth/AndroidTest.java
package com.xw.bluetooth;
import com.xw.bledemo.R;
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.Toast;
public class AndroidTest extends Activity {
private NetWorkChangeReceiver networkChangeReceiver;
private final static String TAG = "AndroidTest";
private AudioManager mAudioManager;
private int max;
private int current;
private String ACTION_VOLUME_CHANGED = "android.media.VOLUME_CHANGED_ACTION";
private String ACTION_MEDIA_BUTTON = "android.intent.action.MEDIA_BUTTON";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ble_test);
initView();
initData();
}
private void initView() {
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// 获取手机当前音量值
current = mAudioManager.getStreamVolume(AudioManager.STREAM_SYSTEM);
Log.e(TAG, "keyCode=" + keyCode);
switch (keyCode) {
// 音量减小
case KeyEvent.KEYCODE_VOLUME_DOWN:
Toast.makeText(this, "当前音量值: " + current, Toast.LENGTH_SHORT)
.show();
return true;
// 音量增大
case KeyEvent.KEYCODE_VOLUME_UP:
Toast.makeText(this, "当前音量值: " + current, Toast.LENGTH_SHORT)
.show();
return true;
}
return super.onKeyDown(keyCode, event);
}
private void initData() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ACTION_VOLUME_CHANGED);
intentFilter.addAction(ACTION_MEDIA_BUTTON);
networkChangeReceiver = new NetWorkChangeReceiver();
registerReceiver(networkChangeReceiver, intentFilter);
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);// 1
current = mAudioManager.getStreamVolume(AudioManager.STREAM_SYSTEM);
Log.e("service", "系统音量值:" + max + "-" + current);
}
class NetWorkChangeReceiver extends BroadcastReceiver {
@Override
// 接收到广播后,要执行的代码
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_MEDIA_BUTTON.equals(action)) {
// 获得KeyEvent对象
KeyEvent keyEvent = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
Log.e(TAG, "Action ---->" + action + " KeyEvent----->"+ keyEvent.toString());
}
if (ACTION_VOLUME_CHANGED.equals(action)) {
Log.e(TAG, "音量改变 ");
current = mAudioManager
.getStreamVolume(AudioManager.STREAM_SYSTEM);
Log.e("service", "系统音量值:" + max + "-" + current);
Toast.makeText(context, "音量改变 ", Toast.LENGTH_LONG).show();
}
}
}
}
<file_sep>/src/com/xw/ble/service/BTWorkThread.java
package com.xw.ble.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import com.xw.ble.RecvDataListener;
import com.xw.ble.utils.Hex2ByteUtil;
import com.xw.ble.utils.MsgHandlerTools;
import com.xw.ble.utils.MyQueue;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;
@SuppressLint("NewApi") public class BTWorkThread extends Thread {
private static final String TAG = "WorkThread";
private static Looper mLooper = null;
public static Handler targetHandler = null;
// private static boolean threadInitOK = false;
private static boolean isConnecting = false;
public boolean isConnect = false;
private static final int STATE_DISCONNECTED = 0;
private static final int STATE_CONNECTING = 1;
private static final int STATE_CONNECTED = 2;
public final static String ACTION_GATT_CONNECTED = "com.hc_ble.bluetooth.le.ACTION_GATT_CONNECTED";
public final static String ACTION_GATT_DISCONNECTED = "com.hc_ble.bluetooth.le.ACTION_GATT_DISCONNECTED";
public final static String ACTION_GATT_SERVICES_DISCOVERED = "com.hc_ble.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
public final static String ACTION_DATA_AVAILABLE = "com.hc_ble.bluetooth.le.ACTION_DATA_AVAILABLE";
public final static String EXTRA_DATA = "com.hc_ble.bluetooth.le.EXTRA_DATA";
public final static String UUID_SERVICE_MAIN = "0003cdd0-0000-1000-8000-00805f9b0131";
public final static String UUID_DATA_READ = "0003cdd1-0000-1000-8000-00805f9b0131";
public final static String UUID_DATA_WRITE = "0003cdd2-0000-1000-8000-00805f9b0131";
public final static String UUID_CONF = "00002902-0000-1000-8000-00805f9b34fb";
private static BluetoothGattCharacteristic character_read = null;
private static BluetoothGattCharacteristic character_write = null;
private static BluetoothGattCharacteristic character_notify = null;
private Context mContext;
private BluetoothManager mBluetoothManager;
public BluetoothAdapter mBluetoothAdapter;
private String mBluetoothDeviceAddress;
public static BluetoothGatt mBluetoothGatt;
private BluetoothGattService bluetoothGattService;
private Boolean isSet = false;
private int mConnectionState = STATE_DISCONNECTED;
private long lastTime = 0;
private String bufferData = "";
private boolean isLastData = false;
private int length = 0;
public static boolean isnotify = false;
private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
// 定义
public static boolean isFirst = true;
public RecvDataListener mRecvDataListener;
public MyQueue myQueue;
public BTWorkThread(Context mContext, Handler handler) {
// threadInitOK = false;
this.mContext = mContext;
targetHandler = handler;
initialize();
registerBroadcast();
}
public BTWorkThread(Context mContext, Handler handler,
RecvDataListener mRecvDataListener) {
// threadInitOK = false;
this.mContext = mContext;
targetHandler = handler;
this.mRecvDataListener = mRecvDataListener;
initialize();
registerBroadcast();
}
@Override
public void start() {
super.start();
// while (!threadInitOK)
// ;
}
/* service 中蓝牙初始化 */
public boolean initialize() {
if (mBluetoothManager == null) { // 获取系统的蓝牙管理器
mBluetoothManager = (BluetoothManager) mContext
.getSystemService(Context.BLUETOOTH_SERVICE);
if (mBluetoothManager == null) {
Log.e(TAG, "Unable to initialize BluetoothManager.");
return false;
}
}
mBluetoothAdapter = mBluetoothManager.getAdapter();
if (mBluetoothAdapter == null) {
Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
return false;
}
Log.e(TAG, "bluetooth initialize successful.");
myQueue = new MyQueue();
myQueue.setmRecvDataListener(mRecvDataListener);
return true;
}
// 连接远程蓝牙
public boolean connect(final String address) {
if (mBluetoothAdapter == null || address == null) {
Log.e(TAG,
"BluetoothAdapter not initialized or unspecified address.");
return false;
}
// Previously connected device. Try to reconnect.
if (mBluetoothDeviceAddress != null
&& address.equals(mBluetoothDeviceAddress)
&& mBluetoothGatt != null) {
Log.e(TAG,
"Trying to use an existing mBluetoothGatt for connection.");
isSet = false;
if (mBluetoothGatt.connect())// 连接蓝牙,其实就是调用BluetoothGatt的连接方法
{
mConnectionState = STATE_CONNECTING;
return true;
} else {
return false;
}
}
/* 获取远端的蓝牙设备 */
final BluetoothDevice device = mBluetoothAdapter
.getRemoteDevice(address);
if (device == null) {
Log.e(TAG, "Device not found. Unable to connect.");
return false;
}
// We want to directly connect to the device, so we are setting the
// autoConnect
// parameter to false.
/* 调用device中的connectGatt连接到远程设备 */
mBluetoothGatt = device.connectGatt(mContext, false, mGattCallback);
Log.e(TAG, "Trying to create a new connection.");
mBluetoothDeviceAddress = address;
isSet = true;
// Boolean flg = mBluetoothGatt.requestMtu(40);
// final Intent intent = new Intent(ACTION_DATA_AVAILABLE);
// intent.putExtra(EXTRA_DATA,
// "mBluetoothGatt.requestMtu(38) is success?:"+flg);
// sendBroadcast(intent);
mConnectionState = STATE_CONNECTING;
return true;
}
/*
* 取消连接
*/
/**
* @Title: disconnect
* @Description: TODO(取消蓝牙连接)
* @param 无
* @return void
* @throws
*/
public void disconnect() {
Log.e(TAG, "BluetoothGatt disconnect");
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.d(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.disconnect();
}
/**
* @Title: close
* @Description: TODO(关闭所有蓝牙连接)
* @param 无
* @return void
* @throws
*/
public void close() {
if (mBluetoothGatt == null) {
return;
}
mBluetoothGatt.close();
mBluetoothGatt = null;
}
/**
* @Title: readCharacteristic
* @Description: TODO(读取特征值)
* @param @param characteristic(要读的特征值)
* @return void 返回类型
* @throws
*/
public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.e("hyw", "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.readCharacteristic(characteristic);
}
// 写入特征值
public void writeCharacteristic(BluetoothGattCharacteristic characteristic) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.e(TAG, "BluetoothAdapter not initialized");
return;
}
Log.e(TAG,
"write data:"
+ Hex2ByteUtil.bytesToHexString(characteristic
.getValue()));
boolean result = mBluetoothGatt.writeCharacteristic(characteristic);
if(result){
Log.e(TAG, "写入特征值成功");
}else{
Log.e(TAG, "写入特征值失败");
}
}
/**
* @Title: setCharacteristicNotification
* @Description: TODO(设置特征值通变化通知)
* @param @param characteristic(特征值)
* @param @param enabled (使能)
* @return void
* @throws
*/
public void setCharacteristicNotification(
BluetoothGattCharacteristic characteristic, boolean enabled) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.e("hyw", "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
BluetoothGattDescriptor clientConfig = characteristic
.getDescriptor(UUID
.fromString(UUID_CONF));
for (BluetoothGattDescriptor descriptor:characteristic.getDescriptors()){
Log.e(TAG, "BluetoothGattDescriptor: "+descriptor.getUuid().toString());
}
if (enabled) {
clientConfig
.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
} else {
clientConfig
.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
}
mBluetoothGatt.writeDescriptor(clientConfig);
}
/**
* @Title: getSupportedGattServices
* @Description: TODO(得到蓝牙的所有服务)
* @param @return 无
* @return List<BluetoothGattService>
* @throws
*/
public List<BluetoothGattService> getSupportedGattServices() {
if (mBluetoothGatt == null)
return null;
return mBluetoothGatt.getServices();
}
/* 连接远程设备的回调函数 */
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState) {
String intentAction;
isnotify = false;
isFirst = true;
if (newState == BluetoothProfile.STATE_CONNECTED)// 连接成功
{
Log.e(TAG, "Connected to GATT server,status:" + status
+ " newState:" + newState);
try {
isSet = false;
mBluetoothGatt.discoverServices();
intentAction = ACTION_GATT_CONNECTED;
mConnectionState = STATE_CONNECTED;
isConnect = true;
/* 通过广播更新连接状态 */
broadcastUpdate(intentAction);
} catch (Exception e) {
// TODO: handle exception
Log.e(TAG,
" mBluetoothGatt.requestMtu(41) error:"
+ e.getMessage());
}
} else if (newState == BluetoothProfile.STATE_DISCONNECTED)// 连接失败
{
// mBluetoothGatt.requestMtu(20);
intentAction = ACTION_GATT_DISCONNECTED;
mConnectionState = STATE_DISCONNECTED;
isConnect = false;
disconnect();
Log.e(TAG, "STATE_DISCONNECTED,status:" + status
+ " newState:" + newState);
broadcastUpdate(intentAction);
}
}
@Override
public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
super.onMtuChanged(gatt, mtu, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.e(TAG, "onMtuChanged:" + mtu + " status:" + status);
} else {
Log.e(TAG, "mtu:" + mtu + " status:" + status);
}
mBluetoothGatt.discoverServices();
final Intent intent = new Intent(ACTION_DATA_AVAILABLE);
// 从特征值获取数据
intent.putExtra(EXTRA_DATA, "onMtuChanged:" + "mtu:" + mtu
+ " status:" + status);
mContext.sendBroadcast(intent);
}
/*
* 重写onServicesDiscovered,发现蓝牙服务
*/
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS)// 发现到服务
{
broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
Log.d(TAG, "onServicesDiscoveredSuccess:发现gatt服务" + status);
} else {
Log.d(TAG, "onServicesDiscoveredFail:" + status);
}
}
/*
* 特征值的读写
*/
@Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
// 将数据通过广播到Ble_Activity
broadcastUpdateData(ACTION_DATA_AVAILABLE, characteristic);
Log.e(TAG, "onCharacteristicRead: ,status:" + status);
}
}
/*
* 特征值的改变
*/
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
Log.e("hyw", "onCharacteristicChanged:");
broadcastUpdateData(ACTION_DATA_AVAILABLE, characteristic);
}
};
// 广播意图
private void broadcastUpdate(final String action) {
final Intent intent = new Intent(action);
mContext.sendBroadcast(intent);
}
/* 广播远程发送过来的数据 */
public void broadcastUpdateData(final String action,
final BluetoothGattCharacteristic characteristic) {
// 从特征值获取数据
final byte[] sourceData = characteristic.getValue();
if (myQueue != null && sourceData != null) {
myQueue.RecvData(sourceData);
}
String data = Hex2ByteUtil.bytesToHexString(characteristic.getValue());
final Intent intent = new Intent(action);
if (data == null) {
return;
}
intent.putExtra(EXTRA_DATA, data);
if (!"41542B030110010131470D0A".equals(data)) {
Log.e(TAG, "收到数据:" + data);
}
mContext.sendBroadcast(intent);
// mRecvDataListener.setData(data);
}
private void registerBroadcast() {
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_GATT_CONNECTED);
filter.addAction(ACTION_GATT_DISCONNECTED);
filter.addAction(ACTION_GATT_SERVICES_DISCOVERED);
filter.addAction(ACTION_DATA_AVAILABLE);
mContext.registerReceiver(mGattUpdateReceiver, filter);
}
public void unregisterBroadcast() {
mContext.unregisterReceiver(mGattUpdateReceiver);
}
@Override
public void run() {
Looper.prepare();
mLooper = Looper.myLooper();
if (null == mLooper)
Log.v(TAG, "mLooper is null pointer");
else
Log.v(TAG, "mLooper is valid");
// threadInitOK = true;
Looper.loop();
}
public void quit() {
try {
if (null != mLooper) {
mLooper.quit();
mLooper = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean isConnecting() {
return isConnecting;
}
public boolean isConnect() {
return isConnect;
}
public void setConnect(boolean isConnect) {
this.isConnect = isConnect;
}
public int getConnectionState() {
return mConnectionState;
}
public void writeData(byte[] data) {
if (character_write == null) {
Toast.makeText(mContext, "无相应服务,不能进行写操作", Toast.LENGTH_SHORT)
.show();
if (mBluetoothGatt != null) {
BluetoothGattService service = mBluetoothGatt
.getService(UUID.fromString(UUID_SERVICE_MAIN));
if(service == null){
Log.e(TAG,"service="+service);
return;
}
character_read = service.getCharacteristic(UUID
.fromString(UUID_DATA_READ));
character_notify = service.getCharacteristic(UUID
.fromString(UUID_DATA_READ));
readCharacteristic(character_read);
setCharacteristicNotification(character_notify, true);
Log.e(TAG, "再次初始化相关服务");
Toast.makeText(mContext, "服务已重新打开,请重试", Toast.LENGTH_SHORT)
.show();
} else {
disconnect();
close();
Log.e("hyw", "蓝牙初始化失败,已关闭所有连接");
Toast.makeText(mContext, "蓝牙初始化失败,已关闭所有连接", Toast.LENGTH_SHORT)
.show();
}
return;
}
if (data.length > 20) {
List<byte[]> dataList = MsgHandlerTools.cutPackage(data);
for (int i = 0; i < dataList.size(); i++) {
character_write.setValue(dataList.get(i));
writeCharacteristic(character_write);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return;
} else {
try {
Log.e("messon", "数据包:" + Hex2ByteUtil.bytesToHexString(data));
character_write.setValue(data);
writeCharacteristic(character_write);
} catch (Exception e) {
// TODO: handle exception
}
}
}
/**
* 合并数组
*
* @param a
* @param b
* @return
*/
private static byte[] concat(byte[] a, byte[] b) {
byte[] c = new byte[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
/**
* @Title: displayGattServices
* @Description: TODO(处理蓝牙服务)
* @param 无
* @return void
* @throws
*/
@SuppressLint("NewApi")
private void displayGattServices(List<BluetoothGattService> gattServices) {
Log.d(TAG, "displayGattServices gattServices.size:" + gattServices.size());
if (gattServices == null)
{
Log.e(TAG, "gattServices==null");
return;
}
// 部分层次,所有特征值集合
mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
// Loops through available GATT Services.
int j = 0;
for (BluetoothGattService gattService : gattServices) {
j++;
List<BluetoothGattCharacteristic> gattCharacteristics = gattService
.getCharacteristics();
// 对于当前循环所指向的服务中的每一个特征值
int i = 0;
Log.d(TAG, "service_uuid:" + gattService.getUuid());
if (gattService.getUuid().equals(UUID_SERVICE_MAIN)) {
bluetoothGattService = gattService;
}
for (final BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
i++;
Log.d(TAG, "UUID:" + gattCharacteristic.getUuid().toString());
for (BluetoothGattDescriptor gsc : gattCharacteristic
.getDescriptors()) {
Log.d(TAG, "getDescriptors:" + gsc.getUuid().toString()
+ " per" + gsc.getPermissions());
}
if (gattCharacteristic.getUuid().toString()
.equals(UUID_DATA_READ)) {
// 接受Characteristic被写的通知,收到蓝牙模块的数据后会触发mOnDataAvailable.onCharacteristicWrite()
if (gattCharacteristic != null) {
if (!isnotify) {
character_read = gattCharacteristic;
readCharacteristic(character_read);
character_notify = gattCharacteristic;
setCharacteristicNotification(character_notify,
true);
isnotify = true;
}
}
for (BluetoothGattDescriptor gsc : gattCharacteristic
.getDescriptors()) {
Log.e(TAG, j + "DescriptorUuid:" + i + " "
+ gsc.getUuid().toString());
}
}
if (gattCharacteristic.getUuid().toString()
.equals(UUID_DATA_WRITE)) {
character_write = gattCharacteristic;
}
}
}
}
private BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (ACTION_GATT_CONNECTED.equals(action)) {
} else if (ACTION_GATT_SERVICES_DISCOVERED// 发现GATT服务器
.equals(action)) {
// Show all the supported services and characteristics on the
// user interface.
// 获取设备的所有蓝牙服务
displayGattServices(getSupportedGattServices());
}
}
};
}
<file_sep>/src/com/xw/ble/utils/Hex2ByteUtil.java
package com.xw.ble.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.UnsupportedEncodingException;
public class Hex2ByteUtil {
// public static void main(String[] args) {
// string2Hex();
// Hex2File();
// System.out.println("main test");
//
// }
/**
*
* @Title Hex2Txt
* @Description 将收到的16进制字符串写入到txt文件中
* @author 李官周
* @date 2014-8-15 上午9:46:24
* @param hexStr
* @param fileOutPath
*/
public static void Hex2Txt(String hexStr,String fileOutPath) {
File out = new File(fileOutPath);
try{
if (!out.exists()) {
out.createNewFile();
}
FileWriter fw = new FileWriter(out,true);
fw.write(hexStr);
fw.close();
}catch(Exception e){
e.printStackTrace();
}
}
/**
*
* @Title txt2File
* @Description 将txt文本中的16进制字符串读出来并转化为文件
* @author 李官周
* @date 2014-8-15 上午9:50:02
* @param FileInPath
* @param FileOutPath
*/
public static boolean txt2File(String FileInPath,String FileOutPath) {
byte[] bytes = new byte[512];
File file = new File(FileInPath);
File out = new File(FileOutPath);
try {
if(!file.exists()){
return false;
}
if (!out.exists()) {
out.createNewFile();
}
// FileInputStream in = new FileInputStream(file);
FileReader in = new FileReader(file);
BufferedReader br = new BufferedReader(in);
// FileOutputStream fileout = new FileOutputStream(out);
// FileWriter fw = new FileWriter(out);
FileOutputStream fout = new FileOutputStream(out);
String result;
while ((result = br.readLine()) != null) {
bytes = hexStringToBytes(result);
// fw.write(bytes);
fout.write(bytes);
}
fout.close();
in.close();
return true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
private static void string2Hex() {
byte[] bytes = new byte[512];
File file = new File("C:/Users/li/Desktop/BusInfoVision.patch");
File out = new File(
"C:/Users/li/Desktop/BusInfoVision.patch.txt");
try {
if (!out.exists()) {
out.createNewFile();
}
FileInputStream in = new FileInputStream(file);
// FileOutputStream fileout = new FileOutputStream(out);
FileWriter fw = new FileWriter(out);
int size = 0;
while ((size = in.read(bytes)) != -1) {
String hex = Hex2ByteUtil.bytesToHexString(bytes,0, size);
fw.write(hex);
}
fw.close();
in.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void Hex2File() {
byte[] bytes = new byte[512];
File file = new File("C:/Users/Administrator/Desktop/��201.txt");
File out = new File("C:/Users/Administrator/Desktop/��201_2.zip");
try {
if (!out.exists()) {
out.createNewFile();
}
// FileInputStream in = new FileInputStream(file);
FileReader in = new FileReader(file);
BufferedReader br = new BufferedReader(in);
// FileOutputStream fileout = new FileOutputStream(out);
// FileWriter fw = new FileWriter(out);
FileOutputStream fout = new FileOutputStream(out);
String result;
while ((result = br.readLine()) != null) {
bytes = hexStringToBytes(result);
// fw.write(bytes);
fout.write(bytes);
}
fout.close();
in.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Convert char to byte
*
* @param c
* char
* @return byte
*/
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
public static String stringToHexString(String str) {
return bytesToHexString(str.getBytes());
}
public static String stringToHexString(String str,String charsetName) {
try {
return bytesToHexString(str.getBytes(charsetName));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* @Title bytesToHexString
* @Description 字节数组装16进制字符串
* @author 李官周
* @date 2014-9-1 上午11:07:54
* @param src 字节数组
* @return
*/
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString().toUpperCase();
}
/**
* @Title bytesToHexString
* @Description 字节数组装16进制字符串
* @author 李官周
* @date 2014-9-1 上午11:07:54
* @param src 字节数组
* @return
*/
public static String bytesToHexString(byte[] src,int start,int size) {
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || start < 0|| size <= start ) {
return null;
}
int len=start+size;
for (int i = start; i < len; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString().toUpperCase();
}
/**
* Convert hex string to byte[]
*
* @param hexString
* the hex string
* @return byte[]
*/
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
/**
* @Title hexStringToByte
* @Description 返回一个byte
* @author 李官周
* @date 2015-1-20 上午10:59:16
* @param hexString
* @return
*/
public static byte hexStringToByte(String hexString) {
if (hexString == null || hexString.equals("")) {
return 0;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
if(length>1){
return 0;
}
char[] hexChars = hexString.toCharArray();
byte d = 0;
for (int i = 0; i < length; i++) {
int pos = i * 2;
d = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
/**
* 把中文转成Unicode�?
* @param str
* @return
*/
public static String chinaToUnicode(String str){
String result="";
for (int i = 0; i < str.length(); i++){
int chr1 = (char) str.charAt(i);
if(chr1>=19968&&chr1<=171941){//汉字范围 \u4e00-\u9fa5 (中文)
result+="" + Integer.toHexString(chr1);
}else{
result+=str.charAt(i);
}
}
return result.toUpperCase();
}
/**
* @Title int2Bytes
* @Description ��������ת��Ϊbyte����
* @author �º���
* @date 2015-8-10 ����10:38:57
* @param integer Ҫת������
* @param byteLen ת����byte���鳤�ȣ����㲹0x00
* @return
*/
public static byte[] int2Bytes(long integer,int byteLen){
byte[] bytes = new byte[byteLen];
try{
int b = (byteLen - 1)* 8;
for(int i = 0 ; i < byteLen ; i++){
bytes[i] = (byte) (integer >> b);
b -= 8;
}
}catch(Exception ex){
ex.printStackTrace();
}
return bytes;
}
/**
*
* @Title bytesToInt2
* @Description ��byte����ת��int ������������(��λ�ں�λ��ǰ)��˳��
* @author ������
* @date 2015-9-19 ����3:02:43
* @param src
* @param offset
* @return
*/
public static int bytesToInt2(byte[] ary, int offset) {
int mask=0xff;
int temp=0;
int n=0;
for(int i=0;i<offset;i++){
n<<=8;
temp=ary[i]&mask;
n|=temp;
}
return n;
}
/***
*
* @Title bytesToInt
* @Description ��byte����ת��int ������������(��λ�ں�λ��ǰ)��˳��
* @author ������
* @date 2015-9-25 ����8:56:54
* @param ary
* @param offset
* @return
*/
public static int bytesToInt(byte[] ary, int offset) {
int mask=0xff;
int temp=0;
int n=0;
for(int i=0;i<offset;i++){
n<<=8;
temp=ary[offset-i-1]&mask;
n|=temp;
}
return n;
}
/**
*
* @Title reverse
* @Description ��byte���鷴ת
* @author ������
* @date 2015-9-25 ����9:54:57
* @param myByte
* @return
*/
public static byte[] reverseBytes(byte[] myByte) {
byte[] newByte = new byte[myByte.length];
for (int i = 1; i <= myByte.length; i++) {
newByte[myByte.length - i] = myByte[i - 1];
}
return newByte;
}
/**
* @Title HexStringAddComma
* @Description �ַ���ż���ӷָ��������ţ�
* @author �����
* @date 2016-3-21 ����9:36:23
* @param src
* @return
*/
public static String HexStringAddComma(String src) {
StringBuilder stringBuilder = new StringBuilder("");
for (int i = 0; i < src.length(); i++) {
if (i%2==0) {
stringBuilder.append(",");
}
stringBuilder.append(src.charAt(i));
}
return stringBuilder.toString().toUpperCase();
}
public static byte[] longToByte2(long number) {
long temp = number;
byte[] b = new byte[2];
for (int i = 0; i < b.length; i++) {
b[b.length-1-i] = new Long(temp & 0xff).byteValue();// �����λ���������λ
temp = temp >> 8; // ������8λ
}
return b;
}
public static byte[] longToByte4(long number) {
long temp = number;
byte[] b = new byte[4];
for (int i = 0; i < b.length; i++) {
b[b.length-1-i] = new Long(temp & 0xff).byteValue();// �����λ���������λ
temp = temp >> 8; // ������8λ
}
return b;
}
/**
* @Title decimalToHexString
* @Description 10����ת16�����ַ���
* @author jw
* @date 2015-11-23 ����3:06:56
* @param i
* @return
*/
public static String decimalToHexString(int i) {
String strDecimal="";
if(i>15){
strDecimal=Integer.toHexString(i);
}
else if (i <=15){
strDecimal="0"+Integer.toHexString(i);
}
return strDecimal;
}
}
<file_sep>/src/com/xw/ble/CommunicationInstruction.java
package com.xw.ble;
import com.xw.ble.utils.Hex2ByteUtil;
import android.util.Log;
/**
*
* @ClassName CommunicationInstruction
* @Description 通讯指令实体类
* @author <NAME>
* @date 2017-11-23 下午4:49:34
*/
public class CommunicationInstruction {
private byte Source; //发送源
private byte Destination; //目的地
private byte Command; //命令
private byte Parameter; //参数
private byte[] dataNumber; //数据数量
private byte[] Data; //数据
private byte checkSum; //校验和
public byte getSource(){
return Source;
}
public void setSource(byte bSource){
this.Source=bSource;
}
public byte getDestination(){
return Destination;
}
public void setDestination(byte bDestination){
this.Destination=bDestination;
}
public byte getCommand(){
return Command;
}
public void setCommand(byte bCommand){
this.Command=bCommand;
}
public byte getParameter(){
return Parameter;
}
public void setParameter(byte bParameter){
this.Parameter=bParameter;
}
public byte[] getDataNumber(){
return dataNumber;
}
public void setDataNumber(byte[] bDataNumber){
this.dataNumber=bDataNumber;
}
public byte[] getData(){
return Data;
}
public void setData(byte[] bData){
this.Data=bData;
}
public byte getCheckSum(){
return checkSum;
}
public void setCheckSum(byte bCheckSum){
this.checkSum=bCheckSum;
}
public CommunicationInstruction(){
}
/**
* 实例化通讯实体类
* @param bSource
* @param bDestination
* @param bCommand
* @param bParameterNumber
* @param bParameter
* @param bDataNumber
* @param bData
* @param bCheckSum
*/
public CommunicationInstruction(byte bSource,byte bDestination,byte bCommand,byte bParameter,byte[] bDataNumber,byte[] bData){
this.Source=bSource;
this.Destination=bDestination;
this.Command=bCommand;
this.Parameter=bParameter;
this.dataNumber=bDataNumber;
this.Data=bData;
}
public CommunicationInstruction(String hexStr) {
if(hexStr.length()<9*2){
return ;
}
this.Source = Hex2ByteUtil.hexStringToByte(hexStr.substring(3*2,4*2));
this.Destination = Hex2ByteUtil.hexStringToByte(hexStr.substring(4*2,5*2));
this.Command = Hex2ByteUtil.hexStringToByte(hexStr.substring(5*2,6*2));
this.Parameter = Hex2ByteUtil.hexStringToByte(hexStr.substring(6*2,7*2));
this.dataNumber = Hex2ByteUtil.hexStringToBytes(hexStr.substring(7*2,8*2));
int iDataNumber=0;
try{
iDataNumber=Integer.parseInt(hexStr.substring(7*2,8*2), 16);
}
catch(Exception e){}
if(iDataNumber>=1 && (8+iDataNumber)*2 <= hexStr.length()){
this.Data = Hex2ByteUtil.hexStringToBytes(hexStr.substring(8*2, (8+iDataNumber)*2));
}
}
public CommunicationInstruction(String hexStr,int type) {
if (type == 2) {
if(hexStr.length()<5*2){
return ;
}
this.Source = Hex2ByteUtil.hexStringToByte(hexStr.substring(1*2,2*2));
this.Destination = Hex2ByteUtil.hexStringToByte(hexStr.substring(2*2,3*2));
this.Command = Hex2ByteUtil.hexStringToByte(hexStr.substring(3*2,4*2));
this.Parameter = (byte)0x00;
this.dataNumber = Hex2ByteUtil.hexStringToBytes(hexStr.substring(4*2,5*2));
int iDataNumber=0;
try{
iDataNumber=Integer.parseInt(hexStr.substring(4*2,5*2), 16);
}
catch(Exception e){}
if(iDataNumber>=1 && (5+iDataNumber)*2 <= hexStr.length()){
this.Data = Hex2ByteUtil.hexStringToBytes(hexStr.substring(5*2, (5+iDataNumber)*2));
}
}
}
}
<file_sep>/src/com/xw/ble/instruct/BtInstructionInfo.java
package com.xw.ble.instruct;
public class BtInstructionInfo {
private int MsgOperate;
private BtInstructionType MsgType;
private int MsgTime;
private Object InputData;
public int getMsgOperate(){
return MsgOperate;
}
public void setMsgOperate(int iMsgOperate){
this.MsgOperate=iMsgOperate;
}
public BtInstructionType getMsgType(){
return MsgType;
}
public void setMsgType(BtInstructionType iType){
this.MsgType=iType;
}
public int getMsgTime(){
return MsgTime;
}
public void setMsgTime(int iTime){
this.MsgTime=iTime;
}
public Object getInputData(){
return InputData;
}
public void setInputData(Object oInputData){
this.InputData=oInputData;
}
public BtInstructionInfo(){
}
public BtInstructionInfo(BtInstructionType iType){
this.MsgType=iType;
}
public BtInstructionInfo(BtInstructionType iType,int iOperate){
this.MsgType=iType;
this.MsgOperate=iOperate;
}
public BtInstructionInfo(BtInstructionType iType,Object oInputData){
this.MsgType=iType;
this.InputData=oInputData;
}
public BtInstructionInfo(BtInstructionType iType,int iOperate,int iTime){
this.MsgType=iType;
this.MsgOperate=iOperate;
this.MsgTime=iTime;
}
}
<file_sep>/src/com/xw/ble/InstructInputView.java
package com.xw.ble;
import com.xw.ble.utils.BtSendCommandUtils;
import com.xw.ble.utils.Hex2ByteUtil;
import com.xw.bledemo.R;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class InstructInputView extends LinearLayout{
private Context context;
private EditText send_receive_et;
private EditText instruct_parameter_et;
private EditText data_et;
public InstructInputView(Context context) {
this(context, null);
// TODO Auto-generated constructor stub
this.context = context;
}
public InstructInputView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public InstructInputView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
this.context = context;
initData();
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
View.inflate(getContext(), R.layout.instruct_input_view, this);
send_receive_et = (EditText) findViewById(R.id.send_receive_et);
instruct_parameter_et = (EditText) findViewById(R.id.instruct_parameter_et);
data_et = (EditText) findViewById(R.id.data_et);
}
/**
* 初始化数据
*/
private void initData()
{
}
public boolean sendViewInstruct()
{
String sendReceiveStr = send_receive_et.getText().toString().trim();
String instructParameterStr = instruct_parameter_et.getText().toString().trim();
String dataStr = data_et.getText().toString().trim();
if (TextUtils.isEmpty(sendReceiveStr) || sendReceiveStr.length() < 4) {
Toast.makeText(context, "请输入发送和接收地", Toast.LENGTH_SHORT).show();
}else if (TextUtils.isEmpty(instructParameterStr)|| instructParameterStr.length() < 4) {
Toast.makeText(context, "请输入指令和参数", Toast.LENGTH_SHORT).show();
}else if (TextUtils.isEmpty(dataStr)) {
Toast.makeText(context, "请输入数据", Toast.LENGTH_SHORT).show();
}else{
byte bSource = Hex2ByteUtil.hexStringToBytes(sendReceiveStr.substring(0, 2))[0];
byte bDestination = Hex2ByteUtil.hexStringToBytes(sendReceiveStr.substring(2, 4))[0];
byte bInstruction = Hex2ByteUtil.hexStringToBytes(instructParameterStr.substring(0, 2))[0];
byte bParameter = Hex2ByteUtil.hexStringToBytes(instructParameterStr.substring(2, 4))[0];
byte[] bData = {};
if (!TextUtils.isEmpty(dataStr)) {
bData = Hex2ByteUtil.hexStringToBytes(dataStr);
}
byte[] bDataNumber = BtSendCommandUtils.getDataNumber(bData.length);
CommunicationInstruction versionInstruction = new CommunicationInstruction(
bSource, bDestination, bInstruction, bParameter, bDataNumber,
bData);
BtSendCommandUtils.sendInstruction(versionInstruction);
}
return true;
}
}
<file_sep>/src/com/xw/ble/instruct/SendPasswordListener.java
package com.xw.ble.instruct;
public interface SendPasswordListener {
public void getInstructionInput(String Input);
public void getInstructionOutput(String Output);
public void getInstructionData(String Data);
}
| cc3876c1384200e634569f281d18fe184ad3b188 | [
"Java"
] | 11 | Java | kris-L/BleDemo | 4e9aef69e95e30666166dd41afd3f45f7baf1b28 | 857f16680e7368a13c1706b18515e1d52b6a04d7 |
refs/heads/main | <file_sep>package com.deprosun.mapperlangplugin.psi;
import com.intellij.openapi.util.IconLoader;
import javax.swing.*;
public class MapperIcon {
public static final Icon ICON = IconLoader.findIcon("/icons/mapperIcon.png");
}
<file_sep># MapperLangPlugin
An IntelliJ plugin to read and parse the `.mapper` file format. This plugin provides
* Syntax Highlighting
* Auto Reformatting
* Auto Completion
Highly under construction :sweat_smile:
<file_sep>rootProject.name = 'MapperLangPlugin'
<file_sep>plugins {
id 'org.jetbrains.intellij' version '1.1.6'
id 'java'
}
group 'com.deprosun'
version '0.1'
sourceSets.main.java.srcDirs 'src/main/gen'
repositories {
mavenCentral()
}
dependencies {
implementation "org.antlr:antlr4-intellij-adaptor:0.1"
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0'
implementation group: 'com.github.vbmacher', name: 'java-cup-runtime', version: '11b-20160615'
}
// See https://github.com/JetBrains/gradle-intellij-plugin/
intellij {
version = '2021.2.2'
}
patchPluginXml {
changeNotes = """
Add change notes here.<br>
<em>most HTML tags may be used</em>"""
}
test {
useJUnitPlatform()
}<file_sep>package com.deprosun.mapperlangplugin.psi;
import com.intellij.extapi.psi.PsiFileBase;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.psi.FileViewProvider;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
public class MapperFile extends PsiFileBase {
public MapperFile(@NotNull FileViewProvider viewProvider) {
super(viewProvider, MapperLanguage.INSTANCE);
}
@NotNull
@Override
public FileType getFileType() {
return MapperFileType.INSTANCE;
}
@Override
public String toString() {
return "Simple File";
}
@Override
public Icon getIcon(int flags) {
return super.getIcon(flags);
}
}<file_sep>package com.deprosun.mapperlangplugin;
import com.deprosun.mapperlangplugin.psi.MapperLexerAdapter;
import com.deprosun.mapperlangplugin.psi.SimpleTypes;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
public class MapperSyntaxHighlighter extends SyntaxHighlighterBase {
public static final TextAttributesKey TOPIC =
createTextAttributesKey("TOPIC", DefaultLanguageHighlighterColors.FUNCTION_DECLARATION);
public static final TextAttributesKey DOT =
createTextAttributesKey("DOT", DefaultLanguageHighlighterColors.DOT);
public static final TextAttributesKey LP =
createTextAttributesKey("LP", DefaultLanguageHighlighterColors.PARENTHESES);
public static final TextAttributesKey ID =
createTextAttributesKey("ID", DefaultLanguageHighlighterColors.KEYWORD);
private static final TextAttributesKey[] TOPIC_KEYS = new TextAttributesKey[]{TOPIC};
private static final TextAttributesKey[] DOT_KEYS = new TextAttributesKey[]{DOT};
private static final TextAttributesKey[] LP_KEYS = new TextAttributesKey[]{LP};
private static final TextAttributesKey[] ID_KEYS = new TextAttributesKey[]{ID};
private static final TextAttributesKey[] EMPTY_KEYS = new TextAttributesKey[0];
@Override
public @NotNull Lexer getHighlightingLexer() {
return new MapperLexerAdapter();
}
@Override
public TextAttributesKey @NotNull [] getTokenHighlights(IElementType tokenType) {
if (tokenType.equals(SimpleTypes.TOPIC)
|| tokenType.equals(SimpleTypes.FROM)
|| tokenType.equals(SimpleTypes.FILTER)
|| tokenType.equals(SimpleTypes.BROADCAST)
|| tokenType.equals(SimpleTypes.AS)) {
return TOPIC_KEYS;
} else if (tokenType.equals(SimpleTypes.DOT)) {
return DOT_KEYS;
} else if (tokenType.equals(SimpleTypes.LP) || tokenType.equals(SimpleTypes.RP)) {
return LP_KEYS;
} else if (tokenType.equals(SimpleTypes.ID)) {
return ID_KEYS;
} else {
return EMPTY_KEYS;
}
}
}
<file_sep>package com.deprosun.mapperlangplugin.psi;
import com.intellij.psi.tree.IElementType;
public class MapperTokenType extends IElementType {
public MapperTokenType(String debugName) {
super(debugName, MapperLanguage.INSTANCE);
}
@Override
public String toString() {
return "MapperTokenType." + super.toString();
}
}
<file_sep>package com.deprosun.mapperlangplugin.psi;
import com.intellij.psi.tree.IElementType;
public class MapperElementType extends IElementType {
public MapperElementType(String debugName) {
super(debugName, MapperLanguage.INSTANCE);
}
}
| 786f759f9d7f35039e3448372bc2b877c1cfeb73 | [
"Markdown",
"Java",
"Gradle"
] | 8 | Java | deprosun/MapperLangPlugin | 80eb1f5c92bb5e4bab7fc444eb04c14aa95a2ca6 | 6b8d7905fa34aac3c4a3e17021d2244cfd9aa1ba |
refs/heads/master | <repo_name>hzxuzhonghu/kubernetes<file_sep>/test/integration/dryrun/dryrun_test.go
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package dryrun
import (
"encoding/json"
"io/ioutil"
"net"
"net/http"
"os"
"strings"
"testing"
"time"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apiserver/pkg/features"
genericapiserveroptions "k8s.io/apiserver/pkg/server/options"
utilfeature "k8s.io/apiserver/pkg/util/feature"
utilfeaturetesting "k8s.io/apiserver/pkg/util/feature/testing"
cacheddiscovery "k8s.io/client-go/discovery/cached"
"k8s.io/client-go/dynamic"
clientset "k8s.io/client-go/kubernetes"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/restmapper"
"k8s.io/kubernetes/cmd/kube-apiserver/app"
"k8s.io/kubernetes/cmd/kube-apiserver/app/options"
"k8s.io/kubernetes/test/integration/framework"
// install all APIs
_ "k8s.io/kubernetes/pkg/master" // TODO what else is needed
)
// dryrun data for all persisted objects.
var dryrunData = map[schema.GroupVersionResource]struct {
stub string // Valid JSON stub to use during create
}{
// k8s.io/kubernetes/pkg/api/v1
gvr("", "v1", "configmaps"): {
stub: `{"data": {"foo": "bar"}, "metadata": {"name": "cm1"}}`,
},
gvr("", "v1", "services"): {
stub: `{"metadata": {"name": "service1"}, "spec": {"externalName": "service1name", "ports": [{"port": 10000, "targetPort": 11000}], "selector": {"test": "data"}}}`,
},
gvr("", "v1", "podtemplates"): {
stub: `{"metadata": {"name": "pt1name"}, "template": {"metadata": {"labels": {"pt": "01"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container9"}]}}}`,
},
gvr("", "v1", "pods"): {
stub: `{"metadata": {"name": "pod1"}, "spec": {"containers": [{"image": "fedora:latest", "name": "container7", "resources": {"limits": {"cpu": "1M"}, "requests": {"cpu": "1M"}}}]}}`,
},
gvr("", "v1", "endpoints"): {
stub: `{"metadata": {"name": "ep1name"}, "subsets": [{"addresses": [{"hostname": "bar-001", "ip": "192.168.3.1"}], "ports": [{"port": 8000}]}]}`,
},
gvr("", "v1", "resourcequotas"): {
stub: `{"metadata": {"name": "rq1name"}, "spec": {"hard": {"cpu": "5M"}}}`,
},
gvr("", "v1", "limitranges"): {
stub: `{"metadata": {"name": "lr1name"}, "spec": {"limits": [{"type": "Pod"}]}}`,
},
gvr("", "v1", "namespaces"): {
stub: `{"metadata": {"name": "namespace2"}, "spec": {"finalizers": ["kubernetes"]}}`,
},
gvr("", "v1", "nodes"): {
stub: `{"metadata": {"name": "node1"}, "spec": {"unschedulable": true}}`,
},
gvr("", "v1", "persistentvolumes"): {
stub: `{"metadata": {"name": "pv1name"}, "spec": {"accessModes": ["ReadWriteOnce"], "capacity": {"storage": "3M"}, "hostPath": {"path": "/tmp/test/"}}}`,
},
gvr("", "v1", "events"): {
stub: `{"involvedObject": {"namespace": "dryrunnamespace"}, "message": "some data here", "metadata": {"name": "event1"}}`,
},
gvr("", "v1", "persistentvolumeclaims"): {
stub: `{"metadata": {"name": "pvc1"}, "spec": {"accessModes": ["ReadWriteOnce"], "resources": {"limits": {"storage": "1M"}, "requests": {"storage": "2M"}}, "selector": {"matchLabels": {"pvc": "stuff"}}}}`,
},
gvr("", "v1", "serviceaccounts"): {
stub: `{"metadata": {"name": "sa1name"}, "secrets": [{"name": "secret00"}]}`,
},
gvr("", "v1", "secrets"): {
stub: `{"data": {"key": "<KEY>"}, "metadata": {"name": "secret1"}}`,
},
gvr("", "v1", "replicationcontrollers"): {
stub: `{"metadata": {"name": "rc1"}, "spec": {"selector": {"new": "stuff"}, "template": {"metadata": {"labels": {"new": "stuff"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container8"}]}}}}`,
},
// --
// k8s.io/kubernetes/pkg/apis/apps/v1beta1
gvr("apps", "v1beta1", "statefulsets"): {
stub: `{"metadata": {"name": "ss1"}, "spec": {"selector": {"matchLabels": {"a": "b"}}, "template": {"metadata": {"labels": {"a": "b"}}}}}`,
},
gvr("apps", "v1beta1", "deployments"): {
stub: `{"metadata": {"name": "deployment2"}, "spec": {"selector": {"matchLabels": {"f": "z"}}, "template": {"metadata": {"labels": {"f": "z"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container6"}]}}}}`,
},
gvr("apps", "v1beta1", "controllerrevisions"): {
stub: `{"metadata":{"name":"crs1"},"data":{"name":"abc","namespace":"default","creationTimestamp":null,"Spec":{"Replicas":0,"Selector":{"matchLabels":{"foo":"bar"}},"Template":{"creationTimestamp":null,"labels":{"foo":"bar"},"Spec":{"Volumes":null,"InitContainers":null,"Containers":null,"RestartPolicy":"Always","TerminationGracePeriodSeconds":null,"ActiveDeadlineSeconds":null,"DNSPolicy":"ClusterFirst","NodeSelector":null,"ServiceAccountName":"","AutomountServiceAccountToken":null,"NodeName":"","SecurityContext":null,"ImagePullSecrets":null,"Hostname":"","Subdomain":"","Affinity":null,"SchedulerName":"","Tolerations":null,"HostAliases":null}},"VolumeClaimTemplates":null,"ServiceName":""},"Status":{"ObservedGeneration":null,"Replicas":0}},"revision":0}`,
},
// --
// k8s.io/kubernetes/pkg/apis/apps/v1beta2
gvr("apps", "v1beta2", "statefulsets"): {
stub: `{"metadata": {"name": "ss2"}, "spec": {"selector": {"matchLabels": {"a": "b"}}, "template": {"metadata": {"labels": {"a": "b"}}}}}`,
},
gvr("apps", "v1beta2", "deployments"): {
stub: `{"metadata": {"name": "deployment3"}, "spec": {"selector": {"matchLabels": {"f": "z"}}, "template": {"metadata": {"labels": {"f": "z"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container6"}]}}}}`,
},
gvr("apps", "v1beta2", "daemonsets"): {
stub: `{"metadata": {"name": "ds5"}, "spec": {"selector": {"matchLabels": {"a": "b"}}, "template": {"metadata": {"labels": {"a": "b"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container6"}]}}}}`,
},
gvr("apps", "v1beta2", "replicasets"): {
stub: `{"metadata": {"name": "rs2"}, "spec": {"selector": {"matchLabels": {"g": "h"}}, "template": {"metadata": {"labels": {"g": "h"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container4"}]}}}}`,
},
gvr("apps", "v1beta2", "controllerrevisions"): {
stub: `{"metadata":{"name":"crs2"},"data":{"name":"abc","namespace":"default","creationTimestamp":null,"Spec":{"Replicas":0,"Selector":{"matchLabels":{"foo":"bar"}},"Template":{"creationTimestamp":null,"labels":{"foo":"bar"},"Spec":{"Volumes":null,"InitContainers":null,"Containers":null,"RestartPolicy":"Always","TerminationGracePeriodSeconds":null,"ActiveDeadlineSeconds":null,"DNSPolicy":"ClusterFirst","NodeSelector":null,"ServiceAccountName":"","AutomountServiceAccountToken":null,"NodeName":"","SecurityContext":null,"ImagePullSecrets":null,"Hostname":"","Subdomain":"","Affinity":null,"SchedulerName":"","Tolerations":null,"HostAliases":null}},"VolumeClaimTemplates":null,"ServiceName":""},"Status":{"ObservedGeneration":null,"Replicas":0}},"revision":0}`,
},
// --
// k8s.io/kubernetes/pkg/apis/apps/v1
gvr("apps", "v1", "daemonsets"): {
stub: `{"metadata": {"name": "ds6"}, "spec": {"selector": {"matchLabels": {"a": "b"}}, "template": {"metadata": {"labels": {"a": "b"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container6"}]}}}}`,
},
gvr("apps", "v1", "deployments"): {
stub: `{"metadata": {"name": "deployment4"}, "spec": {"selector": {"matchLabels": {"f": "z"}}, "template": {"metadata": {"labels": {"f": "z"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container6"}]}}}}`,
},
gvr("apps", "v1", "statefulsets"): {
stub: `{"metadata": {"name": "ss3"}, "spec": {"selector": {"matchLabels": {"a": "b"}}, "template": {"metadata": {"labels": {"a": "b"}}}}}`,
},
gvr("apps", "v1", "replicasets"): {
stub: `{"metadata": {"name": "rs3"}, "spec": {"selector": {"matchLabels": {"g": "h"}}, "template": {"metadata": {"labels": {"g": "h"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container4"}]}}}}`,
},
gvr("apps", "v1", "controllerrevisions"): {
stub: `{"metadata":{"name":"crs3"},"data":{"name":"abc","namespace":"default","creationTimestamp":null,"Spec":{"Replicas":0,"Selector":{"matchLabels":{"foo":"bar"}},"Template":{"creationTimestamp":null,"labels":{"foo":"bar"},"Spec":{"Volumes":null,"InitContainers":null,"Containers":null,"RestartPolicy":"Always","TerminationGracePeriodSeconds":null,"ActiveDeadlineSeconds":null,"DNSPolicy":"ClusterFirst","NodeSelector":null,"ServiceAccountName":"","AutomountServiceAccountToken":null,"NodeName":"","SecurityContext":null,"ImagePullSecrets":null,"Hostname":"","Subdomain":"","Affinity":null,"SchedulerName":"","Tolerations":null,"HostAliases":null}},"VolumeClaimTemplates":null,"ServiceName":""},"Status":{"ObservedGeneration":null,"Replicas":0}},"revision":0}`,
},
// --
// k8s.io/kubernetes/pkg/apis/autoscaling/v1
gvr("autoscaling", "v1", "horizontalpodautoscalers"): {
stub: `{"metadata": {"name": "hpa2"}, "spec": {"maxReplicas": 3, "scaleTargetRef": {"kind": "something", "name": "cross"}}}`,
},
// --
// k8s.io/kubernetes/pkg/apis/autoscaling/v2beta1
gvr("autoscaling", "v2beta1", "horizontalpodautoscalers"): {
stub: `{"metadata": {"name": "hpa1"}, "spec": {"maxReplicas": 3, "scaleTargetRef": {"kind": "something", "name": "cross"}}}`,
},
// --
// k8s.io/kubernetes/pkg/apis/autoscaling/v2beta2
gvr("autoscaling", "v2beta2", "horizontalpodautoscalers"): {
stub: `{"metadata": {"name": "hpa3"}, "spec": {"maxReplicas": 3, "scaleTargetRef": {"kind": "something", "name": "cross"}}}`,
},
// --
// k8s.io/kubernetes/pkg/apis/batch/v1
gvr("batch", "v1", "jobs"): {
stub: `{"metadata": {"name": "job1"}, "spec": {"manualSelector": true, "selector": {"matchLabels": {"controller-uid": "uid1"}}, "template": {"metadata": {"labels": {"controller-uid": "uid1"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container1"}], "dnsPolicy": "ClusterFirst", "restartPolicy": "Never"}}}}`,
},
// --
// k8s.io/kubernetes/pkg/apis/batch/v1beta1
gvr("batch", "v1beta1", "cronjobs"): {
stub: `{"metadata": {"name": "cjv1beta1"}, "spec": {"jobTemplate": {"spec": {"template": {"metadata": {"labels": {"controller-uid": "uid0"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container0"}], "dnsPolicy": "ClusterFirst", "restartPolicy": "Never"}}}}, "schedule": "* * * * *"}}`,
},
// --
// k8s.io/kubernetes/pkg/apis/batch/v2alpha1
gvr("batch", "v2alpha1", "cronjobs"): {
stub: `{"metadata": {"name": "cjv2alpha1"}, "spec": {"jobTemplate": {"spec": {"template": {"metadata": {"labels": {"controller-uid": "uid0"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container0"}], "dnsPolicy": "ClusterFirst", "restartPolicy": "Never"}}}}, "schedule": "* * * * *"}}`,
},
// --
// k8s.io/kubernetes/pkg/apis/certificates/v1beta1
gvr("certificates.k8s.io", "v1beta1", "certificatesigningrequests"): {
stub: `{"metadata": {"name": "csr1"}, "spec": {"request": "<KEY>}}`,
},
// --
// k8s.io/kubernetes/pkg/apis/coordination/v1beta1
gvr("coordination.k8s.io", "v1beta1", "leases"): {
stub: `{"metadata": {"name": "lease1"}, "spec": {"holderIdentity": "holder", "leaseDurationSeconds": 5}}`,
},
// --
// k8s.io/kubernetes/pkg/apis/events/v1beta1
gvr("events.k8s.io", "v1beta1", "events"): {
stub: `{"metadata": {"name": "event2"}, "regarding": {"namespace": "dryrunnamespace"}, "note": "some data here", "eventTime": "2017-08-09T15:04:05.000000Z", "reportingInstance": "node-xyz", "reportingController": "k8s.io/my-controller", "action": "DidNothing", "reason": "Laziness"}`,
},
// --
// k8s.io/kubernetes/pkg/apis/extensions/v1beta1
gvr("extensions", "v1beta1", "daemonsets"): {
stub: `{"metadata": {"name": "ds1"}, "spec": {"selector": {"matchLabels": {"u": "t"}}, "template": {"metadata": {"labels": {"u": "t"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container5"}]}}}}`,
},
gvr("extensions", "v1beta1", "podsecuritypolicies"): {
stub: `{"metadata": {"name": "psp1"}, "spec": {"fsGroup": {"rule": "RunAsAny"}, "privileged": true, "runAsUser": {"rule": "RunAsAny"}, "seLinux": {"rule": "MustRunAs"}, "supplementalGroups": {"rule": "RunAsAny"}}}`,
},
gvr("extensions", "v1beta1", "ingresses"): {
stub: `{"metadata": {"name": "ingress1"}, "spec": {"backend": {"serviceName": "service", "servicePort": 5000}}}`,
},
gvr("extensions", "v1beta1", "networkpolicies"): {
stub: `{"metadata": {"name": "np1"}, "spec": {"podSelector": {"matchLabels": {"e": "f"}}}}`,
},
gvr("extensions", "v1beta1", "deployments"): {
stub: `{"metadata": {"name": "deployment1"}, "spec": {"selector": {"matchLabels": {"f": "z"}}, "template": {"metadata": {"labels": {"f": "z"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container6"}]}}}}`,
},
gvr("extensions", "v1beta1", "replicasets"): {
stub: `{"metadata": {"name": "rs1"}, "spec": {"selector": {"matchLabels": {"g": "h"}}, "template": {"metadata": {"labels": {"g": "h"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container4"}]}}}}`,
},
// --
// k8s.io/kubernetes/pkg/apis/networking/v1
gvr("networking.k8s.io", "v1", "networkpolicies"): {
stub: `{"metadata": {"name": "np2"}, "spec": {"podSelector": {"matchLabels": {"e": "f"}}}}`,
},
// --
// k8s.io/kubernetes/pkg/apis/policy/v1beta1
gvr("policy", "v1beta1", "poddisruptionbudgets"): {
stub: `{"metadata": {"name": "pdb1"}, "spec": {"selector": {"matchLabels": {"anokkey": "anokvalue"}}}}`,
},
gvr("policy", "v1beta1", "podsecuritypolicies"): {
stub: `{"metadata": {"name": "psp2"}, "spec": {"fsGroup": {"rule": "RunAsAny"}, "privileged": true, "runAsUser": {"rule": "RunAsAny"}, "seLinux": {"rule": "MustRunAs"}, "supplementalGroups": {"rule": "RunAsAny"}}}`,
},
// --
// k8s.io/kubernetes/pkg/apis/storage/v1alpha1
gvr("storage.k8s.io", "v1alpha1", "volumeattachments"): {
stub: `{"metadata": {"name": "va1"}, "spec": {"attacher": "gce", "nodeName": "localhost", "source": {"persistentVolumeName": "pv1"}}}`,
},
// --
// k8s.io/kubernetes/pkg/apis/storage/v1beta1
gvr("storage.k8s.io", "v1beta1", "volumeattachments"): {
stub: `{"metadata": {"name": "va2"}, "spec": {"attacher": "gce", "nodeName": "localhost", "source": {"persistentVolumeName": "pv2"}}}`,
},
// --
// k8s.io/kubernetes/pkg/apis/storage/v1beta1
gvr("storage.k8s.io", "v1beta1", "storageclasses"): {
stub: `{"metadata": {"name": "sc1"}, "provisioner": "aws"}`,
},
// --
// k8s.io/kubernetes/pkg/apis/storage/v1
gvr("storage.k8s.io", "v1", "storageclasses"): {
stub: `{"metadata": {"name": "sc2"}, "provisioner": "aws"}`,
},
// --
// k8s.io/kubernetes/pkg/apis/settings/v1alpha1
gvr("settings.k8s.io", "v1alpha1", "podpresets"): {
stub: `{"metadata": {"name": "podpre1"}, "spec": {"env": [{"name": "FOO"}]}}`,
},
// --
// k8s.io/kubernetes/pkg/apis/rbac/v1alpha1
gvr("rbac.authorization.k8s.io", "v1alpha1", "roles"): {
stub: `{"metadata": {"name": "role1"}, "rules": [{"apiGroups": ["v1"], "resources": ["events"], "verbs": ["watch"]}]}`,
},
gvr("rbac.authorization.k8s.io", "v1alpha1", "clusterroles"): {
stub: `{"metadata": {"name": "drcrole1"}, "rules": [{"nonResourceURLs": ["/version"], "verbs": ["get"]}]}`,
},
gvr("rbac.authorization.k8s.io", "v1alpha1", "rolebindings"): {
stub: `{"metadata": {"name": "drroleb1"}, "roleRef": {"apiGroup": "rbac.authorization.k8s.io", "kind": "ClusterRole", "name": "somecr"}, "subjects": [{"apiVersion": "rbac.authorization.k8s.io/v1alpha1", "kind": "Group", "name": "system:authenticated"}]}`,
},
gvr("rbac.authorization.k8s.io", "v1alpha1", "clusterrolebindings"): {
stub: `{"metadata": {"name": "drcroleb1"}, "roleRef": {"apiGroup": "rbac.authorization.k8s.io", "kind": "ClusterRole", "name": "somecr"}, "subjects": [{"apiVersion": "rbac.authorization.k8s.io/v1alpha1", "kind": "Group", "name": "system:authenticated"}]}`,
},
// --
// k8s.io/kubernetes/pkg/apis/rbac/v1beta1
gvr("rbac.authorization.k8s.io", "v1beta1", "roles"): {
stub: `{"metadata": {"name": "drrole2"}, "rules": [{"apiGroups": ["v1"], "resources": ["events"], "verbs": ["watch"]}]}`,
},
gvr("rbac.authorization.k8s.io", "v1beta1", "clusterroles"): {
stub: `{"metadata": {"name": "drcrole2"}, "rules": [{"nonResourceURLs": ["/version"], "verbs": ["get"]}]}`,
},
gvr("rbac.authorization.k8s.io", "v1beta1", "rolebindings"): {
stub: `{"metadata": {"name": "drroleb2"}, "roleRef": {"apiGroup": "rbac.authorization.k8s.io", "kind": "ClusterRole", "name": "somecr"}, "subjects": [{"apiVersion": "rbac.authorization.k8s.io/v1alpha1", "kind": "Group", "name": "system:authenticated"}]}`,
},
gvr("rbac.authorization.k8s.io", "v1beta1", "clusterrolebindings"): {
stub: `{"metadata": {"name": "drcroleb2"}, "roleRef": {"apiGroup": "rbac.authorization.k8s.io", "kind": "ClusterRole", "name": "somecr"}, "subjects": [{"apiVersion": "rbac.authorization.k8s.io/v1alpha1", "kind": "Group", "name": "system:authenticated"}]}`,
},
// --
// k8s.io/kubernetes/pkg/apis/rbac/v1
gvr("rbac.authorization.k8s.io", "v1", "roles"): {
stub: `{"metadata": {"name": "drrole3"}, "rules": [{"apiGroups": ["v1"], "resources": ["events"], "verbs": ["watch"]}]}`,
},
gvr("rbac.authorization.k8s.io", "v1", "clusterroles"): {
stub: `{"metadata": {"name": "drcrole3"}, "rules": [{"nonResourceURLs": ["/version"], "verbs": ["get"]}]}`,
},
gvr("rbac.authorization.k8s.io", "v1", "rolebindings"): {
stub: `{"metadata": {"name": "drroleb3"}, "roleRef": {"apiGroup": "rbac.authorization.k8s.io", "kind": "ClusterRole", "name": "somecr"}, "subjects": [{"apiVersion": "rbac.authorization.k8s.io/v1alpha1", "kind": "Group", "name": "system:authenticated"}]}`,
},
gvr("rbac.authorization.k8s.io", "v1", "clusterrolebindings"): {
stub: `{"metadata": {"name": "drcroleb3"}, "roleRef": {"apiGroup": "rbac.authorization.k8s.io", "kind": "ClusterRole", "name": "somecr"}, "subjects": [{"apiVersion": "rbac.authorization.k8s.io/v1alpha1", "kind": "Group", "name": "system:authenticated"}]}`,
},
// --
// k8s.io/kubernetes/pkg/apis/admissionregistration/v1alpha1
gvr("admissionregistration.k8s.io", "v1alpha1", "initializerconfigurations"): {
stub: `{"metadata":{"name":"ic1"},"initializers":[{"name":"initializer.k8s.io","rules":[{"apiGroups":["group"],"apiVersions":["version"],"resources":["resource"]}],"failurePolicy":"Ignore"}]}`,
},
// k8s.io/kubernetes/pkg/apis/admissionregistration/v1beta1
gvr("admissionregistration.k8s.io", "v1beta1", "validatingwebhookconfigurations"): {
stub: `{"metadata":{"name":"hook1","creationTimestamp":null},"webhooks":[{"name":"externaladmissionhook.k8s.io","clientConfig":{"service":{"namespace":"ns","name":"n"},"caBundle":null},"rules":[{"operations":["CREATE"],"apiGroups":["group"],"apiVersions":["version"],"resources":["resource"]}],"failurePolicy":"Ignore"}]}`,
},
gvr("admissionregistration.k8s.io", "v1beta1", "mutatingwebhookconfigurations"): {
stub: `{"metadata":{"name":"hook1","creationTimestamp":null},"webhooks":[{"name":"externaladmissionhook.k8s.io","clientConfig":{"service":{"namespace":"ns","name":"n"},"caBundle":null},"rules":[{"operations":["CREATE"],"apiGroups":["group"],"apiVersions":["version"],"resources":["resource"]}],"failurePolicy":"Ignore"}]}`,
},
// --
// k8s.io/kubernetes/pkg/apis/scheduling/v1alpha1
gvr("scheduling.k8s.io", "v1alpha1", "priorityclasses"): {
stub: `{"metadata":{"name":"pc1"},"Value":1000}`,
},
// --
// k8s.io/kubernetes/pkg/apis/scheduling/v1beta1
gvr("scheduling.k8s.io", "v1beta1", "priorityclasses"): {
stub: `{"metadata":{"name":"pc2"},"Value":1000}`,
},
// --
// k8s.io/kube-aggregator/pkg/apis/apiregistration/v1beta1
// depends on aggregator using the same ungrouped RESTOptionsGetter as the kube apiserver, not SimpleRestOptionsFactory in aggregator.go
gvr("apiregistration.k8s.io", "v1beta1", "apiservices"): {
stub: `{"metadata": {"name": "dras1.foo.com"}, "spec": {"group": "foo.com", "version": "dras1", "groupPriorityMinimum":100, "versionPriority":10}}`,
},
// --
// k8s.io/kube-aggregator/pkg/apis/apiregistration/v1
// depends on aggregator using the same ungrouped RESTOptionsGetter as the kube apiserver, not SimpleRestOptionsFactory in aggregator.go
gvr("apiregistration.k8s.io", "v1", "apiservices"): {
stub: `{"metadata": {"name": "dras2.foo.com"}, "spec": {"group": "foo.com", "version": "dras2", "groupPriorityMinimum":100, "versionPriority":10}}`,
},
// --
// k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1
gvr("apiextensions.k8s.io", "v1beta1", "customresourcedefinitions"): {
stub: `{"metadata": {"name": "openshiftwebconsoleconfigs.webconsole.operator.openshift.io"},"spec": {"scope": "Cluster","group": "webconsole.operator.openshift.io","version": "v1alpha1","names": {"kind": "OpenShiftWebConsoleConfig","plural": "openshiftwebconsoleconfigs","singular": "openshiftwebconsoleconfig"}}}`,
},
// --
}
// Only add kinds to this list when this a virtual resource with get and create verbs that doesn't actually
// store into it's kind. We've used this downstream for mappings before.
var kindWhiteList = sets.NewString()
// namespace used for all tests, do not change this
const testNamespace = "dryrunnamespace"
func DryRunCreateTest(t *testing.T, rsc dynamic.ResourceInterface, obj *unstructured.Unstructured, gvResource schema.GroupVersionResource) {
createdObj, err := rsc.Create(obj, metav1.CreateOptions{DryRun: []string{metav1.DryRunAll}})
if err != nil {
t.Fatalf("failed to dry-run create stub for %s: %#v", gvResource, err)
}
if obj.GroupVersionKind() != createdObj.GroupVersionKind() {
t.Fatalf("created object doesn't have the same gvk as original object: got %v, expected %v",
createdObj.GroupVersionKind(),
obj.GroupVersionKind())
}
if _, err := rsc.Get(obj.GetName(), metav1.GetOptions{}); !errors.IsNotFound(err) {
t.Fatalf("object shouldn't exist: %v", err)
}
}
func DryRunPatchTest(t *testing.T, rsc dynamic.ResourceInterface, name string) {
patch := []byte(`{"metadata":{"annotations":{"patch": "true"}}}`)
obj, err := rsc.Patch(name, types.MergePatchType, patch, metav1.UpdateOptions{DryRun: []string{metav1.DryRunAll}})
if err != nil {
t.Fatalf("failed to dry-run patch object: %v", err)
}
if v := obj.GetAnnotations()["patch"]; v != "true" {
t.Fatalf("dry-run patched annotations should be returned, got: %v", obj.GetAnnotations())
}
obj, err = rsc.Get(obj.GetName(), metav1.GetOptions{})
if err != nil {
t.Fatalf("failed to get object: %v", err)
}
if v := obj.GetAnnotations()["patch"]; v == "true" {
t.Fatalf("dry-run patched annotations should not be persisted, got: %v", obj.GetAnnotations())
}
}
func getReplicasOrFail(t *testing.T, obj *unstructured.Unstructured) int64 {
t.Helper()
replicas, found, err := unstructured.NestedInt64(obj.UnstructuredContent(), "spec", "replicas")
if err != nil {
t.Fatalf("failed to get int64 for replicas: %v", err)
}
if !found {
t.Fatal("object doesn't have spec.replicas")
}
return replicas
}
func setReplicasOrFail(t *testing.T, obj *unstructured.Unstructured, replicas int64) {
m, found, err := unstructured.NestedMap(obj.UnstructuredContent(), "spec")
if err != nil {
t.Fatalf("failed to get spec: %v", err)
}
if !found {
t.Fatal("object doesn't have spec")
}
m["replicas"] = replicas
unstructured.SetNestedMap(obj.UnstructuredContent(), m, "spec")
}
func DryRunScalePatchTest(t *testing.T, rsc dynamic.ResourceInterface, name string) {
obj, err := rsc.Get(name, metav1.GetOptions{}, "scale")
if errors.IsNotFound(err) {
return
}
if err != nil {
t.Fatalf("failed to get object: %v", err)
}
replicas := getReplicasOrFail(t, obj)
patch := []byte(`{"spec":{"replicas":10}}`)
patchedObj, err := rsc.Patch(name, types.MergePatchType, patch, metav1.UpdateOptions{DryRun: []string{metav1.DryRunAll}}, "scale")
if err != nil {
t.Fatalf("failed to dry-run patch object: %v", err)
}
if newReplicas := getReplicasOrFail(t, patchedObj); newReplicas != 10 {
t.Fatalf("dry-run patch to replicas didn't return new value: %v", newReplicas)
}
persistedObj, err := rsc.Get(name, metav1.GetOptions{}, "scale")
if err != nil {
t.Fatalf("failed to get scale sub-resource")
}
if newReplicas := getReplicasOrFail(t, persistedObj); newReplicas != replicas {
t.Fatalf("number of replicas changed, expected %v, got %v", replicas, newReplicas)
}
}
func DryRunScaleUpdateTest(t *testing.T, rsc dynamic.ResourceInterface, name string) {
obj, err := rsc.Get(name, metav1.GetOptions{}, "scale")
if errors.IsNotFound(err) {
return
}
if err != nil {
t.Fatalf("failed to get object: %v", err)
}
replicas := getReplicasOrFail(t, obj)
unstructured.SetNestedField(obj.Object, int64(10), "spec", "replicas")
updatedObj, err := rsc.Update(obj, metav1.UpdateOptions{DryRun: []string{metav1.DryRunAll}}, "scale")
if err != nil {
t.Fatalf("failed to dry-run update scale sub-resource: %v", err)
}
if newReplicas := getReplicasOrFail(t, updatedObj); newReplicas != 10 {
t.Fatalf("dry-run update to replicas didn't return new value: %v", newReplicas)
}
persistedObj, err := rsc.Get(name, metav1.GetOptions{}, "scale")
if err != nil {
t.Fatalf("failed to get scale sub-resource")
}
if newReplicas := getReplicasOrFail(t, persistedObj); newReplicas != replicas {
t.Fatalf("number of replicas changed, expected %v, got %v", replicas, newReplicas)
}
}
func DryRunUpdateTest(t *testing.T, rsc dynamic.ResourceInterface, name string) {
var err error
var obj *unstructured.Unstructured
for i := 0; i < 3; i++ {
obj, err = rsc.Get(name, metav1.GetOptions{})
if err != nil {
t.Fatalf("failed to retrieve object: %v", err)
}
obj.SetAnnotations(map[string]string{"update": "true"})
obj, err = rsc.Update(obj, metav1.UpdateOptions{DryRun: []string{metav1.DryRunAll}})
if err == nil || !errors.IsConflict(err) {
break
}
}
if err != nil {
t.Fatalf("failed to dry-run update resource: %v", err)
}
if v := obj.GetAnnotations()["update"]; v != "true" {
t.Fatalf("dry-run updated annotations should be returned, got: %v", obj.GetAnnotations())
}
obj, err = rsc.Get(obj.GetName(), metav1.GetOptions{})
if err != nil {
t.Fatalf("failed to get object: %v", err)
}
if v := obj.GetAnnotations()["update"]; v == "true" {
t.Fatalf("dry-run updated annotations should not be persisted, got: %v", obj.GetAnnotations())
}
}
func DryRunDeleteCollectionTest(t *testing.T, rsc dynamic.ResourceInterface, name string) {
err := rsc.DeleteCollection(&metav1.DeleteOptions{DryRun: []string{metav1.DryRunAll}}, metav1.ListOptions{})
if err != nil {
t.Fatalf("dry-run delete collection failed: %v", err)
}
obj, err := rsc.Get(name, metav1.GetOptions{})
if err != nil {
t.Fatalf("failed to get object: %v", err)
}
ts := obj.GetDeletionTimestamp()
if ts != nil {
t.Fatalf("object has a deletion timestamp after dry-run delete collection")
}
}
func DryRunDeleteTest(t *testing.T, rsc dynamic.ResourceInterface, name string) {
err := rsc.Delete(name, &metav1.DeleteOptions{DryRun: []string{metav1.DryRunAll}})
if err != nil {
t.Fatalf("dry-run delete failed: %v", err)
}
obj, err := rsc.Get(name, metav1.GetOptions{})
if err != nil {
t.Fatalf("failed to get object: %v", err)
}
ts := obj.GetDeletionTimestamp()
if ts != nil {
t.Fatalf("object has a deletion timestamp after dry-run delete")
}
}
// TestDryRun tests dry-run on all types.
func TestDryRun(t *testing.T) {
certDir, _ := ioutil.TempDir("", "test-integration-dryrun")
defer os.RemoveAll(certDir)
defer utilfeaturetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.DryRun, true)()
clientConfig := startRealMasterOrDie(t, certDir)
dClient := dynamic.NewForConfigOrDie(clientConfig)
kubeClient := clientset.NewForConfigOrDie(clientConfig)
if _, err := kubeClient.CoreV1().Namespaces().Create(&v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: testNamespace}}); err != nil {
t.Fatal(err)
}
discoveryClient := cacheddiscovery.NewMemCacheClient(kubeClient.Discovery())
restMapper := restmapper.NewDeferredDiscoveryRESTMapper(discoveryClient)
restMapper.Reset()
serverResources, err := kubeClient.Discovery().ServerResources()
if err != nil {
t.Fatal(err)
}
resourcesToTest := getResourcesToTest(serverResources, false, t)
for _, resourceToTest := range resourcesToTest {
t.Run(resourceToTest.gvr.String(), func(t *testing.T) {
gvk := resourceToTest.gvk
gvResource := resourceToTest.gvr
kind := gvk.Kind
mapping := &meta.RESTMapping{
Resource: resourceToTest.gvr,
GroupVersionKind: resourceToTest.gvk,
Scope: meta.RESTScopeRoot,
}
if resourceToTest.namespaced {
mapping.Scope = meta.RESTScopeNamespace
}
if kindWhiteList.Has(kind) {
t.Skip("whitelisted")
}
testData, hasTest := dryrunData[gvResource]
if !hasTest {
t.Fatalf("no test data for %s. Please add a test for your new type to dryrunData.", gvResource)
}
// we don't require GVK on the data we provide, so we fill it in here. We could, but that seems extraneous.
typeMetaAdder := map[string]interface{}{}
err := json.Unmarshal([]byte(testData.stub), &typeMetaAdder)
if err != nil {
t.Fatalf("failed to unmarshal stub (%v): %v", testData.stub, err)
}
typeMetaAdder["apiVersion"] = mapping.GroupVersionKind.GroupVersion().String()
typeMetaAdder["kind"] = mapping.GroupVersionKind.Kind
rsc := dClient.Resource(mapping.Resource).Namespace(testNamespace)
if mapping.Scope == meta.RESTScopeRoot {
rsc = dClient.Resource(mapping.Resource)
}
obj := &unstructured.Unstructured{Object: typeMetaAdder}
name := obj.GetName()
DryRunCreateTest(t, rsc, obj, gvResource)
if _, err := rsc.Create(obj, metav1.CreateOptions{}); err != nil {
t.Fatalf("failed to create stub for %s: %#v", gvResource, err)
}
DryRunUpdateTest(t, rsc, name)
DryRunPatchTest(t, rsc, name)
DryRunScalePatchTest(t, rsc, name)
DryRunScaleUpdateTest(t, rsc, name)
if resourceToTest.hasDeleteCollection {
DryRunDeleteCollectionTest(t, rsc, name)
}
DryRunDeleteTest(t, rsc, name)
if err = rsc.Delete(obj.GetName(), metav1.NewDeleteOptions(0)); err != nil {
t.Fatalf("deleting final object failed: %v", err)
}
})
}
}
func startRealMasterOrDie(t *testing.T, certDir string) *restclient.Config {
_, defaultServiceClusterIPRange, err := net.ParseCIDR("10.0.0.0/24")
if err != nil {
t.Fatal(err)
}
listener, _, err := genericapiserveroptions.CreateListener("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
kubeAPIServerOptions := options.NewServerRunOptions()
kubeAPIServerOptions.InsecureServing.BindPort = 0
kubeAPIServerOptions.SecureServing.Listener = listener
kubeAPIServerOptions.SecureServing.ServerCert.CertDirectory = certDir
kubeAPIServerOptions.Etcd.StorageConfig.ServerList = []string{framework.GetEtcdURL()}
kubeAPIServerOptions.Etcd.DefaultStorageMediaType = runtime.ContentTypeJSON // force json we can easily interpret the result in etcd
kubeAPIServerOptions.ServiceClusterIPRange = *defaultServiceClusterIPRange
kubeAPIServerOptions.Authorization.Modes = []string{"RBAC"}
kubeAPIServerOptions.Admission.GenericAdmission.DisablePlugins = []string{"ServiceAccount"}
completedOptions, err := app.Complete(kubeAPIServerOptions)
if err != nil {
t.Fatal(err)
}
kubeAPIServerOptions.APIEnablement.RuntimeConfig.Set("api/all=true")
kubeAPIServer, err := app.CreateServerChain(completedOptions, wait.NeverStop)
if err != nil {
t.Fatal(err)
}
kubeClientConfig := restclient.CopyConfig(kubeAPIServer.LoopbackClientConfig)
go func() {
// Catch panics that occur in this go routine so we get a comprehensible failure
defer func() {
if err := recover(); err != nil {
t.Errorf("Unexpected panic trying to start API master: %#v", err)
}
}()
if err := kubeAPIServer.PrepareRun().Run(wait.NeverStop); err != nil {
t.Fatal(err)
}
}()
lastHealth := ""
if err := wait.PollImmediate(time.Second, time.Minute, func() (done bool, err error) {
// wait for the server to be healthy
result := clientset.NewForConfigOrDie(kubeClientConfig).RESTClient().Get().AbsPath("/healthz").Do()
content, _ := result.Raw()
lastHealth = string(content)
if errResult := result.Error(); errResult != nil {
t.Log(errResult)
return false, nil
}
var status int
result.StatusCode(&status)
return status == http.StatusOK, nil
}); err != nil {
t.Log(lastHealth)
t.Fatal(err)
}
// this test makes lots of requests, don't be slow
kubeClientConfig.QPS = 99999
kubeClientConfig.Burst = 9999
return kubeClientConfig
}
func gvr(g, v, r string) schema.GroupVersionResource {
return schema.GroupVersionResource{Group: g, Version: v, Resource: r}
}
type resourceToTest struct {
gvk schema.GroupVersionKind
gvr schema.GroupVersionResource
namespaced bool
hasDeleteCollection bool
}
func getResourcesToTest(serverResources []*metav1.APIResourceList, isOAPI bool, t *testing.T) []resourceToTest {
resourcesToTest := []resourceToTest{}
for _, discoveryGroup := range serverResources {
for _, discoveryResource := range discoveryGroup.APIResources {
// this is a subresource, skip it
if strings.Contains(discoveryResource.Name, "/") {
continue
}
hasCreate := false
hasGet := false
hasDeleteCollection := false
for _, verb := range discoveryResource.Verbs {
if string(verb) == "get" {
hasGet = true
}
if string(verb) == "create" {
hasCreate = true
}
if string(verb) == "deletecollection" {
hasDeleteCollection = true
}
}
if !(hasCreate && hasGet) {
continue
}
resourceGV, err := schema.ParseGroupVersion(discoveryGroup.GroupVersion)
if err != nil {
t.Fatal(err)
}
gvk := resourceGV.WithKind(discoveryResource.Kind)
if len(discoveryResource.Group) > 0 || len(discoveryResource.Version) > 0 {
gvk = schema.GroupVersionKind{
Group: discoveryResource.Group,
Version: discoveryResource.Version,
Kind: discoveryResource.Kind,
}
}
gvr := resourceGV.WithResource(discoveryResource.Name)
resourcesToTest = append(resourcesToTest, resourceToTest{
gvk: gvk,
gvr: gvr,
namespaced: discoveryResource.Namespaced,
hasDeleteCollection: hasDeleteCollection,
})
}
}
return resourcesToTest
}
<file_sep>/pkg/kubectl/cmd/create/create_test.go
/*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package create
import (
"net/http"
"testing"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/cli-runtime/pkg/genericclioptions/resource"
"k8s.io/client-go/rest/fake"
cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing"
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/scheme"
)
func TestExtraArgsFail(t *testing.T) {
initTestErrorHandler(t)
f := cmdtesting.NewTestFactory()
defer f.Cleanup()
c := NewCmdCreate(f, genericclioptions.NewTestIOStreamsDiscard())
options := CreateOptions{}
if options.ValidateArgs(c, []string{"rc"}) == nil {
t.Errorf("unexpected non-error")
}
}
func TestCreateObject(t *testing.T) {
initTestErrorHandler(t)
_, _, rc := testData()
rc.Items[0].Name = "redis-master-controller"
tf := cmdtesting.NewTestFactory().WithNamespace("test")
defer tf.Cleanup()
codec := scheme.Codecs.LegacyCodec(scheme.Scheme.PrioritizedVersionsAllGroups()...)
tf.UnstructuredClient = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: "v1"},
NegotiatedSerializer: unstructuredSerializer,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
switch p, m := req.URL.Path, req.Method; {
case p == "/namespaces/test/replicationcontrollers" && m == http.MethodPost:
return &http.Response{StatusCode: http.StatusCreated, Header: defaultHeader(), Body: objBody(codec, &rc.Items[0])}, nil
default:
t.Fatalf("unexpected request: %#v\n%#v", req.URL, req)
return nil, nil
}
}),
}
ioStreams, _, buf, _ := genericclioptions.NewTestIOStreams()
cmd := NewCmdCreate(tf, ioStreams)
cmd.Flags().Set("filename", "../../../../test/e2e/testing-manifests/guestbook/legacy/redis-master-controller.yaml")
cmd.Flags().Set("output", "name")
cmd.Run(cmd, []string{})
// uses the name from the file, not the response
if buf.String() != "replicationcontroller/redis-master-controller\n" {
t.Errorf("unexpected output: %s", buf.String())
}
}
func TestCreateMultipleObject(t *testing.T) {
initTestErrorHandler(t)
_, svc, rc := testData()
tf := cmdtesting.NewTestFactory().WithNamespace("test")
defer tf.Cleanup()
codec := scheme.Codecs.LegacyCodec(scheme.Scheme.PrioritizedVersionsAllGroups()...)
tf.UnstructuredClient = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: "v1"},
NegotiatedSerializer: unstructuredSerializer,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
switch p, m := req.URL.Path, req.Method; {
case p == "/namespaces/test/services" && m == http.MethodPost:
return &http.Response{StatusCode: http.StatusCreated, Header: defaultHeader(), Body: objBody(codec, &svc.Items[0])}, nil
case p == "/namespaces/test/replicationcontrollers" && m == http.MethodPost:
return &http.Response{StatusCode: http.StatusCreated, Header: defaultHeader(), Body: objBody(codec, &rc.Items[0])}, nil
default:
t.Fatalf("unexpected request: %#v\n%#v", req.URL, req)
return nil, nil
}
}),
}
ioStreams, _, buf, _ := genericclioptions.NewTestIOStreams()
cmd := NewCmdCreate(tf, ioStreams)
cmd.Flags().Set("filename", "../../../../test/e2e/testing-manifests/guestbook/legacy/redis-master-controller.yaml")
cmd.Flags().Set("filename", "../../../../test/e2e/testing-manifests/guestbook/frontend-service.yaml")
cmd.Flags().Set("output", "name")
cmd.Run(cmd, []string{})
// Names should come from the REST response, NOT the files
if buf.String() != "replicationcontroller/rc1\nservice/baz\n" {
t.Errorf("unexpected output: %s", buf.String())
}
}
func TestCreateDirectory(t *testing.T) {
initTestErrorHandler(t)
_, _, rc := testData()
rc.Items[0].Name = "name"
tf := cmdtesting.NewTestFactory().WithNamespace("test")
defer tf.Cleanup()
codec := scheme.Codecs.LegacyCodec(scheme.Scheme.PrioritizedVersionsAllGroups()...)
tf.UnstructuredClient = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: "v1"},
NegotiatedSerializer: unstructuredSerializer,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
switch p, m := req.URL.Path, req.Method; {
case p == "/namespaces/test/replicationcontrollers" && m == http.MethodPost:
return &http.Response{StatusCode: http.StatusCreated, Header: defaultHeader(), Body: objBody(codec, &rc.Items[0])}, nil
default:
t.Fatalf("unexpected request: %#v\n%#v", req.URL, req)
return nil, nil
}
}),
}
ioStreams, _, buf, _ := genericclioptions.NewTestIOStreams()
cmd := NewCmdCreate(tf, ioStreams)
cmd.Flags().Set("filename", "../../../../test/e2e/testing-manifests/guestbook/legacy")
cmd.Flags().Set("output", "name")
cmd.Run(cmd, []string{})
if buf.String() != "replicationcontroller/name\nreplicationcontroller/name\nreplicationcontroller/name\n" {
t.Errorf("unexpected output: %s", buf.String())
}
}
var unstructuredSerializer = resource.UnstructuredPlusDefaultContentConfig().NegotiatedSerializer
func initTestErrorHandler(t *testing.T) {
cmdutil.BehaviorOnFatal(func(str string, code int) {
t.Errorf("Error running command (exit code %d): %s", code, str)
})
}
func testData() (*corev1.PodList, *corev1.ServiceList, *corev1.ReplicationControllerList) {
grace := int64(30)
pods := &corev1.PodList{
ListMeta: metav1.ListMeta{
ResourceVersion: "15",
},
Items: []corev1.Pod{
{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "test", ResourceVersion: "10"},
Spec: corev1.PodSpec{
RestartPolicy: corev1.RestartPolicyAlways,
DNSPolicy: corev1.DNSClusterFirst,
TerminationGracePeriodSeconds: &grace,
SecurityContext: &corev1.PodSecurityContext{},
},
},
{
ObjectMeta: metav1.ObjectMeta{Name: "bar", Namespace: "test", ResourceVersion: "11"},
Spec: corev1.PodSpec{
RestartPolicy: corev1.RestartPolicyAlways,
DNSPolicy: corev1.DNSClusterFirst,
TerminationGracePeriodSeconds: &grace,
SecurityContext: &corev1.PodSecurityContext{},
},
},
},
}
svc := &corev1.ServiceList{
ListMeta: metav1.ListMeta{
ResourceVersion: "16",
},
Items: []corev1.Service{
{
ObjectMeta: metav1.ObjectMeta{Name: "baz", Namespace: "test", ResourceVersion: "12"},
Spec: corev1.ServiceSpec{
SessionAffinity: "None",
Type: corev1.ServiceTypeClusterIP,
},
},
},
}
one := int32(1)
rc := &corev1.ReplicationControllerList{
ListMeta: metav1.ListMeta{
ResourceVersion: "17",
},
Items: []corev1.ReplicationController{
{
ObjectMeta: metav1.ObjectMeta{Name: "rc1", Namespace: "test", ResourceVersion: "18"},
Spec: corev1.ReplicationControllerSpec{
Replicas: &one,
},
},
},
}
return pods, svc, rc
}
<file_sep>/staging/src/k8s.io/csi-api/pkg/crd/crd_test.go
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package crd_test
import (
"path/filepath"
"testing"
"github.com/ghodss/yaml"
"io/ioutil"
apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
apiextensionsscheme "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/scheme"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/diff"
"k8s.io/csi-api/pkg/crd"
"os"
)
func TestBootstrapCRDs(t *testing.T) {
testObjects(t, crd.CSIDriverCRD(), "csidriver.yaml")
testObjects(t, crd.CSINodeInfoCRD(), "csinodeinfo.yaml")
}
func testObjects(t *testing.T, crd *apiextensionsv1beta1.CustomResourceDefinition, fixtureFilename string) {
filename := filepath.Join("testdata", fixtureFilename)
expectedYAML, err := ioutil.ReadFile(filename)
if err != nil {
t.Fatal(err)
}
jsonData, err := runtime.Encode(apiextensionsscheme.Codecs.LegacyCodec(apiextensionsv1beta1.SchemeGroupVersion), crd)
if err != nil {
t.Fatal(err)
}
yamlData, err := yaml.JSONToYAML(jsonData)
if err != nil {
t.Fatal(err)
}
if string(yamlData) != string(expectedYAML) {
t.Errorf("Bootstrap CRD data does not match the test fixture in %s", filename)
const updateEnvVar = "UPDATE_CSI_CRD_FIXTURE_DATA"
if os.Getenv(updateEnvVar) == "true" {
if err := ioutil.WriteFile(filename, []byte(yamlData), os.FileMode(0755)); err == nil {
t.Logf("Updated data in %s", filename)
t.Logf("Verify the diff, commit changes, and rerun the tests")
} else {
t.Logf("Could not update data in %s: %v", filename, err)
}
} else {
t.Logf("Diff between data in code and fixture data in %s:\n-------------\n%s", filename, diff.StringDiff(string(yamlData), string(expectedYAML)))
t.Logf("If the change is expected, re-run with %s=true to update the fixtures", updateEnvVar)
}
}
}
<file_sep>/test/integration/etcd/etcd_storage_path_test.go
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package etcd
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"reflect"
"strings"
"testing"
"time"
"k8s.io/api/core/v1"
apiequality "k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/diff"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/wait"
genericapiserveroptions "k8s.io/apiserver/pkg/server/options"
cacheddiscovery "k8s.io/client-go/discovery/cached"
"k8s.io/client-go/dynamic"
clientset "k8s.io/client-go/kubernetes"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/restmapper"
"k8s.io/kubernetes/cmd/kube-apiserver/app"
"k8s.io/kubernetes/cmd/kube-apiserver/app/options"
"k8s.io/kubernetes/test/integration"
"k8s.io/kubernetes/test/integration/framework"
// install all APIs
_ "k8s.io/kubernetes/pkg/master" // TODO what else is needed
"github.com/coreos/etcd/clientv3"
)
// Etcd data for all persisted objects.
var etcdStorageData = map[schema.GroupVersionResource]struct {
stub string // Valid JSON stub to use during create
prerequisites []prerequisite // Optional, ordered list of JSON objects to create before stub
expectedEtcdPath string // Expected location of object in etcd, do not use any variables, constants, etc to derive this value - always supply the full raw string
expectedGVK *schema.GroupVersionKind // The GVK that we expect this object to be stored as - leave this nil to use the default
}{
// k8s.io/kubernetes/pkg/api/v1
gvr("", "v1", "configmaps"): {
stub: `{"data": {"foo": "bar"}, "metadata": {"name": "cm1"}}`,
expectedEtcdPath: "/registry/configmaps/etcdstoragepathtestnamespace/cm1",
},
gvr("", "v1", "services"): {
stub: `{"metadata": {"name": "service1"}, "spec": {"externalName": "service1name", "ports": [{"port": 10000, "targetPort": 11000}], "selector": {"test": "data"}}}`,
expectedEtcdPath: "/registry/services/specs/etcdstoragepathtestnamespace/service1",
},
gvr("", "v1", "podtemplates"): {
stub: `{"metadata": {"name": "pt1name"}, "template": {"metadata": {"labels": {"pt": "01"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container9"}]}}}`,
expectedEtcdPath: "/registry/podtemplates/etcdstoragepathtestnamespace/pt1name",
},
gvr("", "v1", "pods"): {
stub: `{"metadata": {"name": "pod1"}, "spec": {"containers": [{"image": "fedora:latest", "name": "container7", "resources": {"limits": {"cpu": "1M"}, "requests": {"cpu": "1M"}}}]}}`,
expectedEtcdPath: "/registry/pods/etcdstoragepathtestnamespace/pod1",
},
gvr("", "v1", "endpoints"): {
stub: `{"metadata": {"name": "ep1name"}, "subsets": [{"addresses": [{"hostname": "bar-001", "ip": "192.168.3.1"}], "ports": [{"port": 8000}]}]}`,
expectedEtcdPath: "/registry/services/endpoints/etcdstoragepathtestnamespace/ep1name",
},
gvr("", "v1", "resourcequotas"): {
stub: `{"metadata": {"name": "rq1name"}, "spec": {"hard": {"cpu": "5M"}}}`,
expectedEtcdPath: "/registry/resourcequotas/etcdstoragepathtestnamespace/rq1name",
},
gvr("", "v1", "limitranges"): {
stub: `{"metadata": {"name": "lr1name"}, "spec": {"limits": [{"type": "Pod"}]}}`,
expectedEtcdPath: "/registry/limitranges/etcdstoragepathtestnamespace/lr1name",
},
gvr("", "v1", "namespaces"): {
stub: `{"metadata": {"name": "namespace1"}, "spec": {"finalizers": ["kubernetes"]}}`,
expectedEtcdPath: "/registry/namespaces/namespace1",
},
gvr("", "v1", "nodes"): {
stub: `{"metadata": {"name": "node1"}, "spec": {"unschedulable": true}}`,
expectedEtcdPath: "/registry/minions/node1",
},
gvr("", "v1", "persistentvolumes"): {
stub: `{"metadata": {"name": "pv1name"}, "spec": {"accessModes": ["ReadWriteOnce"], "capacity": {"storage": "3M"}, "hostPath": {"path": "/tmp/test/"}}}`,
expectedEtcdPath: "/registry/persistentvolumes/pv1name",
},
gvr("", "v1", "events"): {
stub: `{"involvedObject": {"namespace": "etcdstoragepathtestnamespace"}, "message": "some data here", "metadata": {"name": "event1"}}`,
expectedEtcdPath: "/registry/events/etcdstoragepathtestnamespace/event1",
},
gvr("", "v1", "persistentvolumeclaims"): {
stub: `{"metadata": {"name": "pvc1"}, "spec": {"accessModes": ["ReadWriteOnce"], "resources": {"limits": {"storage": "1M"}, "requests": {"storage": "2M"}}, "selector": {"matchLabels": {"pvc": "stuff"}}}}`,
expectedEtcdPath: "/registry/persistentvolumeclaims/etcdstoragepathtestnamespace/pvc1",
},
gvr("", "v1", "serviceaccounts"): {
stub: `{"metadata": {"name": "sa1name"}, "secrets": [{"name": "secret00"}]}`,
expectedEtcdPath: "/registry/serviceaccounts/etcdstoragepathtestnamespace/sa1name",
},
gvr("", "v1", "secrets"): {
stub: `{"data": {"key": "<KEY>"}, "metadata": {"name": "secret1"}}`,
expectedEtcdPath: "/registry/secrets/etcdstoragepathtestnamespace/secret1",
},
gvr("", "v1", "replicationcontrollers"): {
stub: `{"metadata": {"name": "rc1"}, "spec": {"selector": {"new": "stuff"}, "template": {"metadata": {"labels": {"new": "stuff"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container8"}]}}}}`,
expectedEtcdPath: "/registry/controllers/etcdstoragepathtestnamespace/rc1",
},
// --
// k8s.io/kubernetes/pkg/apis/apps/v1beta1
gvr("apps", "v1beta1", "statefulsets"): {
stub: `{"metadata": {"name": "ss1"}, "spec": {"selector": {"matchLabels": {"a": "b"}}, "template": {"metadata": {"labels": {"a": "b"}}}}}`,
expectedEtcdPath: "/registry/statefulsets/etcdstoragepathtestnamespace/ss1",
expectedGVK: gvkP("apps", "v1", "StatefulSet"),
},
gvr("apps", "v1beta1", "deployments"): {
stub: `{"metadata": {"name": "deployment2"}, "spec": {"selector": {"matchLabels": {"f": "z"}}, "template": {"metadata": {"labels": {"f": "z"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container6"}]}}}}`,
expectedEtcdPath: "/registry/deployments/etcdstoragepathtestnamespace/deployment2",
expectedGVK: gvkP("apps", "v1", "Deployment"),
},
gvr("apps", "v1beta1", "controllerrevisions"): {
stub: `{"metadata":{"name":"crs1"},"data":{"name":"abc","namespace":"default","creationTimestamp":null,"Spec":{"Replicas":0,"Selector":{"matchLabels":{"foo":"bar"}},"Template":{"creationTimestamp":null,"labels":{"foo":"bar"},"Spec":{"Volumes":null,"InitContainers":null,"Containers":null,"RestartPolicy":"Always","TerminationGracePeriodSeconds":null,"ActiveDeadlineSeconds":null,"DNSPolicy":"ClusterFirst","NodeSelector":null,"ServiceAccountName":"","AutomountServiceAccountToken":null,"NodeName":"","SecurityContext":null,"ImagePullSecrets":null,"Hostname":"","Subdomain":"","Affinity":null,"SchedulerName":"","Tolerations":null,"HostAliases":null}},"VolumeClaimTemplates":null,"ServiceName":""},"Status":{"ObservedGeneration":null,"Replicas":0}},"revision":0}`,
expectedEtcdPath: "/registry/controllerrevisions/etcdstoragepathtestnamespace/crs1",
expectedGVK: gvkP("apps", "v1", "ControllerRevision"),
},
// --
// k8s.io/kubernetes/pkg/apis/apps/v1beta2
gvr("apps", "v1beta2", "statefulsets"): {
stub: `{"metadata": {"name": "ss2"}, "spec": {"selector": {"matchLabels": {"a": "b"}}, "template": {"metadata": {"labels": {"a": "b"}}}}}`,
expectedEtcdPath: "/registry/statefulsets/etcdstoragepathtestnamespace/ss2",
expectedGVK: gvkP("apps", "v1", "StatefulSet"),
},
gvr("apps", "v1beta2", "deployments"): {
stub: `{"metadata": {"name": "deployment3"}, "spec": {"selector": {"matchLabels": {"f": "z"}}, "template": {"metadata": {"labels": {"f": "z"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container6"}]}}}}`,
expectedEtcdPath: "/registry/deployments/etcdstoragepathtestnamespace/deployment3",
expectedGVK: gvkP("apps", "v1", "Deployment"),
},
gvr("apps", "v1beta2", "daemonsets"): {
stub: `{"metadata": {"name": "ds5"}, "spec": {"selector": {"matchLabels": {"a": "b"}}, "template": {"metadata": {"labels": {"a": "b"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container6"}]}}}}`,
expectedEtcdPath: "/registry/daemonsets/etcdstoragepathtestnamespace/ds5",
expectedGVK: gvkP("apps", "v1", "DaemonSet"),
},
gvr("apps", "v1beta2", "replicasets"): {
stub: `{"metadata": {"name": "rs2"}, "spec": {"selector": {"matchLabels": {"g": "h"}}, "template": {"metadata": {"labels": {"g": "h"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container4"}]}}}}`,
expectedEtcdPath: "/registry/replicasets/etcdstoragepathtestnamespace/rs2",
expectedGVK: gvkP("apps", "v1", "ReplicaSet"),
},
gvr("apps", "v1beta2", "controllerrevisions"): {
stub: `{"metadata":{"name":"crs2"},"data":{"name":"abc","namespace":"default","creationTimestamp":null,"Spec":{"Replicas":0,"Selector":{"matchLabels":{"foo":"bar"}},"Template":{"creationTimestamp":null,"labels":{"foo":"bar"},"Spec":{"Volumes":null,"InitContainers":null,"Containers":null,"RestartPolicy":"Always","TerminationGracePeriodSeconds":null,"ActiveDeadlineSeconds":null,"DNSPolicy":"ClusterFirst","NodeSelector":null,"ServiceAccountName":"","AutomountServiceAccountToken":null,"NodeName":"","SecurityContext":null,"ImagePullSecrets":null,"Hostname":"","Subdomain":"","Affinity":null,"SchedulerName":"","Tolerations":null,"HostAliases":null}},"VolumeClaimTemplates":null,"ServiceName":""},"Status":{"ObservedGeneration":null,"Replicas":0}},"revision":0}`,
expectedEtcdPath: "/registry/controllerrevisions/etcdstoragepathtestnamespace/crs2",
expectedGVK: gvkP("apps", "v1", "ControllerRevision"),
},
// --
// k8s.io/kubernetes/pkg/apis/apps/v1
gvr("apps", "v1", "daemonsets"): {
stub: `{"metadata": {"name": "ds6"}, "spec": {"selector": {"matchLabels": {"a": "b"}}, "template": {"metadata": {"labels": {"a": "b"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container6"}]}}}}`,
expectedEtcdPath: "/registry/daemonsets/etcdstoragepathtestnamespace/ds6",
},
gvr("apps", "v1", "deployments"): {
stub: `{"metadata": {"name": "deployment4"}, "spec": {"selector": {"matchLabels": {"f": "z"}}, "template": {"metadata": {"labels": {"f": "z"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container6"}]}}}}`,
expectedEtcdPath: "/registry/deployments/etcdstoragepathtestnamespace/deployment4",
},
gvr("apps", "v1", "statefulsets"): {
stub: `{"metadata": {"name": "ss3"}, "spec": {"selector": {"matchLabels": {"a": "b"}}, "template": {"metadata": {"labels": {"a": "b"}}}}}`,
expectedEtcdPath: "/registry/statefulsets/etcdstoragepathtestnamespace/ss3",
},
gvr("apps", "v1", "replicasets"): {
stub: `{"metadata": {"name": "rs3"}, "spec": {"selector": {"matchLabels": {"g": "h"}}, "template": {"metadata": {"labels": {"g": "h"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container4"}]}}}}`,
expectedEtcdPath: "/registry/replicasets/etcdstoragepathtestnamespace/rs3",
},
gvr("apps", "v1", "controllerrevisions"): {
stub: `{"metadata":{"name":"crs3"},"data":{"name":"abc","namespace":"default","creationTimestamp":null,"Spec":{"Replicas":0,"Selector":{"matchLabels":{"foo":"bar"}},"Template":{"creationTimestamp":null,"labels":{"foo":"bar"},"Spec":{"Volumes":null,"InitContainers":null,"Containers":null,"RestartPolicy":"Always","TerminationGracePeriodSeconds":null,"ActiveDeadlineSeconds":null,"DNSPolicy":"ClusterFirst","NodeSelector":null,"ServiceAccountName":"","AutomountServiceAccountToken":null,"NodeName":"","SecurityContext":null,"ImagePullSecrets":null,"Hostname":"","Subdomain":"","Affinity":null,"SchedulerName":"","Tolerations":null,"HostAliases":null}},"VolumeClaimTemplates":null,"ServiceName":""},"Status":{"ObservedGeneration":null,"Replicas":0}},"revision":0}`,
expectedEtcdPath: "/registry/controllerrevisions/etcdstoragepathtestnamespace/crs3",
},
// --
// k8s.io/kubernetes/pkg/apis/autoscaling/v1
gvr("autoscaling", "v1", "horizontalpodautoscalers"): {
stub: `{"metadata": {"name": "hpa2"}, "spec": {"maxReplicas": 3, "scaleTargetRef": {"kind": "something", "name": "cross"}}}`,
expectedEtcdPath: "/registry/horizontalpodautoscalers/etcdstoragepathtestnamespace/hpa2",
},
// --
// k8s.io/kubernetes/pkg/apis/autoscaling/v2beta1
gvr("autoscaling", "v2beta1", "horizontalpodautoscalers"): {
stub: `{"metadata": {"name": "hpa1"}, "spec": {"maxReplicas": 3, "scaleTargetRef": {"kind": "something", "name": "cross"}}}`,
expectedEtcdPath: "/registry/horizontalpodautoscalers/etcdstoragepathtestnamespace/hpa1",
expectedGVK: gvkP("autoscaling", "v1", "HorizontalPodAutoscaler"),
},
// --
// k8s.io/kubernetes/pkg/apis/autoscaling/v2beta2
gvr("autoscaling", "v2beta2", "horizontalpodautoscalers"): {
stub: `{"metadata": {"name": "hpa3"}, "spec": {"maxReplicas": 3, "scaleTargetRef": {"kind": "something", "name": "cross"}}}`,
expectedEtcdPath: "/registry/horizontalpodautoscalers/etcdstoragepathtestnamespace/hpa3",
expectedGVK: gvkP("autoscaling", "v1", "HorizontalPodAutoscaler"),
},
// --
// k8s.io/kubernetes/pkg/apis/batch/v1
gvr("batch", "v1", "jobs"): {
stub: `{"metadata": {"name": "job1"}, "spec": {"manualSelector": true, "selector": {"matchLabels": {"controller-uid": "uid1"}}, "template": {"metadata": {"labels": {"controller-uid": "uid1"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container1"}], "dnsPolicy": "ClusterFirst", "restartPolicy": "Never"}}}}`,
expectedEtcdPath: "/registry/jobs/etcdstoragepathtestnamespace/job1",
},
// --
// k8s.io/kubernetes/pkg/apis/batch/v1beta1
gvr("batch", "v1beta1", "cronjobs"): {
stub: `{"metadata": {"name": "cjv1beta1"}, "spec": {"jobTemplate": {"spec": {"template": {"metadata": {"labels": {"controller-uid": "uid0"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container0"}], "dnsPolicy": "ClusterFirst", "restartPolicy": "Never"}}}}, "schedule": "* * * * *"}}`,
expectedEtcdPath: "/registry/cronjobs/etcdstoragepathtestnamespace/cjv1beta1",
},
// --
// k8s.io/kubernetes/pkg/apis/batch/v2alpha1
gvr("batch", "v2alpha1", "cronjobs"): {
stub: `{"metadata": {"name": "cjv2alpha1"}, "spec": {"jobTemplate": {"spec": {"template": {"metadata": {"labels": {"controller-uid": "uid0"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container0"}], "dnsPolicy": "ClusterFirst", "restartPolicy": "Never"}}}}, "schedule": "* * * * *"}}`,
expectedEtcdPath: "/registry/cronjobs/etcdstoragepathtestnamespace/cjv2alpha1",
expectedGVK: gvkP("batch", "v1beta1", "CronJob"),
},
// --
// k8s.io/kubernetes/pkg/apis/certificates/v1beta1
gvr("certificates.k8s.io", "v1beta1", "certificatesigningrequests"): {
stub: `{"metadata": {"name": "csr1"}, "spec": {"request": "<KEY>}}`,
expectedEtcdPath: "/registry/certificatesigningrequests/csr1",
},
// --
// k8s.io/kubernetes/pkg/apis/coordination/v1beta1
gvr("coordination.k8s.io", "v1beta1", "leases"): {
stub: `{"metadata": {"name": "lease1"}, "spec": {"holderIdentity": "holder", "leaseDurationSeconds": 5}}`,
expectedEtcdPath: "/registry/leases/etcdstoragepathtestnamespace/lease1",
},
// --
// k8s.io/kubernetes/pkg/apis/events/v1beta1
gvr("events.k8s.io", "v1beta1", "events"): {
stub: `{"metadata": {"name": "event2"}, "regarding": {"namespace": "etcdstoragepathtestnamespace"}, "note": "some data here", "eventTime": "2017-08-09T15:04:05.000000Z", "reportingInstance": "node-xyz", "reportingController": "k8s.io/my-controller", "action": "DidNothing", "reason": "Laziness"}`,
expectedEtcdPath: "/registry/events/etcdstoragepathtestnamespace/event2",
expectedGVK: gvkP("", "v1", "Event"),
},
// --
// k8s.io/kubernetes/pkg/apis/extensions/v1beta1
gvr("extensions", "v1beta1", "daemonsets"): {
stub: `{"metadata": {"name": "ds1"}, "spec": {"selector": {"matchLabels": {"u": "t"}}, "template": {"metadata": {"labels": {"u": "t"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container5"}]}}}}`,
expectedEtcdPath: "/registry/daemonsets/etcdstoragepathtestnamespace/ds1",
expectedGVK: gvkP("apps", "v1", "DaemonSet"),
},
gvr("extensions", "v1beta1", "podsecuritypolicies"): {
stub: `{"metadata": {"name": "psp1"}, "spec": {"fsGroup": {"rule": "RunAsAny"}, "privileged": true, "runAsUser": {"rule": "RunAsAny"}, "seLinux": {"rule": "MustRunAs"}, "supplementalGroups": {"rule": "RunAsAny"}}}`,
expectedEtcdPath: "/registry/podsecuritypolicy/psp1",
expectedGVK: gvkP("policy", "v1beta1", "PodSecurityPolicy"),
},
gvr("extensions", "v1beta1", "ingresses"): {
stub: `{"metadata": {"name": "ingress1"}, "spec": {"backend": {"serviceName": "service", "servicePort": 5000}}}`,
expectedEtcdPath: "/registry/ingress/etcdstoragepathtestnamespace/ingress1",
},
gvr("extensions", "v1beta1", "networkpolicies"): {
stub: `{"metadata": {"name": "np1"}, "spec": {"podSelector": {"matchLabels": {"e": "f"}}}}`,
expectedEtcdPath: "/registry/networkpolicies/etcdstoragepathtestnamespace/np1",
expectedGVK: gvkP("networking.k8s.io", "v1", "NetworkPolicy"),
},
gvr("extensions", "v1beta1", "deployments"): {
stub: `{"metadata": {"name": "deployment1"}, "spec": {"selector": {"matchLabels": {"f": "z"}}, "template": {"metadata": {"labels": {"f": "z"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container6"}]}}}}`,
expectedEtcdPath: "/registry/deployments/etcdstoragepathtestnamespace/deployment1",
expectedGVK: gvkP("apps", "v1", "Deployment"),
},
gvr("extensions", "v1beta1", "replicasets"): {
stub: `{"metadata": {"name": "rs1"}, "spec": {"selector": {"matchLabels": {"g": "h"}}, "template": {"metadata": {"labels": {"g": "h"}}, "spec": {"containers": [{"image": "fedora:latest", "name": "container4"}]}}}}`,
expectedEtcdPath: "/registry/replicasets/etcdstoragepathtestnamespace/rs1",
expectedGVK: gvkP("apps", "v1", "ReplicaSet"),
},
// --
// k8s.io/kubernetes/pkg/apis/networking/v1
gvr("networking.k8s.io", "v1", "networkpolicies"): {
stub: `{"metadata": {"name": "np2"}, "spec": {"podSelector": {"matchLabels": {"e": "f"}}}}`,
expectedEtcdPath: "/registry/networkpolicies/etcdstoragepathtestnamespace/np2",
},
// --
// k8s.io/kubernetes/pkg/apis/policy/v1beta1
gvr("policy", "v1beta1", "poddisruptionbudgets"): {
stub: `{"metadata": {"name": "pdb1"}, "spec": {"selector": {"matchLabels": {"anokkey": "anokvalue"}}}}`,
expectedEtcdPath: "/registry/poddisruptionbudgets/etcdstoragepathtestnamespace/pdb1",
},
gvr("policy", "v1beta1", "podsecuritypolicies"): {
stub: `{"metadata": {"name": "psp2"}, "spec": {"fsGroup": {"rule": "RunAsAny"}, "privileged": true, "runAsUser": {"rule": "RunAsAny"}, "seLinux": {"rule": "MustRunAs"}, "supplementalGroups": {"rule": "RunAsAny"}}}`,
expectedEtcdPath: "/registry/podsecuritypolicy/psp2",
},
// --
// k8s.io/kubernetes/pkg/apis/storage/v1alpha1
gvr("storage.k8s.io", "v1alpha1", "volumeattachments"): {
stub: `{"metadata": {"name": "va1"}, "spec": {"attacher": "gce", "nodeName": "localhost", "source": {"persistentVolumeName": "pv1"}}}`,
expectedEtcdPath: "/registry/volumeattachments/va1",
expectedGVK: gvkP("storage.k8s.io", "v1beta1", "VolumeAttachment"),
},
// --
// k8s.io/kubernetes/pkg/apis/storage/v1beta1
gvr("storage.k8s.io", "v1beta1", "volumeattachments"): {
stub: `{"metadata": {"name": "va2"}, "spec": {"attacher": "gce", "nodeName": "localhost", "source": {"persistentVolumeName": "pv2"}}}`,
expectedEtcdPath: "/registry/volumeattachments/va2",
},
// --
// k8s.io/kubernetes/pkg/apis/storage/v1beta1
gvr("storage.k8s.io", "v1beta1", "storageclasses"): {
stub: `{"metadata": {"name": "sc1"}, "provisioner": "aws"}`,
expectedEtcdPath: "/registry/storageclasses/sc1",
expectedGVK: gvkP("storage.k8s.io", "v1", "StorageClass"),
},
// --
// k8s.io/kubernetes/pkg/apis/storage/v1
gvr("storage.k8s.io", "v1", "storageclasses"): {
stub: `{"metadata": {"name": "sc2"}, "provisioner": "aws"}`,
expectedEtcdPath: "/registry/storageclasses/sc2",
},
// --
// k8s.io/kubernetes/pkg/apis/settings/v1alpha1
gvr("settings.k8s.io", "v1alpha1", "podpresets"): {
stub: `{"metadata": {"name": "podpre1"}, "spec": {"env": [{"name": "FOO"}]}}`,
expectedEtcdPath: "/registry/podpresets/etcdstoragepathtestnamespace/podpre1",
},
// --
// k8s.io/kubernetes/pkg/apis/rbac/v1alpha1
gvr("rbac.authorization.k8s.io", "v1alpha1", "roles"): {
stub: `{"metadata": {"name": "role1"}, "rules": [{"apiGroups": ["v1"], "resources": ["events"], "verbs": ["watch"]}]}`,
expectedEtcdPath: "/registry/roles/etcdstoragepathtestnamespace/role1",
expectedGVK: gvkP("rbac.authorization.k8s.io", "v1", "Role"),
},
gvr("rbac.authorization.k8s.io", "v1alpha1", "clusterroles"): {
stub: `{"metadata": {"name": "crole1"}, "rules": [{"nonResourceURLs": ["/version"], "verbs": ["get"]}]}`,
expectedEtcdPath: "/registry/clusterroles/crole1",
expectedGVK: gvkP("rbac.authorization.k8s.io", "v1", "ClusterRole"),
},
gvr("rbac.authorization.k8s.io", "v1alpha1", "rolebindings"): {
stub: `{"metadata": {"name": "roleb1"}, "roleRef": {"apiGroup": "rbac.authorization.k8s.io", "kind": "ClusterRole", "name": "somecr"}, "subjects": [{"apiVersion": "rbac.authorization.k8s.io/v1alpha1", "kind": "Group", "name": "system:authenticated"}]}`,
expectedEtcdPath: "/registry/rolebindings/etcdstoragepathtestnamespace/roleb1",
expectedGVK: gvkP("rbac.authorization.k8s.io", "v1", "RoleBinding"),
},
gvr("rbac.authorization.k8s.io", "v1alpha1", "clusterrolebindings"): {
stub: `{"metadata": {"name": "croleb1"}, "roleRef": {"apiGroup": "rbac.authorization.k8s.io", "kind": "ClusterRole", "name": "somecr"}, "subjects": [{"apiVersion": "rbac.authorization.k8s.io/v1alpha1", "kind": "Group", "name": "system:authenticated"}]}`,
expectedEtcdPath: "/registry/clusterrolebindings/croleb1",
expectedGVK: gvkP("rbac.authorization.k8s.io", "v1", "ClusterRoleBinding"),
},
// --
// k8s.io/kubernetes/pkg/apis/rbac/v1beta1
gvr("rbac.authorization.k8s.io", "v1beta1", "roles"): {
stub: `{"metadata": {"name": "role2"}, "rules": [{"apiGroups": ["v1"], "resources": ["events"], "verbs": ["watch"]}]}`,
expectedEtcdPath: "/registry/roles/etcdstoragepathtestnamespace/role2",
expectedGVK: gvkP("rbac.authorization.k8s.io", "v1", "Role"),
},
gvr("rbac.authorization.k8s.io", "v1beta1", "clusterroles"): {
stub: `{"metadata": {"name": "crole2"}, "rules": [{"nonResourceURLs": ["/version"], "verbs": ["get"]}]}`,
expectedEtcdPath: "/registry/clusterroles/crole2",
expectedGVK: gvkP("rbac.authorization.k8s.io", "v1", "ClusterRole"),
},
gvr("rbac.authorization.k8s.io", "v1beta1", "rolebindings"): {
stub: `{"metadata": {"name": "roleb2"}, "roleRef": {"apiGroup": "rbac.authorization.k8s.io", "kind": "ClusterRole", "name": "somecr"}, "subjects": [{"apiVersion": "rbac.authorization.k8s.io/v1alpha1", "kind": "Group", "name": "system:authenticated"}]}`,
expectedEtcdPath: "/registry/rolebindings/etcdstoragepathtestnamespace/roleb2",
expectedGVK: gvkP("rbac.authorization.k8s.io", "v1", "RoleBinding"),
},
gvr("rbac.authorization.k8s.io", "v1beta1", "clusterrolebindings"): {
stub: `{"metadata": {"name": "croleb2"}, "roleRef": {"apiGroup": "rbac.authorization.k8s.io", "kind": "ClusterRole", "name": "somecr"}, "subjects": [{"apiVersion": "rbac.authorization.k8s.io/v1alpha1", "kind": "Group", "name": "system:authenticated"}]}`,
expectedEtcdPath: "/registry/clusterrolebindings/croleb2",
expectedGVK: gvkP("rbac.authorization.k8s.io", "v1", "ClusterRoleBinding"),
},
// --
// k8s.io/kubernetes/pkg/apis/rbac/v1
gvr("rbac.authorization.k8s.io", "v1", "roles"): {
stub: `{"metadata": {"name": "role3"}, "rules": [{"apiGroups": ["v1"], "resources": ["events"], "verbs": ["watch"]}]}`,
expectedEtcdPath: "/registry/roles/etcdstoragepathtestnamespace/role3",
},
gvr("rbac.authorization.k8s.io", "v1", "clusterroles"): {
stub: `{"metadata": {"name": "crole3"}, "rules": [{"nonResourceURLs": ["/version"], "verbs": ["get"]}]}`,
expectedEtcdPath: "/registry/clusterroles/crole3",
},
gvr("rbac.authorization.k8s.io", "v1", "rolebindings"): {
stub: `{"metadata": {"name": "roleb3"}, "roleRef": {"apiGroup": "rbac.authorization.k8s.io", "kind": "ClusterRole", "name": "somecr"}, "subjects": [{"apiVersion": "rbac.authorization.k8s.io/v1alpha1", "kind": "Group", "name": "system:authenticated"}]}`,
expectedEtcdPath: "/registry/rolebindings/etcdstoragepathtestnamespace/roleb3",
},
gvr("rbac.authorization.k8s.io", "v1", "clusterrolebindings"): {
stub: `{"metadata": {"name": "croleb3"}, "roleRef": {"apiGroup": "rbac.authorization.k8s.io", "kind": "ClusterRole", "name": "somecr"}, "subjects": [{"apiVersion": "rbac.authorization.k8s.io/v1alpha1", "kind": "Group", "name": "system:authenticated"}]}`,
expectedEtcdPath: "/registry/clusterrolebindings/croleb3",
},
// --
// k8s.io/kubernetes/pkg/apis/admissionregistration/v1alpha1
gvr("admissionregistration.k8s.io", "v1alpha1", "initializerconfigurations"): {
stub: `{"metadata":{"name":"ic1"},"initializers":[{"name":"initializer.k8s.io","rules":[{"apiGroups":["group"],"apiVersions":["version"],"resources":["resource"]}],"failurePolicy":"Ignore"}]}`,
expectedEtcdPath: "/registry/initializerconfigurations/ic1",
},
// k8s.io/kubernetes/pkg/apis/admissionregistration/v1beta1
gvr("admissionregistration.k8s.io", "v1beta1", "validatingwebhookconfigurations"): {
stub: `{"metadata":{"name":"hook1","creationTimestamp":null},"webhooks":[{"name":"externaladmissionhook.k8s.io","clientConfig":{"service":{"namespace":"ns","name":"n"},"caBundle":null},"rules":[{"operations":["CREATE"],"apiGroups":["group"],"apiVersions":["version"],"resources":["resource"]}],"failurePolicy":"Ignore"}]}`,
expectedEtcdPath: "/registry/validatingwebhookconfigurations/hook1",
},
gvr("admissionregistration.k8s.io", "v1beta1", "mutatingwebhookconfigurations"): {
stub: `{"metadata":{"name":"hook1","creationTimestamp":null},"webhooks":[{"name":"externaladmissionhook.k8s.io","clientConfig":{"service":{"namespace":"ns","name":"n"},"caBundle":null},"rules":[{"operations":["CREATE"],"apiGroups":["group"],"apiVersions":["version"],"resources":["resource"]}],"failurePolicy":"Ignore"}]}`,
expectedEtcdPath: "/registry/mutatingwebhookconfigurations/hook1",
},
// --
// k8s.io/kubernetes/pkg/apis/scheduling/v1alpha1
gvr("scheduling.k8s.io", "v1alpha1", "priorityclasses"): {
stub: `{"metadata":{"name":"pc1"},"Value":1000}`,
expectedEtcdPath: "/registry/priorityclasses/pc1",
expectedGVK: gvkP("scheduling.k8s.io", "v1beta1", "PriorityClass"),
},
// --
// k8s.io/kubernetes/pkg/apis/scheduling/v1beta1
gvr("scheduling.k8s.io", "v1beta1", "priorityclasses"): {
stub: `{"metadata":{"name":"pc2"},"Value":1000}`,
expectedEtcdPath: "/registry/priorityclasses/pc2",
},
// --
// k8s.io/kube-aggregator/pkg/apis/apiregistration/v1beta1
// depends on aggregator using the same ungrouped RESTOptionsGetter as the kube apiserver, not SimpleRestOptionsFactory in aggregator.go
gvr("apiregistration.k8s.io", "v1beta1", "apiservices"): {
stub: `{"metadata": {"name": "as1.foo.com"}, "spec": {"group": "foo.com", "version": "as1", "groupPriorityMinimum":100, "versionPriority":10}}`,
expectedEtcdPath: "/registry/apiregistration.k8s.io/apiservices/as1.foo.com",
},
// --
// k8s.io/kube-aggregator/pkg/apis/apiregistration/v1
// depends on aggregator using the same ungrouped RESTOptionsGetter as the kube apiserver, not SimpleRestOptionsFactory in aggregator.go
gvr("apiregistration.k8s.io", "v1", "apiservices"): {
stub: `{"metadata": {"name": "as2.foo.com"}, "spec": {"group": "foo.com", "version": "as2", "groupPriorityMinimum":100, "versionPriority":10}}`,
expectedEtcdPath: "/registry/apiregistration.k8s.io/apiservices/as2.foo.com",
expectedGVK: gvkP("apiregistration.k8s.io", "v1beta1", "APIService"),
},
// --
// k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1
gvr("apiextensions.k8s.io", "v1beta1", "customresourcedefinitions"): {
stub: `{"metadata": {"name": "openshiftwebconsoleconfigs.webconsole.operator.openshift.io"},"spec": {"scope": "Cluster","group": "webconsole.operator.openshift.io","version": "v1alpha1","names": {"kind": "OpenShiftWebConsoleConfig","plural": "openshiftwebconsoleconfigs","singular": "openshiftwebconsoleconfig"}}}`,
expectedEtcdPath: "/registry/apiextensions.k8s.io/customresourcedefinitions/openshiftwebconsoleconfigs.webconsole.operator.openshift.io",
},
// --
}
// Only add kinds to this list when this a virtual resource with get and create verbs that doesn't actually
// store into it's kind. We've used this downstream for mappings before.
var kindWhiteList = sets.NewString()
// namespace used for all tests, do not change this
const testNamespace = "etcdstoragepathtestnamespace"
// TestEtcdStoragePath tests to make sure that all objects are stored in an expected location in etcd.
// It will start failing when a new type is added to ensure that all future types are added to this test.
// It will also fail when a type gets moved to a different location. Be very careful in this situation because
// it essentially means that you will be break old clusters unless you create some migration path for the old data.
func TestEtcdStoragePath(t *testing.T) {
certDir, _ := ioutil.TempDir("", "test-integration-etcd")
defer os.RemoveAll(certDir)
clientConfig, kvClient := startRealMasterOrDie(t, certDir)
defer func() {
dumpEtcdKVOnFailure(t, kvClient)
}()
client := &allClient{dynamicClient: dynamic.NewForConfigOrDie(clientConfig)}
kubeClient := clientset.NewForConfigOrDie(clientConfig)
if _, err := kubeClient.CoreV1().Namespaces().Create(&v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: testNamespace}}); err != nil {
t.Fatal(err)
}
discoveryClient := cacheddiscovery.NewMemCacheClient(kubeClient.Discovery())
restMapper := restmapper.NewDeferredDiscoveryRESTMapper(discoveryClient)
restMapper.Reset()
resourcesToPersist := []resourceToPersist{}
serverResources, err := kubeClient.Discovery().ServerResources()
if err != nil {
t.Fatal(err)
}
resourcesToPersist = append(resourcesToPersist, getResourcesToPersist(serverResources, false, t)...)
kindSeen := sets.NewString()
pathSeen := map[string][]schema.GroupVersionResource{}
etcdSeen := map[schema.GroupVersionResource]empty{}
cohabitatingResources := map[string]map[schema.GroupVersionKind]empty{}
for _, resourceToPersist := range resourcesToPersist {
t.Run(resourceToPersist.gvr.String(), func(t *testing.T) {
gvk := resourceToPersist.gvk
gvResource := resourceToPersist.gvr
kind := gvk.Kind
mapping := &meta.RESTMapping{
Resource: resourceToPersist.gvr,
GroupVersionKind: resourceToPersist.gvk,
Scope: meta.RESTScopeRoot,
}
if resourceToPersist.namespaced {
mapping.Scope = meta.RESTScopeNamespace
}
if kindWhiteList.Has(kind) {
kindSeen.Insert(kind)
t.Skip("whitelisted")
}
etcdSeen[gvResource] = empty{}
testData, hasTest := etcdStorageData[gvResource]
if !hasTest {
t.Fatalf("no test data for %s. Please add a test for your new type to etcdStorageData.", gvResource)
}
if len(testData.expectedEtcdPath) == 0 {
t.Fatalf("empty test data for %s", gvResource)
}
shouldCreate := len(testData.stub) != 0 // try to create only if we have a stub
var input *metaObject
if shouldCreate {
if input, err = jsonToMetaObject([]byte(testData.stub)); err != nil || input.isEmpty() {
t.Fatalf("invalid test data for %s: %v", gvResource, err)
}
}
all := &[]cleanupData{}
defer func() {
if !t.Failed() { // do not cleanup if test has already failed since we may need things in the etcd dump
if err := client.cleanup(all); err != nil {
t.Fatalf("failed to clean up etcd: %#v", err)
}
}
}()
if err := client.createPrerequisites(restMapper, testNamespace, testData.prerequisites, all); err != nil {
t.Fatalf("failed to create prerequisites for %s: %#v", gvResource, err)
}
if shouldCreate { // do not try to create items with no stub
if err := client.create(testData.stub, testNamespace, mapping, all); err != nil {
t.Fatalf("failed to create stub for %s: %#v", gvResource, err)
}
}
output, err := getFromEtcd(kvClient, testData.expectedEtcdPath)
if err != nil {
t.Fatalf("failed to get from etcd for %s: %#v", gvResource, err)
}
expectedGVK := gvk
if testData.expectedGVK != nil {
if gvk == *testData.expectedGVK {
t.Errorf("GVK override %s for %s is unnecessary or something was changed incorrectly", testData.expectedGVK, gvk)
}
expectedGVK = *testData.expectedGVK
}
actualGVK := output.getGVK()
if actualGVK != expectedGVK {
t.Errorf("GVK for %s does not match, expected %s got %s", kind, expectedGVK, actualGVK)
}
if !apiequality.Semantic.DeepDerivative(input, output) {
t.Errorf("Test stub for %s does not match: %s", kind, diff.ObjectGoPrintDiff(input, output))
}
addGVKToEtcdBucket(cohabitatingResources, actualGVK, getEtcdBucket(testData.expectedEtcdPath))
pathSeen[testData.expectedEtcdPath] = append(pathSeen[testData.expectedEtcdPath], mapping.Resource)
})
}
if inEtcdData, inEtcdSeen := diffMaps(etcdStorageData, etcdSeen); len(inEtcdData) != 0 || len(inEtcdSeen) != 0 {
t.Errorf("etcd data does not match the types we saw:\nin etcd data but not seen:\n%s\nseen but not in etcd data:\n%s", inEtcdData, inEtcdSeen)
}
if inKindData, inKindSeen := diffMaps(kindWhiteList, kindSeen); len(inKindData) != 0 || len(inKindSeen) != 0 {
t.Errorf("kind whitelist data does not match the types we saw:\nin kind whitelist but not seen:\n%s\nseen but not in kind whitelist:\n%s", inKindData, inKindSeen)
}
for bucket, gvks := range cohabitatingResources {
if len(gvks) != 1 {
gvkStrings := []string{}
for key := range gvks {
gvkStrings = append(gvkStrings, keyStringer(key))
}
t.Errorf("cohabitating resources in etcd bucket %s have inconsistent GVKs\nyou may need to use DefaultStorageFactory.AddCohabitatingResources to sync the GVK of these resources:\n%s", bucket, gvkStrings)
}
}
for path, gvrs := range pathSeen {
if len(gvrs) != 1 {
gvrStrings := []string{}
for _, key := range gvrs {
gvrStrings = append(gvrStrings, keyStringer(key))
}
t.Errorf("invalid test data, please ensure all expectedEtcdPath are unique, path %s has duplicate GVRs:\n%s", path, gvrStrings)
}
}
}
func startRealMasterOrDie(t *testing.T, certDir string) (*restclient.Config, clientv3.KV) {
_, defaultServiceClusterIPRange, err := net.ParseCIDR("10.0.0.0/24")
if err != nil {
t.Fatal(err)
}
listener, _, err := genericapiserveroptions.CreateListener("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
kubeAPIServerOptions := options.NewServerRunOptions()
kubeAPIServerOptions.InsecureServing.BindPort = 0
kubeAPIServerOptions.SecureServing.Listener = listener
kubeAPIServerOptions.SecureServing.ServerCert.CertDirectory = certDir
kubeAPIServerOptions.Etcd.StorageConfig.ServerList = []string{framework.GetEtcdURL()}
kubeAPIServerOptions.Etcd.DefaultStorageMediaType = runtime.ContentTypeJSON // force json we can easily interpret the result in etcd
kubeAPIServerOptions.ServiceClusterIPRange = *defaultServiceClusterIPRange
kubeAPIServerOptions.Authorization.Modes = []string{"RBAC"}
kubeAPIServerOptions.Admission.GenericAdmission.DisablePlugins = []string{"ServiceAccount"}
completedOptions, err := app.Complete(kubeAPIServerOptions)
if err != nil {
t.Fatal(err)
}
kubeAPIServerOptions.APIEnablement.RuntimeConfig.Set("api/all=true")
kubeAPIServer, err := app.CreateServerChain(completedOptions, wait.NeverStop)
if err != nil {
t.Fatal(err)
}
kubeClientConfig := restclient.CopyConfig(kubeAPIServer.LoopbackClientConfig)
go func() {
// Catch panics that occur in this go routine so we get a comprehensible failure
defer func() {
if err := recover(); err != nil {
t.Errorf("Unexpected panic trying to start API master: %#v", err)
}
}()
if err := kubeAPIServer.PrepareRun().Run(wait.NeverStop); err != nil {
t.Fatal(err)
}
}()
lastHealth := ""
if err := wait.PollImmediate(time.Second, time.Minute, func() (done bool, err error) {
// wait for the server to be healthy
result := clientset.NewForConfigOrDie(kubeClientConfig).RESTClient().Get().AbsPath("/healthz").Do()
content, _ := result.Raw()
lastHealth = string(content)
if errResult := result.Error(); errResult != nil {
t.Log(errResult)
return false, nil
}
var status int
result.StatusCode(&status)
return status == http.StatusOK, nil
}); err != nil {
t.Log(lastHealth)
t.Fatal(err)
}
// this test makes lots of requests, don't be slow
kubeClientConfig.QPS = 99999
kubeClientConfig.Burst = 9999
kvClient, err := integration.GetEtcdKVClient(kubeAPIServerOptions.Etcd.StorageConfig)
if err != nil {
t.Fatal(err)
}
return kubeClientConfig, kvClient
}
func dumpEtcdKVOnFailure(t *testing.T, kvClient clientv3.KV) {
if t.Failed() {
response, err := kvClient.Get(context.Background(), "/", clientv3.WithPrefix())
if err != nil {
t.Fatal(err)
}
for _, kv := range response.Kvs {
t.Error(string(kv.Key), "->", string(kv.Value))
}
}
}
func addGVKToEtcdBucket(cohabitatingResources map[string]map[schema.GroupVersionKind]empty, gvk schema.GroupVersionKind, bucket string) {
if cohabitatingResources[bucket] == nil {
cohabitatingResources[bucket] = map[schema.GroupVersionKind]empty{}
}
cohabitatingResources[bucket][gvk] = empty{}
}
// getEtcdBucket assumes the last segment of the given etcd path is the name of the object.
// Thus it strips that segment to extract the object's storage "bucket" in etcd. We expect
// all objects that share the a bucket (cohabitating resources) to be stored as the same GVK.
func getEtcdBucket(path string) string {
idx := strings.LastIndex(path, "/")
if idx == -1 {
panic("path with no slashes " + path)
}
bucket := path[:idx]
if len(bucket) == 0 {
panic("invalid bucket for path " + path)
}
return bucket
}
// stable fields to compare as a sanity check
type metaObject struct {
// all of type meta
Kind string `json:"kind,omitempty"`
APIVersion string `json:"apiVersion,omitempty"`
// parts of object meta
Metadata struct {
Name string `json:"name,omitempty"`
Namespace string `json:"namespace,omitempty"`
} `json:"metadata,omitempty"`
}
func (obj *metaObject) getGVK() schema.GroupVersionKind {
return schema.FromAPIVersionAndKind(obj.APIVersion, obj.Kind)
}
func (obj *metaObject) isEmpty() bool {
return obj == nil || *obj == metaObject{} // compare to zero value since all fields are strings
}
type prerequisite struct {
gvrData schema.GroupVersionResource
stub string
}
type empty struct{}
type cleanupData struct {
obj *unstructured.Unstructured
resource schema.GroupVersionResource
}
func gvr(g, v, r string) schema.GroupVersionResource {
return schema.GroupVersionResource{Group: g, Version: v, Resource: r}
}
func gvkP(g, v, k string) *schema.GroupVersionKind {
return &schema.GroupVersionKind{Group: g, Version: v, Kind: k}
}
func jsonToMetaObject(stub []byte) (*metaObject, error) {
obj := &metaObject{}
if err := json.Unmarshal(stub, obj); err != nil {
return nil, err
}
return obj, nil
}
func keyStringer(i interface{}) string {
base := "\n\t"
switch key := i.(type) {
case string:
return base + key
case schema.GroupVersionResource:
return base + key.String()
case schema.GroupVersionKind:
return base + key.String()
default:
panic("unexpected type")
}
}
type allClient struct {
dynamicClient dynamic.Interface
}
func (c *allClient) create(stub, ns string, mapping *meta.RESTMapping, all *[]cleanupData) error {
// we don't require GVK on the data we provide, so we fill it in here. We could, but that seems extraneous.
typeMetaAdder := map[string]interface{}{}
err := json.Unmarshal([]byte(stub), &typeMetaAdder)
if err != nil {
return err
}
typeMetaAdder["apiVersion"] = mapping.GroupVersionKind.GroupVersion().String()
typeMetaAdder["kind"] = mapping.GroupVersionKind.Kind
if mapping.Scope == meta.RESTScopeRoot {
ns = ""
}
obj := &unstructured.Unstructured{Object: typeMetaAdder}
actual, err := c.dynamicClient.Resource(mapping.Resource).Namespace(ns).Create(obj, metav1.CreateOptions{})
if err != nil {
return err
}
*all = append(*all, cleanupData{actual, mapping.Resource})
return nil
}
func (c *allClient) cleanup(all *[]cleanupData) error {
for i := len(*all) - 1; i >= 0; i-- { // delete in reverse order in case creation order mattered
obj := (*all)[i].obj
gvr := (*all)[i].resource
if err := c.dynamicClient.Resource(gvr).Namespace(obj.GetNamespace()).Delete(obj.GetName(), nil); err != nil {
return err
}
}
return nil
}
func (c *allClient) createPrerequisites(mapper meta.RESTMapper, ns string, prerequisites []prerequisite, all *[]cleanupData) error {
for _, prerequisite := range prerequisites {
gvk, err := mapper.KindFor(prerequisite.gvrData)
if err != nil {
return err
}
mapping, err := mapper.RESTMapping(gvk.GroupKind(), gvk.Version)
if err != nil {
return err
}
if err := c.create(prerequisite.stub, ns, mapping, all); err != nil {
return err
}
}
return nil
}
func getFromEtcd(keys clientv3.KV, path string) (*metaObject, error) {
response, err := keys.Get(context.Background(), path)
if err != nil {
return nil, err
}
if response.More || response.Count != 1 || len(response.Kvs) != 1 {
return nil, fmt.Errorf("Invalid etcd response (not found == %v): %#v", response.Count == 0, response)
}
return jsonToMetaObject(response.Kvs[0].Value)
}
func diffMaps(a, b interface{}) ([]string, []string) {
inA := diffMapKeys(a, b, keyStringer)
inB := diffMapKeys(b, a, keyStringer)
return inA, inB
}
func diffMapKeys(a, b interface{}, stringer func(interface{}) string) []string {
av := reflect.ValueOf(a)
bv := reflect.ValueOf(b)
ret := []string{}
for _, ka := range av.MapKeys() {
kat := ka.Interface()
found := false
for _, kb := range bv.MapKeys() {
kbt := kb.Interface()
if kat == kbt {
found = true
break
}
}
if !found {
ret = append(ret, stringer(kat))
}
}
return ret
}
type resourceToPersist struct {
gvk schema.GroupVersionKind
gvr schema.GroupVersionResource
golangType reflect.Type
namespaced bool
}
func getResourcesToPersist(serverResources []*metav1.APIResourceList, isOAPI bool, t *testing.T) []resourceToPersist {
resourcesToPersist := []resourceToPersist{}
for _, discoveryGroup := range serverResources {
for _, discoveryResource := range discoveryGroup.APIResources {
// this is a subresource, skip it
if strings.Contains(discoveryResource.Name, "/") {
continue
}
hasCreate := false
hasGet := false
for _, verb := range discoveryResource.Verbs {
if string(verb) == "get" {
hasGet = true
}
if string(verb) == "create" {
hasCreate = true
}
}
if !(hasCreate && hasGet) {
continue
}
resourceGV, err := schema.ParseGroupVersion(discoveryGroup.GroupVersion)
if err != nil {
t.Fatal(err)
}
gvk := resourceGV.WithKind(discoveryResource.Kind)
if len(discoveryResource.Group) > 0 || len(discoveryResource.Version) > 0 {
gvk = schema.GroupVersionKind{
Group: discoveryResource.Group,
Version: discoveryResource.Version,
Kind: discoveryResource.Kind,
}
}
gvr := resourceGV.WithResource(discoveryResource.Name)
resourcesToPersist = append(resourcesToPersist, resourceToPersist{
gvk: gvk,
gvr: gvr,
namespaced: discoveryResource.Namespaced,
})
}
}
return resourcesToPersist
}
<file_sep>/cmd/kubeadm/app/apis/kubeadm/fuzzer/fuzzer_test.go
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fuzzer
// TODO: Fuzzing rouudtrip tests are currently disabled in the v1.12 cycle due to the
// v1alpha2 -> v1alpha3 migration. As the ComponentConfigs were embedded in the structs
// earlier now have moved out it's not possible to do a lossless roundtrip "the normal way"
// When we support v1alpha3 and higher only, we can reenable this
import (
"testing"
"k8s.io/apimachinery/pkg/api/apitesting/roundtrip"
"k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/scheme"
)
func TestRoundTripTypes(t *testing.T) {
roundtrip.RoundTripTestForAPIGroup(t, scheme.AddToScheme, Funcs)
}
| 3802801d828aaa46c69538554ad2da8e5dce91ce | [
"Go"
] | 5 | Go | hzxuzhonghu/kubernetes | a4589f1cbe7de9644934886ef40a4dac3cbaca91 | 6be37da354e2e6747da9c2a860e2832a71dc899e |
refs/heads/master | <repo_name>ChoMk/pick_photo_and_send_or_load_img<file_sep>/ImageLoad/app/src/main/java/com/mksoft/imageload/APIRepo.java
package com.mksoft.imageload;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.service.autofill.UserData;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executor;
import javax.inject.Inject;
import javax.inject.Singleton;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
@Singleton
public class APIRepo {
private static int FRESH_TIMEOUT_IN_MINUTES = 8;
private final APIService webservice;
@Inject
public APIRepo(APIService webservice) {
Log.d("testResultRepo", "make it!!!");
this.webservice = webservice;
}
public void sendFile(MultipartBody.Part fbody){
Call<String> call = webservice.sendFile(fbody);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.isSuccessful()){
Log.d("test0602", response.body());
}
Log.d("test0602","fail 응답");
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Log.d("test0602",t.toString());
}
});
}
}
<file_sep>/ImageLoad/app/src/main/java/com/mksoft/imageload/MainActivity.java
package com.mksoft.imageload;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gun0912.tedpermission.PermissionListener;
import com.gun0912.tedpermission.TedPermission;
import java.io.File;
import java.util.ArrayList;
import javax.inject.Inject;
import dagger.android.AndroidInjection;
import dagger.android.DispatchingAndroidInjector;
import dagger.android.support.HasSupportFragmentInjector;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
public class MainActivity extends AppCompatActivity implements HasSupportFragmentInjector {
Button select_img_button;
Button send_img_to_server;
Button load_img_from_server;
ImageView from_server_img;
ImageView selected_img;
private Boolean isPermission = true;
private static final int PICK_FROM_ALBUM = 1;
Uri photoUri;
File tempFile;
@Inject
DispatchingAndroidInjector<Fragment> dispatchingAndroidInjector;
@Inject
APIRepo apiRepo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.configureDagger();
init();
}
@Override
public DispatchingAndroidInjector<Fragment> supportFragmentInjector() {
return dispatchingAndroidInjector;
}
private void configureDagger(){
AndroidInjection.inject(this);
}
private void init(){
tedPermission();
select_img_button = findViewById(R.id.select_img_button);
send_img_to_server = findViewById(R.id.send_img_to_server);
load_img_from_server = findViewById(R.id.load_img_from_server);
select_img_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(isPermission){
goToAlbum();
}else{
Toast.makeText(getApplicationContext(), "권한을 먼저 승인해 주세여.", Toast.LENGTH_LONG).show();
}
}
});
send_img_to_server.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("test0605", photoUri.toString());
//apiRepo.sendFile(MultipartBody.Part.createFormData("file", photoUri.encode("test.png")));
apiRepo.sendFile(MultipartBody.Part.createFormData("file", tempFile.getPath(), RequestBody.create(MediaType.parse("image/*"), tempFile)));
//apiRepo.sendFile(RequestBody.create(MediaType.parse("image/*"), tempFile));
}
});
from_server_img = findViewById(R.id.from_server_img);
selected_img = findViewById(R.id.selected_img);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
Toast.makeText(this, "취소 되었습니다.", Toast.LENGTH_SHORT).show();
if(tempFile != null) {
if (tempFile.exists()) {
if (tempFile.delete()) {
tempFile = null;
}
}
}
return;
}
if (requestCode == PICK_FROM_ALBUM) {
if(data == null)
return;
photoUri = data.getData();
Glide.with(this).load(photoUri).into(selected_img);
Cursor cursor = null;
try {
/*
* Uri 스키마를
* content:/// 에서 file:/// 로 변경한다.
*/
String[] proj = { MediaStore.Images.Media.DATA };
assert photoUri != null;
cursor = getContentResolver().query(photoUri, proj, null, null, null);
assert cursor != null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
tempFile = new File(cursor.getString(column_index));
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}
private void goToAlbum() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(MediaStore.Images.Media.CONTENT_TYPE);
startActivityForResult(intent, PICK_FROM_ALBUM);
}
private void tedPermission() {
PermissionListener permissionListener = new PermissionListener() {
@Override
public void onPermissionGranted() {
// 권한 요청 성공
isPermission = true;
}
@Override
public void onPermissionDenied(ArrayList<String> deniedPermissions) {
// 권한 요청 실패
isPermission = false;
}
};
TedPermission.with(this)
.setPermissionListener(permissionListener)
.setRationaleMessage("카메라 권한, 쓰기 권한 필요해요.")
.setDeniedMessage("권한 거부하셨습니다. 설정에가서 변경해주세요.")
.setPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
.check();
}
}
<file_sep>/ImageLoad/app/src/main/java/com/mksoft/imageload/AppModule.java
package com.mksoft.imageload;
import android.app.Application;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
@Module
public class AppModule {
// --- NETWORK INJECTION ---
private static String BASE_URL = "http://192.168.127.12:8888";
@Provides
Gson provideGson() { return new GsonBuilder().create(); }
@Provides
Retrofit provideRetrofit(Gson gson) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(BASE_URL)
.build();
return retrofit;
}
@Provides
@Singleton
APIService provideApiWebservice(Retrofit restAdapter) {
return restAdapter.create(APIService.class);
}
// --- REPOSITORY INJECTION ---
@Provides
Executor provideExecutor() {
return Executors.newSingleThreadExecutor();
}
@Provides
@Singleton
APIRepo provideAPIRepository(APIService webservice) {
return new APIRepo(webservice);
}
}
| ea5e09a7e9c85097a8402eea933068b079ba01f1 | [
"Java"
] | 3 | Java | ChoMk/pick_photo_and_send_or_load_img | bb75907ef2262bcf2bf761ba386edcba21556e35 | a50cd43ad3a95adaa990ec178ff58212f9adf0e8 |
refs/heads/master | <repo_name>bibsdb/bibsdb_frontend<file_sep>/bibsdb_frontend.features.inc
<?php
/**
* @file
* bibsdb_frontend.features.inc
*/
/**
* Implements hook_menu_default_menu_custom_alter().
*/
function bibsdb_frontend_menu_default_menu_custom_alter(&$data) {
if (isset($data['menu-footer-menu-1'])) {
$data['menu-footer-menu-1']['title'] = 'Inspiration'; /* WAS: 'Footer menu 1' */
}
if (isset($data['menu-footer-menu-2'])) {
$data['menu-footer-menu-2']['title'] = 'Tilbud'; /* WAS: 'Footer menu 2' */
}
if (isset($data['menu-footer-menu-3'])) {
$data['menu-footer-menu-3']['title'] = 'Sådan gør du'; /* WAS: 'Footer menu 3' */
}
if (isset($data['menu-footer-menu-4'])) {
$data['menu-footer-menu-4']['title'] = 'Information'; /* WAS: 'Footer menu 4' */
}
}
/**
* Implements hook_views_default_views_alter().
*/
function bibsdb_frontend_views_default_views_alter(&$data) {
if (isset($data['ding_node_search'])) {
$data['ding_node_search']->display['default']->display_options['filters']['type']['value']['read_circuit_set'] = 'read_circuit_set'; /* WAS: '' */
}
}
<file_sep>/bibsdb_frontend.features.features_overrides.inc
<?php
/**
* @file
* bibsdb_frontend.features.features_overrides.inc
*/
/**
* Implements hook_features_override_default_overrides().
*/
function bibsdb_frontend_features_override_default_overrides() {
// This code is only used for UI in features. Exported alters hooks do the magic.
$overrides = array();
// Exported overrides for: menu_custom
$overrides["menu_custom.menu-footer-menu-1.title"] = 'Inspiration';
$overrides["menu_custom.menu-footer-menu-2.title"] = 'Tilbud';
$overrides["menu_custom.menu-footer-menu-3.title"] = 'Sådan gør du';
$overrides["menu_custom.menu-footer-menu-4.title"] = 'Information';
// Exported overrides for: views_view
$overrides["views_view.ding_node_search.display|default|display_options|filters|type|value|read_circuit_set"] = 'read_circuit_set';
return $overrides;
}
| 99fcb1477c48a1098e55fe02fc786b07008e3c84 | [
"PHP"
] | 2 | PHP | bibsdb/bibsdb_frontend | 046689102a440dfbefd59a780532cbd1d8a6af9e | b2f1256a2a94c209d732c639c8b4e69511c602aa |
refs/heads/master | <file_sep>/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow strict-local
*/
import React, {useState} from 'react';
import type {Node} from 'react';
import {
Linking,
SafeAreaView,
ScrollView,
StatusBar,
StyleSheet,
Text,
useColorScheme,
View,
TouchableOpacity,
} from 'react-native';
const url1 = 'https://github.com/jaferi512';
const number = '+92 3046282189';
const App: () => Node = () => {
const [message, setmessage] = useState('welcome');
const opeurl = async url => {
const isSupported = await Linking.canOpenURL(url);
if (isSupported) {
await Linking.openURL(url);
} else {
alert("Don't know abuot this");
}
};
return (
<SafeAreaView
style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Text>ok</Text>
<TouchableOpacity
onPress={() => opeurl(url1)}
style={{padding: 7, backgroundColor: 'lightgreen', margin: 4}}>
<Text>Github</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => Linking.openURL(`tel:${number}`)}
style={{padding: 7, backgroundColor: 'lightgreen', margin: 4}}>
<Text>Call</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => Linking.openURL(`sms:number=${number}?body=${message}`)}
style={{padding: 7, backgroundColor: 'lightgreen', margin: 4}}>
<Text>SMS</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() =>
Linking.openURL(
`mailto:<EMAIL>?subject=testing&body=${message}`,
)
}
style={{padding: 7, backgroundColor: 'lightgreen', margin: 4}}>
<Text>Mail</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => Linking.openSettings()}
style={{padding: 7, backgroundColor: 'lightgreen', margin: 4}}>
<Text>Setting</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() =>
Linking.openURL(`whatsapp://send?phone=${number}&text=${message}`)
}
style={{padding: 7, backgroundColor: 'lightgreen', margin: 4}}>
<Text>whatsapp</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => Linking.openURL('https://www.google.com/maps')}
style={{padding: 7, backgroundColor: 'lightgreen', margin: 4}}>
<Text>Maps</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => Linking.openURL('https://www.youtube.com/')}
style={{padding: 7, backgroundColor: 'lightgreen', margin: 4}}>
<Text>Youtube</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => Linking.openURL('fb://facewebmodal/f')}
style={{padding: 7, backgroundColor: 'lightgreen', margin: 4}}>
<Text>Facebook</Text>
</TouchableOpacity>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
sectionContainer: {
marginTop: 32,
paddingHorizontal: 24,
},
sectionTitle: {
fontSize: 24,
fontWeight: '600',
},
sectionDescription: {
marginTop: 8,
fontSize: 18,
fontWeight: '400',
},
highlight: {
fontWeight: '700',
},
});
export default App;
| 432d681fa08825cff18ec803b80b6357ddf3f1de | [
"JavaScript"
] | 1 | JavaScript | jaferi512/RNDeepLink | a1697b05d705ca2acc4c6dabe8cfc869421a000c | c08f5d16d3f95a51dc0e4bc500d9574971e1ce64 |
refs/heads/master | <repo_name>danielsaad/Sistemas-Operacionais-IFG-TADS<file_sep>/pipe-2.c
/**
Autor: Beej http://beej.us/guide/bgipc/output/html/singlepage/bgipc.html
Adaptado por: <NAME>
Descrição: uso de pipes utilizando stdin e stdout.
**/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char** argv){
int pfds[2];
int pid;
pipe(pfds);
pid = fork();
if(pid == -1){
perror("Fork error: ");
exit(EXIT_FAILURE);
}
else if (pid == 0) {
close(1); /** Fecha o stdout padrão **/
dup(pfds[1]); /** redireciona stdout para pdfs[1]**/
close(pfds[0]); /** fecha pfds[0] **/
execlp("ls", "ls", NULL);
}
else{
close(0);
dup(pfds[0]); /** redireciona stdin para pdfs[1]**/
close(pfds[1]); /** fecha pfds[1] **/
execlp("wc", "wc", "-l", NULL);
}
return 0;
}
<file_sep>/signal-2.c
/**
Autor: <NAME>
Descrição: Um processo que captura o sinal SIGALRM periodicamente.
**/
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
void sigalrm_handler(int sig){
const char* msg = "Trim trim trim trim!\n";
write(0,msg,strlen(msg));
alarm(2);
}
int main(int argc, char** argv){
struct sigaction sa;
sa.sa_handler = sigalrm_handler;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
if(sigaction(SIGALRM,&sa,NULL)==-1){
perror("Sigaction: ");
exit(EXIT_FAILURE);
}
alarm(2);
for(;;);
return(0);
}
<file_sep>/signal-5.c
/**
Autor: <NAME>
Descrição: Demonstração do envio de um sinal (SIGKILL) de um processo
para outro e a sua impossibilidade de captura.
**/
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
void sigkill_handler(int sig){
const char* str = "Filho: Tu não manda em mim, rapá!\n";
write(0,str,strlen(str));
}
int main(int argc, char** argv){
int pid;
struct sigaction sa;
pid = fork();
if(pid == -1){
perror("Fork error:");
exit(EXIT_FAILURE);
}
else if(pid==0){ /** Código do Filho **/
sa.sa_handler = sigkill_handler;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
if(sigaction(SIGKILL,&sa,NULL)==-1){
perror("Impossível capturar SIGKILL");
}
for(;;){
printf("Filho: Omelette du fromage }:-D.\n");
sleep(1);
}
}
else{ /** Código do Pai **/
printf("Pai: Vou dormir. ZzZZzzzZzZzZZZ\n");
sleep(10);
printf("Pai: Acordei!\n");
printf("Pai: Que zoeira é essa!\n");
printf("Pai: Cala a boca!\n");
kill(pid,SIGKILL);
sleep(1);
printf("Quem manda nessa p**** aqui, sou eu!\n");
}
return(0);
}
<file_sep>/threads-criacao-1.c
/**
Autor: https://computing.llnl.gov/tutorials/pthreads/
**/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
volatile int x=1; /** Variáveis globais são compartilhadas pelas threads.**/
void* imprime_x(void* arg){
int id = (int) arg;
printf("Sou a thread %d\n",id);
for(;;){
printf("x");
}
pthread_exit(NULL);
}
int main (int argc, char *argv[]){
pthread_t thread;
pthread_attr_t attr;
int id = 0;
int rv;
/* For portability, explicitly create threads in a joinable state */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&thread, &attr, imprime_x, (void *) id);
/* Wait for all threads to complete */
pthread_join(thread, (void*) &rv);
/* Clean up and exit */
pthread_attr_destroy(&attr);
pthread_exit(NULL);
}
<file_sep>/fork-4.c
/**
Autor: <NAME>
Descrição: Demonstração de criação de múltiplos processos usando fork();
**/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
int main(int argc, char** argv){
int rv;
int i;
int id = 0;
int pid=1;
const int NUMERO_DE_PROCESSOS = 10;
int pid_filhos[NUMERO_DE_PROCESSOS];
for(i=0;i<NUMERO_DE_PROCESSOS;i++){
if(pid>0){
pid = fork();
if(pid ==-1){
perror("Fork error: ");
exit(EXIT_FAILURE);
}
else if(pid > 0){
pid_filhos[i] = pid;
}
else{
id = i+1;
}
}
}
printf("Sou o processo de identificador %d e pid %d.\n",id,getpid());
sleep(10); /** Olhe a tabela de processos **/
if(id==0){ /** Processo Pai **/
for(i=0;i<NUMERO_DE_PROCESSOS;i++){
waitpid(pid_filhos[i],&rv,0);
printf("Filhão de pid %d encerrou com código %d.\n",
pid_filhos[i],rv);
}
}
return(0);
}
<file_sep>/pipe-1.c
/**
Autor: Beej http://beej.us/guide/bgipc/output/html/singlepage/bgipc.html
Adaptado por: <NAME>
Descrição: uso de pipes.
**/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char** argv){
int pfds[2]; /** Descritor de pipes **/
char buf[30];
int pid;
pipe(pfds);
pid = fork();
if(pid == -1){
perror("Fork error: ");
exit(EXIT_FAILURE);
}
else if (pid == 0) {
printf("Filho: Escrevendo no pipe.\n");
write(pfds[1], "teste", 6);
printf("Filho: saindo.\n");
exit(0);
}
else{
printf("Pai: lendo do pipe.\n");
read(pfds[0], buf, 6);
printf("Pai: li %s \n", buf);
wait(NULL);
}
return 0;
}
<file_sep>/signal-1.c
/**
Autor: <NAME>
Descrição: Demonstração da captação do sinal SIGINT e a sobrescrita do
comportamento padrão deste sinal.
**/
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
void sigint_handler(int sig){
const char* msg = "Capturei sua interrupção }:-)\n";
write(0,msg,strlen(msg));
}
int main(int argc, char** argv){
struct sigaction sa;
sa.sa_handler = sigint_handler;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
if(sigaction(SIGINT,&sa,NULL)==-1){
perror("Sigaction: ");
exit(EXIT_FAILURE);
}
for(;;);
return(0);
}
<file_sep>/produto-escalar-pthreads.c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/time.h>
#define N (500000)
#define N_THREADS (4)
#define MAX (3)
double time_diff(struct timeval x , struct timeval y)
{
double x_ms , y_ms , diff;
x_ms = (double)x.tv_sec*1000000 + (double)x.tv_usec;
y_ms = (double)y.tv_sec*1000000 + (double)y.tv_usec;
diff = (double)y_ms - (double)x_ms;
return diff;
}
pthread_mutex_t prod_mutex;
int prod = 0;
typedef struct thread_arg{
int* A;
int* B;
int size;
int id;
}thread_arg;
void* prod_escalar(void* arg){
int i;
int begin;
int end;
int local_prod=0;
int block_size = N/N_THREADS;
thread_arg* t_arg = (thread_arg*) arg;
begin = t_arg->id * block_size;
end = t_arg->id == (N_THREADS -1) ? t_arg->size : begin+block_size;
for(i=begin; i<end ;i++){
local_prod += t_arg->A[i] * t_arg->B[i];
}
printf("Thread %d -> Produto local: %d\n",t_arg->id,local_prod);
pthread_mutex_lock(&prod_mutex);
prod+=local_prod;
pthread_mutex_unlock(&prod_mutex);
pthread_exit(NULL);
}
int main(void){
int i;
int A[N],B[N];
pthread_t threads[N_THREADS];
int rv;
thread_arg t_arg[N_THREADS];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
struct timeval before,after;
srand(time(NULL));
for(i=0;i<N;i++){
A[i] = rand()% MAX;
B[i] = rand()% MAX;
}
#ifdef DEBUG
for(i=0;i<N;i++){
printf("%d ",A[i]);
}
printf("\n");
for(i=0;i<N;i++){
printf("%d ",B[i]);
}
printf("\n");
#endif
gettimeofday(&before,NULL);
for(i=0;i<N_THREADS;i++){
t_arg[i].id = i;
t_arg[i].A = A;
t_arg[i].B = B;
t_arg[i].size = N;
pthread_create(&threads[i], &attr, prod_escalar, (void*) &t_arg[i]);
}
for(i=0;i<N_THREADS;i++){
pthread_join(threads[i],(void*) &rv);
}
gettimeofday(&after,NULL);
printf("O cálculo levou %lf microsegundos: ",time_diff(before,after));
printf("O produto escalar é: %d\n",prod);
pthread_exit(NULL);
}
<file_sep>/mensagem-spock.c
/**
Autor: Beej http://beej.us/guide/bgipc/output/html/singlepage/bgipc.html
Adaptado por: <NAME>
Descrição: Descrição: Demonstração da utilização de troca de mensagens
entre os processos kirk e spock.
Spock: Obtém mensagens da fila.
**/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct my_msgbuf {
long mtype;
char mtext[200];
};
int main(void)
{
struct my_msgbuf buf;
int msqid;
key_t key;
if ((key = ftok("mensagem-kirk.c", 'B')) == -1) { /* same key as kirk.c */
perror("ftok");
exit(1);
}
/** Não colocamos IPC_CREAT aqui, pois deixamos Kirk lidar com isso,
* se a fila não tiver sido criada, obteremos um erro
**/
if ((msqid = msgget(key, 0644)) == -1) { /** Conecta até a fila **/
perror("msgget");
exit(1);
}
printf("Spock: pronto para receber mensagens, capitão.\n");
/** ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int
msgflg);
Como o campo está 0, não importao valor de msgtype setado em kirk.
Quando é 0, a primeira mensagem é lida.
**/
for(;;) { /** Spock nunca para de ouvir**/
if (msgrcv(msqid, &buf, sizeof(buf.mtext), 0, 0) == -1) {
perror("msgrcv");
exit(1);
}
printf("spock: \"%s\"\n", buf.mtext);
}
return 0;
}
<file_sep>/fork-5.c
/**
Autor: <NAME>
Descrição: Demonstração do fork() seguido de execv()
**/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
int main(int argc, char** argv){
int id = 0;
int rv;
int pid = fork();
char* args[] = {"ls", "-la", "."};
if(pid == -1){
perror("Fork error:");
exit(EXIT_FAILURE);
}
else if(pid==0){ /** Código do Filho **/
execv("/bin/ls", args); /** Carrega o processo ls com argumentos -la **/
}
else{ /** Código do Pai **/
printf("Sou o processo PAI!\n");
printf("Meu pid é %d!\n",getpid());
printf("Meu id é %d!\n",id);
wait(&rv); /** Espera o filho **/
printf("Meu filhão de pid %d já terminou com código %d.\n",pid,rv);
}
return(0);
}
<file_sep>/README.md
Sistemas Operacionais
======================
Introdução
-----------
Neste repositório temos vários exemplos de programas que utilizam primitivas de comunicação interprocesso para realizar uma tarefa.
A utilização de threads também é abordada.
Compilação
----------
Os programas podem ser compilados facilmente utilizando o gcc
```
gcc <fonte.c> -o <nome do executável>
```
Os programas que utilizam a API Pthreads, necessitam de uma flag especial de ligação:
```
gcc <fonte.c> -o <nome do executável> -lpthread
```
<file_sep>/memoria-1.c
/**
Autor: Beej http://beej.us/guide/bgipc/output/html/singlepage/bgipc.html
Adaptado por: <NAME>
Descrição: Descrição: Demonstração da utilização de memória compartilhada
por dois processos.
Experimente rodar duas ou mais instâncias do processo,
leitores e escritores. Note que pode haver condição de corrida.
**/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_SIZE 1024 /* make it a 1K shared memory segment */
int main(int argc, char *argv[])
{
key_t key;
int shmid;
char *data;
if (argc > 2) {
fprintf(stderr, "uso (escrita): ./shmdemo <dados a serem escritos>\n");
fprintf(stderr, "uso(leitura): ./shmdemo \n");
exit(1);
}
/** gere a chave: (tem que ser a mesma entre os dois processos) **/
if ((key = ftok("memoria-1.c", 'R')) == -1) {
perror("ftok: ");
exit(1);
}
/** Conectar-se e possivelmente criar o segmento **/
if ((shmid = shmget(key, SHM_SIZE, 0644 | IPC_CREAT)) == -1) {
perror("shmget: ");
exit(1);
}
/** se acoplar ao segmente e obter um ponteiro para ele: **/
data = shmat(shmid, (void *)0, 0);
if (data == (char *)(-1)) {
perror("shmat: ");
exit(1);
}
/** ler ou modificar o segmento, de acordo com a linha de comando: */
if (argc == 2) {
printf("escrevendo no segmento: \"%s\"\n", argv[1]);
strncpy(data, argv[1], SHM_SIZE);
}
else{
while(1){
sleep(5);
printf("segmento contém: \"%s\"\n", data);
}
}
/** Desacoplar segmento do processo: **/
if (shmdt(data) == -1) {
perror("shmdt");
exit(1);
}
return (0);
}
/**
* Para remover um segmento de memória.
* shmctl(shmid, IPC_RMID, NULL);
* OBS: Só é removido depois que todos os processos que o usam
* dão dettach.
**/
<file_sep>/signal-3.c
/**
Autor: <NAME>
Descrição: Demonstração do envio de um sinal (SIGTERM) de um processo
para outro.
**/
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
int main(int argc, char** argv){
int pid = fork();
if(pid == -1){
perror("Fork error:");
exit(EXIT_FAILURE);
}
else if(pid==0){ /** Código do Filho **/
for(;;){
printf("Filho: Omelette du fromage }:-D.\n");
sleep(1);
}
}
else{ /** Código do Pai **/
printf("Pai: Vou dormir. ZzZZzzzZzZzZZZ\n");
sleep(10);
printf("Pai: Acordei!\n");
printf("Pai: Que zoeira é essa!\n");
printf("Pai: Cala a boca!\n");
kill(pid,SIGTERM);
}
return(0);
}
<file_sep>/fork-2.c
/**
Autor: <NAME>
Descrição: Demonstração de criação de processos usando fork();
Neste caso, o filho fica como zumbi (defunct), pois está esperando o wait
do pai.
**/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
int main(int argc, char** argv){
int id = 0;
int rv;
int pid = fork();
if(pid == -1){
perror("Fork error:");
exit(EXIT_FAILURE);
}
else if(pid==0){ /** Código do Filho **/
id = 1;
printf("Sou o processo FILHO!\n");
printf("Meu pid é %d!\n",getpid());
printf("O pid do meu pai é %d.\n",getppid());
printf("Meu id é %d!\n",id);
}
else{ /** Código do Pai **/
printf("Sou o processo PAI!\n");
printf("Meu pid é %d!\n",getpid());
printf("Meu id é %d!\n",id);
sleep(10); /** Cheque o que houve na tabela de processos **/
wait(&rv);
}
return(0);
}
| ca05843fa27920740d8e6a2dda6015c8cc5883e7 | [
"Markdown",
"C"
] | 14 | C | danielsaad/Sistemas-Operacionais-IFG-TADS | 5688406fcbab3fabf12322b58812f1b35bb73fc6 | d74d2d854b723432b03dfd7790248b4ce39d451f |
refs/heads/master | <repo_name>muraadkov/WorkerService<file_sep>/WorkerFolderService/Worker.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using EmailService;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace WorkerFolderService
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private readonly IEmailSender _sender;
private FileSystemWatcher watcher;
private readonly string path = @"C:/Users/murka/Desktop/folder";
public Worker(ILogger<Worker> logger, IEmailSender sender)
{
_logger = logger;
_sender = sender;
}
public override Task StartAsync(CancellationToken cancellationToken)
{
watcher = new FileSystemWatcher();
watcher.Path = path;
watcher.Created += OnCreate;
watcher.Changed += OnChange;
watcher.Deleted += OnDelete;
watcher.Renamed += OnRename;
return base.StartAsync(cancellationToken);
}
private void OnCreate(object sender, FileSystemEventArgs e)
{
_logger.LogError("Some error");
_logger.LogWarning("Some warning");
_logger.LogInformation("File created at: {time}", DateTimeOffset.Now);
var message = new Message(new string[] { "<EMAIL>" }, "SE1904 subject", $"created file with name {e.Name}", e.FullPath);
_sender.SendEmail(message);
}
private void OnChange(object sender, FileSystemEventArgs e)
{
_logger.LogError("Some error");
_logger.LogWarning("Some warning");
_logger.LogInformation("File changed at: {time}", DateTimeOffset.Now);
var message = new Message(new string[] { "<EMAIL>" }, "SE1904 subject", $"changed file, with name {e.Name}", e.FullPath);
_sender.SendEmail(message);
}
private void OnDelete(object sender, FileSystemEventArgs e)
{
_logger.LogError("Some error");
_logger.LogWarning("Some warning");
_logger.LogInformation("File deleted at: {time}", DateTimeOffset.Now);
var message = new Message(new string[] { "<EMAIL>" }, "SE1904 subject", $"deleted file, with name {e.Name}", e.FullPath);
_sender.SendEmail(message);
}
private void OnRename(object sender, FileSystemEventArgs e)
{
_logger.LogError("Some error");
_logger.LogWarning("Some warning");
_logger.LogInformation("File renamed at: {time}", DateTimeOffset.Now);
var message = new Message(new string[] { "<EMAIL>" }, "SE1904 subject", $"renamed file, with name {e.Name}", e.FullPath);
_sender.SendEmail(message);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
watcher.EnableRaisingEvents = true;
await Task.Delay(1000, stoppingToken);
}
}
}
}
| b040484dd5d6cdc59d87c116e6877eade58f4194 | [
"C#"
] | 1 | C# | muraadkov/WorkerService | 003853b7dedf4063bc2799140f59eaa79ae0b9d9 | 180d6239b21d25956d88c3b35f3eae4b6c2e941d |
refs/heads/master | <file_sep>PROJECT = server
PROJECT_DESCRIPTION = pacman server
PROJECT_VERSION = 0.0.1
DEPS = cowboy jiffy protobuffs ejwt
include erlang.mk
<file_sep>import Phaser from 'phaser'
import Entity from './Entity'
import {Direction, TILE_SIZE, Latency} from '../const'
import {Message, MessageType, Protocols, decode} from '../protocol'
const speed = 6
export default class Player extends Entity {
constructor(opts) {
opts.asset = opts.asset || 'dude'
super(opts)
this.animations.add('left', [0, 1, 2, 3], 10, true)
this.animations.add('right', [5, 6, 7, 8], 10, true)
this.origScale = 1
this.scale.setTo(this.origScale, this.origScale)
this.graph = opts.graph
this.map = opts.map
this.src = opts.src
this.dst = -1
this.now = this.game.time.time
}
update() {
const dt = this.game.time.time - this.now
const delta = speed * dt / 1000
this.now = this.game.time.time
if (this.src >= 0 && this.dst >= 0 && this.offset < this.offsetMax) {
this.offset += delta
const {x, y} = this.map.edge2xy(this.src, this.dst, this.offset)
this.x = (x + 0.5) * TILE_SIZE
this.y = (y + 0.5) * TILE_SIZE
if (this.offset >= this.offsetMax) {
const dst1 = this.graph.lookup(this.dst, this.nextDirection)
const dst2 = this.graph.lookup(this.dst, this.direction)
if (dst1 >= 0) {
this.src = this.dst
this.dst = dst1
this.offset = this.offset - this.offsetMax
this.offsetMax = this.map.edgeDistance(this.src, this.dst)
this.direction = this.nextDirection
this.nextDirection = -1
} else if(dst2 >= 0) {
this.src = this.dst
this.dst = dst2
this.offset = this.offset - this.offsetMax
this.offsetMax = this.map.edgeDistance(this.src, this.dst)
} else {
this.src = this.dst
this.dst = -1
this.direction = -1
this.nextDirection = -1
this.offset = 0
}
}
} else {
const {x, y} = this.map.edge2xy(this.src, this.dst, this.offset)
this.x = (x + 0.5) * TILE_SIZE
this.y = (y + 0.5) * TILE_SIZE
}
}
move(direction) {
if (this.dst == -1) {
const dst = this.graph.lookup(this.src, direction)
if (dst >= 0) {
this.dst = dst
this.offset = 0
this.offsetMax = this.map.edgeDistance(this.src, this.dst)
this.direction = direction
this.nextDirection = -1
this.sendAction(direction)
}
} else if (direction == Direction.opposite(this.direction)) {
const dst = this.src
const src = this.dst
this.src = src
this.dst = dst
this.offset = this.offsetMax - this.offset
this.direction = direction
this.nextDirection = -1
this.sendAction(direction)
} else if (this.direction != direction && this.nextDirection!= direction) {
this.nextDirection = direction
this.sendAction(direction)
}
}
sendAction(direction, next_direction) {
const {ActionReq} = Protocols
const ts = Date.now() & 0xffffffff
const req = new ActionReq({direction, ts})
const message = new Message({type: MessageType.ACTION_REQ, data: req.toArrayBuffer()})
setTimeout(() => this.game.transport.send(message.toArrayBuffer()), Latency.random())
}
}
<file_sep>export default class TileMap {
constructor(data) {
const uint32array = new Uint32Array(data)
this.width = uint32array[0]
this.height = uint32array[1]
this.numNodes = uint32array[2]
this.nodeIdMap = {}
for (let i = 0; i < this.numNodes; i++) {
this.nodeIdMap[uint32array[i + 3]] = i
}
this.directions = new Uint8Array(uint32array.slice(this.numNodes + 3).buffer)
}
isWall(x, y) {
if (x < 0 || x >= this.width || y < 0 || y >= this.height) {
return true
}
const index = y * this.width + x
return this.nodeIdMap[index] == null
}
isRoad(x, y) {
return !this.isWall(x, y)
}
xy2index(x, y) {
return this.width * y + x;
}
index2xy(index) {
const x = index % this.width;
const y = Math.floor(index / this.width);
return {x, y};
}
edge2xy(src, dst, offset) {
const p1 = this.index2xy(src)
const p2 = this.index2xy(dst)
const dx = p2.x - p1.x
const dy = p2.y - p1.y
let {x, y} = p1
if (dx > 0) {
x += offset
} else if (dx < 0) {
x -= offset
} else if (dy > 0) {
y += offset
} else if (dy < 0) {
y -= offset
}
return {x, y}
}
edgeDistance(src, dst) {
const p1 = this.index2xy(src)
const p2 = this.index2xy(dst)
const dx = p2.x - p1.x
const dy = p2.y - p1.y
return Math.abs(dx) + Math.abs(dy)
}
lookup(index1, index2) {
const node1 = this.nodeIdMap[index1]
const node2 = this.nodeIdMap[index2]
if (node1 >= 0 && node2 >= 0) {
return this.directions[node1 * this.numNodes + node2]
}
return false
}
randomPosition() {
const nodeId = Math.floor(this.numNodes * Math.random())
const index = Object.keys(this.nodeIdMap)[nodeId]
return this.index2xy(index)
}
}
<file_sep>import protobuf from 'protobufjs'
import camelcase from 'uppercamelcase'
const builder = protobuf.loadProtoFile('/assets/protocol/messages.proto')
export const MessageType = builder.build('MessageType')
export const Direction = builder.build('Direction')
export const Message = builder.build('Message')
export const Protocols = {}
for (var messageType in MessageType) {
const Protocol = builder.build(camelcase(messageType))
Protocols[MessageType[messageType]] = Protocol
Protocols[camelcase(messageType)] = Protocol
}
export const decode = (data) => {
const msg = Message.decode(data)
const Protocol = Protocols[msg.type]
const subMsg = Protocol.decode(msg.data)
subMsg.type = msg.type
return subMsg
}
<file_sep>import Phaser from 'phaser'
import Player from '../sprites/Player'
import Shadow from '../sprites/Shadow'
import {Direction, TILE_SIZE, Latency} from '../const'
import TileMap from '../map/TileMap'
import Graph from '../map/Graph'
import {Message, MessageType, Protocols, decode} from '../protocol'
export default class extends Phaser.State {
init() {}
preload() {}
create() {
const path = this.cache.getBinary('path')
this.map = new TileMap(path)
const edge = this.cache.getBinary('edge')
this.graph = new Graph(edge)
const border = 0
const graphics = this.add.graphics(0, 0)
// draw roads
graphics.lineStyle(1, 0xafafaf, 1)
graphics.beginFill(0xafafaf, 1)
for (let index in this.map.nodeIdMap) {
const {x, y} = this.map.index2xy(index);
const extra = 5;
graphics.drawRect(x * TILE_SIZE + border - extra, y * TILE_SIZE + border - extra, TILE_SIZE - 2 * border + 2 * extra, TILE_SIZE - 2 * border + 2 * extra)
}
graphics.endFill()
const initEdge = this.graph.randomEdge()
const {x, y} = this.map.index2xy(initEdge.src)
const player = new Player({
game: this.game,
x: (x + 0.5) * TILE_SIZE,
y: (y + 0.5) * TILE_SIZE,
map: this.map,
graph: this.graph,
src: initEdge.src
})
this.game.add.existing(player)
this.player = player
const shadow = new Shadow({
game: this.game,
x: player.x,
y: player.y,
})
this.game.add.existing(shadow)
this.shadow = shadow
// cursors
this.cursors = this.game.input.keyboard.createCursorKeys()
// join room
this.joinRoom()
// regiester protocol
this.game.transport.register('message', this.onMessage.bind(this))
// show fps
this.game.time.advancedTiming = true
const debugInfo = this.add.text(this.world.width - 128, 32, 'debug info', { font: '16px Arial', fill: '#eeeeee', align: 'center' })
debugInfo.anchor.setTo(0.5, 0.5)
this.debugInfo = debugInfo
}
onMessage(evt) {
const message = decode(evt.data)
switch (message.type) {
case MessageType.JOIN_ROOM_RES:
this.player.src = message.entity.src
this.player.dst = message.entity.dst
this.player.offset = message.entity.offset
this.player.id = message.entity.id
this.shadow.src = message.entity.src
this.shadow.dst = message.entity.dst
this.shadow.offset = message.entity.offset
this.shadow.id = message.entity.id
break
case MessageType.UPDATE_NTF:
for (let i = 0, len = message.entities.length; i < len; i++) {
const entity = message.entities[i]
const {x, y} = this.map.edge2xy(entity.src, entity.dst, entity.offset)
if (entity.id == this.player.id) {
setTimeout(() => {
this.shadow.src = entity.src;
this.shadow.dst = entity.dst;
this.shadow.offset = entity.offset;
this.shadow.x = (x + 0.5) * TILE_SIZE
this.shadow.y = (y + 0.5) * TILE_SIZE
//if (Math.abs(this.shadow.x - this.player.x) + Math.abs(this.shadow.y - this.player.y) > 5 * TILE_SIZE) {
if (this.shadow.src != this.player.src) {
this.diffCount++
} else {
this.diffCount = 0
}
if (false && this.diffCount > 5) {
console.log('fix')
this.player.src = entity.src
this.player.dst = entity.dst
this.player.offset = entity.offset
this.player.direction = entity.direction
this.player.nextDirection = entity.next_direction
}
}, Latency.random())
}
}
//console.log(message.entities)
break
default:
}
}
joinRoom() {
const {JoinRoomReq} = Protocols
const req = new JoinRoomReq({room_id: 0})
const message = new Message({type: MessageType.JOIN_ROOM_REQ, data: req.toArrayBuffer()})
this.game.transport.send(message.toArrayBuffer())
}
update() {
this.debugInfo.text = `fps: ${this.game.time.fps}`
}
render() {
const player = this.player
const cursors = this.cursors
if (cursors.left.isDown) {
player.move(Direction.LEFT)
} else if (cursors.right.isDown) {
player.move(Direction.RIGHT)
} else if (cursors.up.isDown) {
player.move(Direction.UP)
} else if (cursors.down.isDown) {
player.move(Direction.DOWN)
}
}
}
<file_sep>import Phaser from 'phaser'
import Entity from './Entity'
const speed = 3
export default class Shadow extends Entity {
constructor(opts) {
opts.asset = opts.asset || 'dude'
super(opts)
this.origScale = 1
this.scale.setTo(this.origScale, this.origScale)
this.alpha = 0.5
}
update() {
}
}
<file_sep>import Phaser from 'phaser'
import WSTransport from '../transport/WSTransport'
import {decode} from '../protocol'
export default class extends Phaser.State {
init () {
this.connected = false
}
preload () {
const transport = new WSTransport()
transport.register('open', this.onOpen.bind(this))
transport.register('close', this.onClose.bind(this))
transport.connect()
this.game.transport = transport
this.load.image('blackhole', 'assets/images/blackhole.png')
this.load.image('diamond', 'assets/images/diamond.png')
this.load.image('hurricane', 'assets/images/hurricane.png')
this.load.image('ice', 'assets/images/ice.png')
this.load.image('star', 'assets/images/star.png')
this.load.spritesheet('dude', 'assets/images/dude.png', 32, 48)
this.load.spritesheet('baddie', 'assets/images/baddie.png', 32, 32)
this.load.binary('path', 'assets/map/64.tmx.path.data')
this.load.binary('edge', 'assets/map/64.tmx.edge.data')
}
render () {
if (this.connected) {
this.state.start('Game')
}
}
onOpen() {
this.connected = true
}
onClose() {
this.connected = false
}
}
<file_sep># A Multiplyer PacMan Game
# TODO
<file_sep>var pomelo = window.pomelo;
var host = "127.0.0.1";
var port = "3011";
var uid = 0;
var game;
var nickname;
var playerEntityId;
var entities = {};
var dots = {};
var updates = [];
var cursors;
var spaceKey;
var players;
var stars;
var score = 0;
var scoreText;
var size = 40;
var latency;
var actionId = 0;
var EntityType = {
ENTITY: 0,
PLAYER: 1,
GHOST: 2,
RUNE: 3,
ICE: 4,
BLACKHOLE: 5,
HURRICANE: 6
};
var ActionType = {
STAY: 0,
LEFT: 1,
RIGHT: 2,
UP: 3,
DOWN: 4,
SPEED_UP: 5
};
var EntityStatus = {
NORMAL: 0x0000,
STRONG: 0x0001,
SLOW: 0x0002,
SHIELD: 0x0004,
checkStatus: function(status1, status2) {
return status1 & status2;
}
};
var serverTime = 0;
var serverTick = 0;
var clientTime = 0;
var clientTick = 0;
var clientInterval = 0;
setInterval(function() {
console.log("latency is " + latency);
}, 2000);
var map = {
init: function(data) {
this.width = data.width;
this.height = data.height;
this.data = data.data;
},
intIsWall: function(x, y) {
var index, tile;
if (x < 0 || x >= this.width || y < 0 || y >= this.height) {
return true;
}
index = y * this.width + x;
tile = this.data[index];
return tile === '|' || tile === '_';
},
isWall: function(x, y) {
var ceil, floor;
if (x === parseInt(x) && y === parseInt(y)) {
return this.intIsWall(x, y);
} else if (x === parseInt(x)) {
floor = Math.floor(y);
ceil = Math.ceil(y);
return this.intIsWall(x, floor) || this.intIsWall(x, ceil);
} else if (y === parseInt(y)) {
floor = Math.floor(x);
ceil = Math.ceil(x);
return this.intIsWall(floor, y) || this.intIsWall(ceil, y);
} else {
return true;
}
},
};
function loadMap(cb) {
$.ajax({url: '/map/64.json'}).done(function(data) {
map.init(data);
cb(null);
});
}
function connect() {
pomelo.init({
host: host,
port: port,
log: true
}, function() {
pomelo.request("connector.entryHandler.entry", {nickname}, function(data) {
console.log(JSON.stringify(data));
uid = data.uid;
serverTime = data.serverTime;
serverTick = data.tick;
for (var i = 0, len = data.entities.length; i < len; i++) {
var entity = data.entities[i];
var entityId = entity.id;
if (entity.uid == uid) {
playerEntityId = entityId;
}
entities[entityId] = createEntity(entity.type, entity.x, entity.y);
entities[entityId].entityId = entityId;
entities[entityId].uid = entity.uid;
}
for (var i = 0, len = data.dots.length; i < len; i++) {
var dot = data.dots[i];
dots[dot.x] = dots[dot.x] || {};
dots[dot.x][dot.y] = createEntity(EntityType.STAR, dot.x, dot.y);
}
});
});
}
function notifyAction(action) {
console.log("action: " + action);
var sendtime = Date.now();
pomelo.request("logic.entryHandler.control", {action, serverTime, actionId: actionId++, tick: serverTick}, function (response) {
var recvtime = Date.now();
latency = recvtime - sendtime;
});
}
function preload() {
game.load.image('sky', 'assets/sky.png');
game.load.image('star', 'assets/star.png');
game.load.image('diamond', 'assets/diamond.png');
game.load.image('ice', 'assets/ice.png');
game.load.image('blackhole', 'assets/blackhole.png');
game.load.image('hurricane', 'assets/hurricane.png');
game.load.spritesheet('dude', 'assets/dude.png', 32, 48);
game.load.spritesheet('baddie', 'assets/baddie.png', 32, 32);
require('boot');
connect();
}
function createEntity(type, x, y) {
if (type == EntityType.PLAYER) {
return createPlayer(x, y);
} else if (type == EntityType.GHOST) {
return createGhost(x, y);
} else if (type == EntityType.RUNE) {
return createRune(x, y);
} else if (type == EntityType.STAR) {
return createStar(x, y);
} else if (type == EntityType.ICE) {
return createIce(x, y);
} else if (type == EntityType.BLACKHOLE) {
return createBlackhole(x, y);
} else if (type == EntityType.HURRICANE) {
return createHurricane(x, y);
}
}
function createPlayer(x, y) {
// The player and its settings
var player = players.create(x * size, y * size, 'dude');
game.physics.arcade.enable(player);
player.animations.add('left', [0, 1, 2, 3], 10, true);
player.animations.add('right', [5, 6, 7, 8], 10, true);
player.origScale = 0.5;
player.scale.setTo(player.origScale, player.origScale);
return player;
}
function createGhost(x, y) {
// The ghost and its settings
var ghost = players.create(x * size, y * size, 'baddie');
ghost.animations.add('left', [0, 1], 10, true);
ghost.animations.add('right', [2, 3], 10, true);
game.physics.arcade.enable(ghost);
ghost.origScale = 0.5;
ghost.scale.setTo(ghost.origScale, ghost.origScale);
return ghost;
}
function createRune(x, y) {
// The ghost and its settings
var rune = players.create(x * size, y * size, 'diamond');
game.physics.arcade.enable(rune);
rune.origScale = 0.5;
rune.scale.setTo(rune.origScale, rune.origScale);
return rune;
}
function createIce(x, y) {
// The ghost and its settings
var ice = players.create(x * size, y * size, 'ice');
game.physics.arcade.enable(ice);
ice.origScale = 0.3;
ice.scale.setTo(ice.origScale, ice.origScale);
return ice;
}
function createBlackhole(x, y) {
// The ghost and its settings
var blackhole = players.create(x * size, y * size, 'blackhole');
game.physics.arcade.enable(blackhole);
blackhole.origScale = 0.2;
blackhole.scale.setTo(blackhole.origScale, blackhole.origScale);
return blackhole;
}
function createHurricane(x, y) {
// The ghost and its settings
var hurricane = players.create(x * size, y * size, 'hurricane');
game.physics.arcade.enable(hurricane);
hurricane.origScale = 0.2;
hurricane.scale.setTo(hurricane.origScale, hurricane.origScale);
return hurricane;
}
function createStar(x, y) {
var star = stars.create((x + 0.25) * size, (y + 0.25) * size, 'star');
star.origScale = 0.5;
star.scale.setTo(star.origScale, star.origScale);
return star;
}
function createWalls() {
var graphics = game.add.graphics(0, 0);
graphics.lineStyle(1, 0xffd900, 1);
graphics.beginFill(0xFFFF0B, 1);
for (var x = 0; x < map.width; x++) {
for (var y = 0; y < map.height; y++) {
if (map.isWall(x, y)) {
graphics.drawRect(x * size + 2, y * size + 2, size - 4, size - 4);
game.add.text(x * size + 5, y * size + 10, x + ',' + y, { fontSize: '10px', fill: 'red' });
}
}
}
graphics.endFill();
}
function create() {
game.physics.startSystem(Phaser.Physics.ARCADE);
createWalls();
stars = game.add.group();
stars.enableBody = true;
players = game.add.group();
scoreText = game.add.text(22 * size, 2 * size, 'LEADERBOARD', { fontSize: '15px', fill: 'red' });
cursors = game.input.keyboard.createCursorKeys();
spaceKey = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
pomelo.on('update', function (positions) {
updates.push(positions);
});
pomelo.on('kill', function(msg) {
if (msg.to == playerEntityId) {
alert('you are killed by ' + msg.from);
}
});
pomelo.on('scores', function (scores) {
//console.log(JSON.stringify(scores));
if (scores.scores) renderScores(scores.scores);
});
}
function update() {
clientTick++;
var now = Date.now();
clientInterval = now - clientTime;
clientTime = now;
//for (var i = 0, len = players.children.length; i < len; i++) {
// var player = players.children[i];
// game.physics.arcade.overlap(player, stars, collectStar, null, this);
//}
if (cursors.left.isDown) {
notifyAction(ActionType.LEFT);
} else if (cursors.right.isDown) {
notifyAction(ActionType.RIGHT);
} else if (cursors.up.isDown) {
notifyAction(ActionType.UP);
} else if (cursors.down.isDown) {
notifyAction(ActionType.DOWN);
} else if (spaceKey.isDown) {
notifyAction(ActionType.SPEED_UP);
}
if (updates.length > 1) {
// added
var from = updates[0];
var to = updates[1];
serverTime = from.serverTime;
serverTick = from.tick;
//console.log(`clientTick = ${clientTick} serverTick = ${serverTick}`);
if (from.added) {
for (var i = 0, len = from.added.length; i < len; i++) {
var entity = from.added[i];
if (entity.uid == uid) {
continue;
}
var entityId = entity.id;
entities[entityId] = createEntity(entity.type, entity.x, entity.y);
entities[entityId].entityId = entityId;
}
}
// deleted
if (from.deleted) {
for (var i = 0, len = from.deleted.length; i < len; i++) {
var entityId = from.deleted[i];
var sprite = entities[entityId];
if (sprite) {
sprite.destroy();
}
}
}
// moved
if (from.moved) {
for (var i = 0, len = from.moved.length; i < len; i++) {
var entity = from.moved[i];
var entityId = entity.id;
var sprite = entities[entityId];
if (sprite) {
sprite.x = entity.x * size;
sprite.y = entity.y * size;
// sprite.body.velocity.x = entity.dx * size;
// sprite.body.velocity.y = entity.dy * size;
if (entity.dx > 0 && (entity.type == EntityType.PLAYER || entity.type == EntityType.GHOST)) {
sprite.animations.play('right');
} else if (entity.dx < 0 && (entity.type == EntityType.PLAYER || entity.type == EntityType.GHOST)) {
sprite.animations.play('left');
} else if (entity.type == EntityType.PLAYER || entity.type == EntityType.GHOST){
sprite.animations.stop();
sprite.frame = 4;
}
// strong
if (EntityStatus.checkStatus(entity.status, EntityStatus.STRONG)) {
sprite.scale.setTo(sprite.origScale * 2, sprite.origScale * 2);
}
// slow
if (EntityStatus.checkStatus(entity.status, EntityStatus.SLOW)) {
sprite.scale.setTo(0.5 * sprite.origScale, 0.5 * sprite.origScale);
}
// shield
if (EntityStatus.checkStatus(entity.status, EntityStatus.SHIELD)) {
sprite.scale.setTo(4 * sprite.origScale, 4 * sprite.origScale);
}
// reset
if (entity.status == 0) {
sprite.scale.setTo(sprite.origScale, sprite.origScale);
}
}
}
}
if (from.dotsAdded) {
for (var i = 0, len = from.dotsAdded.length; i < len; i++) {
var dot = from.dotsAdded[i];
console.log(dot);
console.log('added');
dots[dot.x] = dots[dot.x] || {};
if (!dots[dot.x][dot.y]) {
dots[dot.x][dot.y] = createEntity(EntityType.STAR, dot.x, dot.y);
}
}
}
if (from.dotsDeleted) {
for (var i = 0, len = from.dotsDeleted.length; i < len; i++) {
var dot = from.dotsDeleted[i];
var star = dots[dot.x] && dots[dot.x][dot.y];
console.log(dot);
console.log('deleted');
if (star) {
star.destroy();
delete dots[dot.x][dot.y];
}
}
}
if (to.moved) {
for (var i = 0, len = to.moved.length; i < len; i++) {
var entity = to.moved[i];
var entityId = entity.id;
var sprite = entities[entityId];
if (sprite) {
sprite.next_x = entity.x * size;
sprite.next_y = entity.y * size;
sprite.leftTime = to.serverTime - from.serverTime;
}
}
}
updates.shift();
} else {
for (var i = 0, len = players.children.length; i < len; i++) {
var player = players.children[i];
if (player.next_x && player.leftTime > 0) {
var dx = (player.next_x - player.x) * clientInterval / player.leftTime;
var dy = (player.next_y - player.y) * clientInterval / player.leftTime;
player.x += dx;
player.y += dy;
player.leftTime -= clientInterval;
}
}
}
}
function collectStar (player, star) {
star.kill();
if (player.uid == uid) {
//score += 10;
//scoreText.text = 'score: ' + score;
//notifyAction('eat', star.entityId);
}
}
function renderScores(scores) {
var text = 'LEADERBOARD\n';
for (var i = 0; i < scores.length; i++) {
text += scores[i].nickname + ': ' + scores[i].score + '\n'
}
scoreText.text = text;
}
$(function() {
$('#login-modal').modal('show');
$('#login').on('click', function () {
nickname = $('#name').val();
$('#login-modal').modal('hide');
loadMap(function(err) {
if (err) {
return alert(err);
}
game = new Phaser.Game(parseInt(map.width * size), parseInt(map.height * size), Phaser.AUTO, '', { preload: preload, create: create, update: update });
});
});
})
| 6ae7dd53c2399904db4ba30b96a79291a401111b | [
"JavaScript",
"Makefile",
"Markdown"
] | 9 | Makefile | wangchuan3533/phaser_demo | b3e128a3ea76525381128619a77a19a7db3e0023 | cb8e631026178093cb03fa8fe13427909b879d6f |
refs/heads/master | <repo_name>zhaoqingfa/Player<file_sep>/app/src/main/java/com/edu/player/business/main/MainActivity.java
package com.edu.player.business.main;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ViewParent;
import com.edu.player.ITCPHeartAidlInterface;
import com.edu.player.R;
import com.edu.player.base.BaseActivity;
import com.edu.player.base.interfac.IPresenter;
import com.edu.player.common.log.LogUtil;
import com.edu.player.common.service.TCPHeartService;
import com.edu.player.common.widgets.ViewPagerAdapter;
import com.edu.player.util.Config;
public class MainActivity extends BaseActivity<IPresenter> {
private ViewPager mViewPager;
private TabLayout mTabLayout;
private ViewPagerAdapter adapter;
private ITCPHeartAidlInterface aidlInterface;
private ServiceConnection serviceConnection;
@Override
protected int getLayoutId() {
return R.layout.activity_main;
}
@Override
protected void initView() {
super.initView();
mViewPager = findViewById(R.id.vp);
mTabLayout = findViewById(R.id.tl);
}
@Override
protected void initData() {
super.initData();
bindService();
adapter = new ViewPagerAdapter(getSupportFragmentManager(), this, null, null);
mViewPager.setAdapter(adapter);
mTabLayout.setupWithViewPager(mViewPager);
}
@Override
protected void initListener() {
super.initListener();
mTabLayout.addOnTabSelectedListener(new TabLayout.BaseOnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0:
break;
}
// tab.getCustomView().findViewById()
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
}
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
unBindService();
}
private void bindService() {
Intent intent = new Intent(this, TCPHeartService.class);
serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
aidlInterface = ITCPHeartAidlInterface.Stub.asInterface(service);
try {
aidlInterface.toService(Config.DEFAULT_IP, Config.DEFAULT_PORT);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
aidlInterface = null;
}
};
bindService(intent, serviceConnection, BIND_AUTO_CREATE);
}
private void unBindService() {
if (serviceConnection != null) {
unbindService(serviceConnection);
}
}
@Override
public IPresenter initPresenter() {
return null;
}
}
<file_sep>/app/src/main/java/com/edu/player/common/service/TCPHeartService.java
package com.edu.player.common.service;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import com.edu.player.ITCPHeartAidlInterface;
import com.edu.player.common.log.LogUtil;
import com.edu.player.net.socket.SocketClient;
import com.edu.player.util.Config;
import java.nio.ByteBuffer;
import java.util.Arrays;
/**
* Created by v_zhaoqingfa on 2018/12/17.
*/
public class TCPHeartService extends Service{
private static final long HEART_TIME = 1 * 1000;
private String mIp;
private int mPort;
private SocketClient mSocketClient;
private Handler mHandler;
private Runnable mRunnable;
private long sendTime = 0L;
private IBinder mIBinder = new ITCPHeartAidlInterface.Stub() {
@Override
public String toActivity(int code, String msg) throws RemoteException {
return "";
}
@Override
public void toService(String ip, int port) throws RemoteException {
mIp = ip;
mPort = port;
}
};
private SocketClient.SocketEventListener listener = new SocketClient.SocketEventListener() {
@Override
public void onDataReceived(byte[] data, short capacity) {
LogUtil.d("TCPHeartService read success ==>" + Arrays.toString(data));
}
@Override
public void onConnected(short result, Exception e) {
if (SocketClient.SUCCESS == result) {
if (mHandler != null && mRunnable != null) {
mHandler.postDelayed(mRunnable, 0);
}
}
}
@Override
public void onDisconnected(short result, Exception e) {
}
@Override
public void onDataDelivered(short result, Object e) {
if (SocketClient.SUCCESS == result) {
sendTime = System.currentTimeMillis();
LogUtil.d("TCPHeartService write success ==>" + Arrays.toString(((ByteBuffer) e).array()));
}
}
};
@Override
public void onCreate() {
super.onCreate();
initSocket();
mHandler = new Handler();
mRunnable = new Runnable() {
@Override
public void run() {
mSocketClient.send(ByteBuffer.wrap(new byte[]{1}));
mHandler.postDelayed(mRunnable, HEART_TIME);
}
};
}
private void initSocket() {
mIp = TextUtils.isEmpty(mIp) ? Config.DEFAULT_IP : mIp;
mPort = mPort == 0 ? Config.DEFAULT_PORT : mPort;
mSocketClient = new SocketClient(mIp, mPort);
mSocketClient.setSocketEventListener(listener);
mSocketClient.connect();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mIBinder;
}
@Override
public void onDestroy() {
super.onDestroy();
LogUtil.d("TCPHeartService onDestroy");
if (mHandler != null && mRunnable != null) {
mHandler.removeCallbacks(mRunnable);
}
if (mSocketClient != null) {
mSocketClient.setSocketEventListener(null);
}
mSocketClient.close();
}
}
<file_sep>/app/src/main/java/com/edu/player/business/login/LoginPresenter.java
package com.edu.player.business.login;
import com.edu.player.base.BasePresenter;
import com.edu.player.base.interfac.IView;
/**
* Created by zqf on 2018/11/24.
*/
public class LoginPresenter extends BasePresenter<ILoginContact.IV, ILoginContact.IM> {
public LoginPresenter(ILoginContact.IV iv, ILoginContact.IM im) {
super(iv, im);
}
}
| c3a279590f508b568c39bf887fb6b783a0615ac7 | [
"Java"
] | 3 | Java | zhaoqingfa/Player | d83a824bbda27df9c930afe0e3f0152a026c703f | d71ec8ca31734e376b116b9f22b449a38a9a5500 |
refs/heads/master | <repo_name>adbatbasic/LeapProjects<file_sep>/C++/ImageProcessing/ImageProcessing/ImageCorrection.cpp
#include "stdafx.h"
#include <iostream>
#include <cstring>
#include "Leap.h"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/contrib/contrib.hpp>
#include <tuple>
using namespace Leap;
using namespace cv;
using namespace std;
class SampleListener : public Listener {
public:
virtual void onInit(const Controller&);
virtual void onConnect(const Controller&);
virtual void onDisconnect(const Controller&);
virtual void onExit(const Controller&);
virtual void onFrame(const Controller&);
virtual void onServiceConnect(const Controller&);
virtual void onServiceDisconnect(const Controller&);
virtual Mat slowInterpolation(const Image&);
virtual tuple<Mat, Mat> getDistortionMaps(const Image&);
virtual tuple<Mat,Mat> correctImages(const Image&, const Image&);
virtual Mat getDisparityMap(Mat, Mat);
virtual Mat getSteroVar(Mat, Mat);
bool distortionInitFlag;
tuple<Mat, Mat> leftDistortionMaps;
tuple<Mat, Mat> rightDistortionMaps;
private:
};
const string fingerNames[] = { "Thumb", "Index", "Middle", "Ring", "Pinky" };
const string boneNames[] = { "Metacarpal", "Proximal", "Middle", "Distal" };
const string stateNames[] = { "STATE_INVALID", "STATE_START", "STATE_UPDATE", "STATE_END" };
void SampleListener::onInit(const Controller& controller) {
distortionInitFlag = false;
cout << "Initialized" << endl;
}
void SampleListener::onConnect(const Controller& controller) {
cout << "Connected" << endl;
}
void SampleListener::onDisconnect(const Controller& controller) {
cout << "Disconnected" << endl;
}
void SampleListener::onExit(const Controller& controller) {
cout << "Exited" << endl;
}
tuple<Mat, Mat> SampleListener::getDistortionMaps(const Image& image) {
int destinationHeight = 240;
int destinationWidth = 640;
int distortionLength = image.distortionHeight() * image.distortionWidth();
const float* distortion_buffer = image.distortion();
float *xmap = new float[distortionLength / 2];
float *ymap = new float[distortionLength / 2];
for (int i = 0; i < distortionLength; i += 2) {
xmap[distortionLength / 2 - i / 2 - 1] = distortion_buffer[i] * destinationWidth;
ymap[distortionLength / 2 - i / 2 - 1] = distortion_buffer[i + 1] * destinationHeight;
}
Mat extended_xmap(image.distortionHeight(), image.distortionWidth() / 2, CV_32FC1, xmap);
Mat extended_ymap(image.distortionHeight(), image.distortionWidth() / 2, CV_32FC1, ymap);
resize(extended_xmap, extended_xmap, Size(640, 240), 0, 0, CV_INTER_LINEAR);
resize(extended_ymap, extended_ymap, Size(640, 240), 0, 0, CV_INTER_LINEAR);
return make_tuple(extended_xmap, extended_ymap);
}
tuple<Mat, Mat> SampleListener::correctImages(const Image& leftImage, const Image& rightImage) {
Mat leftDestination(640,240,CV_8UC1,0);
Mat rightDestination(640, 240, CV_8UC1, 0);
Mat leftSource(leftImage.height(), leftImage.width(), CV_8UC1, leftImage.dataPointer());
Mat rightSource(leftImage.height(), rightImage.width(), CV_8UC1, rightImage.dataPointer());
if (!distortionInitFlag) {
leftDistortionMaps = getDistortionMaps(leftImage);
rightDistortionMaps = getDistortionMaps(rightImage);
distortionInitFlag = true;
}
remap(leftSource, leftDestination, get<0>(leftDistortionMaps), get<1>(leftDistortionMaps), INTER_LINEAR, BORDER_CONSTANT, Scalar(0, 0, 0));
remap(rightSource, rightDestination, get<0>(rightDistortionMaps), get<1>(rightDistortionMaps), INTER_LINEAR, BORDER_CONSTANT, Scalar(0, 0, 0));
return make_tuple(leftDestination,rightDestination);
}
Mat SampleListener::getDisparityMap(Mat left, Mat right) {
Mat Depth, normalizedDepth;
int ndisparities = 16 * 5;
StereoBM sbm(CV_STEREO_BM_NORMALIZED_RESPONSE,ndisparities,5);
sbm.state->preFilterCap = 25;
sbm.state->minDisparity = -50;
sbm.state->uniquenessRatio = 15;
sbm.state->speckleWindowSize = 150;
sbm.state->speckleRange = 20;
sbm.operator()(left, right, Depth);
normalize(Depth, normalizedDepth, 0, 255, CV_MINMAX, CV_8U);
return normalizedDepth;
}
Mat SampleListener::getSteroVar(Mat left, Mat right) {
Mat Depth, normalizedDepth;
StereoVar SVCalculator(3, 0.25, 50, -50, 50, 7, 1.1, 0.15, 0.15,
StereoVar::PENALIZATION_TICHONOV,
StereoVar::CYCLE_V,
StereoVar::USE_SMART_ID | StereoVar::USE_MEDIAN_FILTERING);
resize(left, left,Size() ,0.25, 0.25, INTER_CUBIC);
resize(right, right, Size(), 0.25, 0.25, INTER_CUBIC);
SVCalculator.operator()(left, right, Depth);
resize(Depth, Depth, Size(640, 240), 0, 0, INTER_CUBIC);
//normalize(Depth, normalizedDepth, 0, 255, CV_MINMAX, CV_8U);
return Depth;
}
void SampleListener::onFrame(const Controller& controller) {
ImageList images = controller.frame().images();
if (images[0].isValid() && images[1].isValid()) {
tuple<Mat,Mat> undistortedImages = correctImages(images[0],images[1]);
Mat disparityMap = getDisparityMap(get<0>(undistortedImages), get<1>(undistortedImages));
//Mat disparityMap = getSteroVar(get<0>(undistortedImages), get<1>(undistortedImages));
namedWindow("Left", WINDOW_AUTOSIZE);
namedWindow("Right", WINDOW_AUTOSIZE);
namedWindow("Disparity Map", WINDOW_AUTOSIZE);
imshow("Left", get<0>(undistortedImages));
imshow("Right", get<1>(undistortedImages));
imshow("Disparity Map", disparityMap);
waitKey(1);
}
}
void SampleListener::onServiceConnect(const Controller& controller) {
cout << "Service Connected" << endl;
}
void SampleListener::onServiceDisconnect(const Controller& controller) {
cout << "Service Disconnected" << endl;
}
Mat SampleListener::slowInterpolation(const Image& image){
float destinationWidth = 320;
float destinationHeight = 120;
unsigned char destination[320][120];
float calibrationX, calibrationY;
float weightX, weightY;
float dX, dX1, dX2, dX3, dX4;
float dY, dY1, dY2, dY3, dY4;
int x1, x2, y1, y2;
int denormalizedX, denormalizedY;
int i, j;
const unsigned char* raw = image.data();
const float* distortion_buffer = image.distortion();
const int distortionWidth = image.distortionWidth();
const int width = image.width();
const int height = image.height();
for (i = 0; i < destinationWidth; i++) {
for (j = 0; j < destinationHeight; j++) {
calibrationX = 63 * i / destinationWidth;
calibrationY = 62 * (1 - j / destinationHeight);
weightX = calibrationX - truncf(calibrationX);
weightY = calibrationY - truncf(calibrationY);
x1 = calibrationX;
y1 = calibrationY;
x2 = x1 + 1;
y2 = y1 + 1;
dX1 = distortion_buffer[x1 * 2 + y1 * distortionWidth];
dX2 = distortion_buffer[x2 * 2 + y1 * distortionWidth];
dX3 = distortion_buffer[x1 * 2 + y2 * distortionWidth];
dX4 = distortion_buffer[x2 * 2 + y2 * distortionWidth];
dY1 = distortion_buffer[x1 * 2 + y1 * distortionWidth + 1];
dY2 = distortion_buffer[x2 * 2 + y1 * distortionWidth + 1];
dY3 = distortion_buffer[x1 * 2 + y2 * distortionWidth + 1];
dY4 = distortion_buffer[x2 * 2 + y2 * distortionWidth + 1];
dX = dX1 * (1 - weightX) * (1 - weightY) +
dX2 * weightX * (1 - weightY) +
dX3 * (1 - weightX) * weightY +
dX4 * weightX * weightY;
dY = dY1 * (1 - weightX) * (1 - weightY) +
dY2 * weightX * (1 - weightY) +
dY3 * (1 - weightX) * weightY +
dY4 * weightX * weightY;
if ((dX >= 0) && (dX <= 1) && (dY >= 0) && (dY <= 1)) {
denormalizedX = dX * width;
denormalizedY = dY * height;
destination[i][j] = raw[denormalizedX + denormalizedY * width];
}
else {
destination[i][j] = -1;
}
}
}
Mat undistorted(destinationWidth, destinationHeight, CV_8UC1, destination);
transpose(undistorted, undistorted);
return undistorted;
}
int main(int argc, char** argv) {
// Create a sample listener and controller
SampleListener listener;
Controller controller;
// Have the sample listener receive events from the controller
controller.addListener(listener);
if (argc > 1 && strcmp(argv[1], "--bg") == 0)
{
controller.setPolicy(Leap::Controller::POLICY_BACKGROUND_FRAMES);
}
controller.setPolicy(Leap::Controller::POLICY_IMAGES);
// Keep this process running until Enter is pressed
cout << "Press Enter to quit..." << endl;
cin.get();
// Remove the sample listener when done
controller.removeListener(listener);
return 0;
}
<file_sep>/README.md
A python/C++ project using the Leap Motion API for image processing and gesture control.
Installation
==========
* Clone the repo or download the zip.
* Make sure you have the Leap SDK installed.
* run `pip install -r "requirements.txt"`
* Follow the instructions [here](https://developer.leapmotion.com/documentation/cpp/devguide/Project_Setup.html) and [here](http://docs.opencv.org/doc/tutorials/introduction/windows_visual_studio_Opencv/windows_visual_studio_Opencv.html) to get the Leap SDK and OpenCV to work with Visual Studio
Usage
=====
### For LeapMouse
* `cd` to the folder.
* run `python LeapMouse.py`
* The coordinates of the palm are used to move the mouse pointer around.
* A pinch between any finger and the thumb simulates a click.
* If the ring finger and pinky are not extended (Like the German hand gesture for the number three), the script enters scrolling mode and tilting the palm scrolls up and down. Moving the palm front and back zooms into and out of the screen.
* Make a fist with the palm pointing left to grab the active window and move it around the screen.
* Moving the hand in a circle of radius > 50 mm in clockwise/anticlockwise direction increases/decreases the master volume.
* LeapMouse.py works only with Windows.
### Other scripts
* `cd` to the folder and run `python <script>.py`
* FingerPlot.py uses matplotlib to plot the coordinates of your fingertips.(Needs Numpy and matplotlib)
* ImageCorrection.py uses bilinear interpolation to remove lens distortion from the Leap Motion controller's images
* ImageCorrection.cpp does the same thing but is much faster.
Screenshots
===========

Right hand image

Left hand image

Disparity map

Fingertip locations from FingerPlot.py
Dependencies
-----------------
* Pywin32 - Win32 API for Python
* comtypes - Pure Python COM package
Contributing
---------------
All contributions are welcome
<file_sep>/Python/FingerPlot.py
import Leap
import sys
import matplotlib.pyplot as plt
from matplotlib import animation
import numpy as np
fig = plt.figure()
ax = plt.axes(xlim = (-500,500),ylim = (0,400))
h1, = plt.plot([],[],'ro')
fingersPosX = np.array([0,0,0,0,0],dtype = 'float')
fingersPosY = np.array([0,0,0,0,0],dtype = 'float')
def init():
h1.set_data(fingersPosX,fingersPosY)
def animate(fn,controller):
frame = controller.frame()
hand = frame.hands.rightmost
fingers = hand.fingers
for finger in (fingers):
fingersPosX[finger.type()] = finger.stabilized_tip_position.x
fingersPosY[finger.type()] = finger.stabilized_tip_position.y
h1.set_data(fingersPosX,fingersPosY)
def main():
controller = Leap.Controller()
controller.set_policy_flags(Leap.Controller.POLICY_BACKGROUND_FRAMES)
anim = animation.FuncAnimation(fig,animate,fargs = (controller,),init_func = init, interval = 1,blit = False)
try:
plt.show()
except KeyboardInterrupt:
sys.exit(0)
if __name__ == '__main__':
main()
<file_sep>/Python/Controllers/FingerController.py
'''
* The coordinates of the palm are used to move the mouse pointer around.
* A pinch between any finger and the thumb simulates a click.
* If the ring finger and pinky are not extended (Like the German three hand gesture), the script enters scrolling mode and tilting the palm scrolls up and down. Moving the palm front and back zooms into and out of the screen.
* Make a fist with the palm pointing left to grab the active window and move it around the screen.
* Moving the hand in a circle of radius > 50 mm in clockwise/anticlockwise direction increases/decreases the master volume.
'''
import sys
import Leap
from Leap import CircleGesture
import win32api, win32con
from .Mouse import Mouse
class FingerListener(Leap.Listener):
def on_init(self,controller):
print("Initialized")
self.mouse = Mouse()
#controller.set_policy(Leap.Controller.POLICY_IMAGES)
def on_connect(self, controller):
print("Connected")
#Enable gestures
controller.enable_gesture(Leap.Gesture.TYPE_CIRCLE)
# controller.enable_gesture(Leap.Gesture.TYPE_KEY_TAP);
# controller.enable_gesture(Leap.Gesture.TYPE_SCREEN_TAP);
# controller.enable_gesture(Leap.Gesture.TYPE_SWIPE);
def on_disconnect(self, controller):
# Note: not dispatched when running in a debugger.
print("Disconnected")
def on_exit(self, controller):
print("Exited")
def on_frame(self, controller):
frame = controller.frame()
self.mouse.Handler(frame)
<file_sep>/Python/LeapMouse.py
from Controllers.FingerController import FingerListener
import Leap
import sys
import argparse
#parser = argparse.ArgumentParser()
#parser.add_argument('-s','--sensitivity',default = 2, type = int, help = 'Set mouse sensitivity')
def main():
#args = parser.parse_args()
controller = Leap.Controller()
listener = FingerListener()
controller.set_policy_flags(Leap.Controller.POLICY_BACKGROUND_FRAMES)
config = controller.config
config.set("Gesture.Circle.MinRadius",100.0)
config.set("Gesture.Circle.MinArc",30 * Leap.PI)
controller.add_listener(listener)
print("Press Enter to exit..")
sys.stdin.readline()
controller.remove_listener(listener)
if __name__ == '__main__':
main()<file_sep>/Python/Controllers/Mouse.py
import Leap
import win32api,win32con,win32gui,comtypes
from .VolumeTest import endpoint, IID_IAudioEndpointVolume, enumerator
class Mouse():
def __init__(self):
self.screen_resolution = (
win32api.GetSystemMetrics(0),
win32api.GetSystemMetrics(1)
)
self.center = {
'x':self.screen_resolution[0]/2,
'y':self.screen_resolution[1]/2
}
self.scale_factor = {
'x':self.screen_resolution[0]/400,
'y':self.screen_resolution[1]/350
}
self.mode = 0
self.clicked = 0
self.clickPoint = None
self.zoomCoord = None
self.cursor_level = None
self.sensitivity = 2.5
def Handler(self,frame):
hands = frame.hands
if hands:
Hand = None
for item in hands:
if item.is_right:
Hand = item
if Hand:
fingers = Hand.fingers
extended_fingers = fingers.extended()
self.mode = 0
Ring = fingers.finger_type(3)[0]
Pinky = fingers.finger_type(4)[0]
if 2<= len(extended_fingers) <=3:
if Ring not in extended_fingers and Pinky not in extended_fingers:
Middle = fingers.finger_type(2)[0]
pinky_to_mid = Pinky.direction.angle_to(Middle.direction)
pinky_to_palm = Pinky.direction.angle_to(Hand.direction)
if 0.1 <= pinky_to_palm <= 3.5 and 0.1 <= pinky_to_mid <= 2.5:
self.mode = 1
if self.clickPoint is None:
self.clickPoint = Hand.palm_position.z
#self.cursor_level = self.hideCursor()
elif Hand.grab_strength > 0.93 and Hand.palm_normal.x < -0.6:
self.mode = 2
else:
pass
if self.mode == 0:
#print "Pointer"
self.clickPoint = None
self.zoomCoord = None
self.Pointer(Hand,0)
if self.cursor_level is not None:
win32api.ShowCursor(self.cursor_level)
elif self.mode == 1:
#print "Scroller"
self.Scroller(Hand)
if self.cursor_level is not None:
win32api.ShowCursor(self.cursor_level)
elif self.mode == 2:
self.clickPoint = None
self.zoomCoord = None
#print "Grabber"
self.Pointer(Hand,1)
else:
pass
for gesture in frame.gestures():
if gesture.type == Leap.Gesture.TYPE_CIRCLE:
circle = Leap.CircleGesture(gesture)
if circle.radius > 50:
self.volumeSetter(circle)
def Scroller(self,hand):
handDir = hand.direction
handPos = hand.palm_position
pitch = handDir.pitch
x,y = win32api.GetCursorPos()
#print win32api.GetAsyncKeyState(win32con.VK_LCONTROL)
if pitch > 0.175:
win32api.mouse_event(win32con.MOUSEEVENTF_WHEEL, x, y, 10, 0)
return
if pitch < -0.2:
win32api.mouse_event(win32con.MOUSEEVENTF_WHEEL, x, y, -10, 0)
return
self.zoomDetect(handPos.z)
def Pointer(self, hand, grab):
if hand.translation_probability > 0.5:
handPos = hand.stabilized_palm_position
if -200 <= handPos.x <= 200 and 50 <= handPos.y <= 400:
x = int(self.sensitivity*self.scale_factor['x']*hand.stabilized_palm_position.x) + self.center['x']
y = -int(self.sensitivity*self.scale_factor['y']*(hand.stabilized_palm_position.y - 225)) + self.center['y']
if grab != 0:
if 20 <= x <= 1900 and 20 <= y <= 1060:
win_handle = win32gui.GetForegroundWindow()
win_size = win32gui.GetWindowRect(win_handle)
win32gui.SetWindowPos(
win_handle,win32con.HWND_TOP,
x,
y,
win_size[2]- win_size[0],
win_size[3] - win_size[1],
win32con.SWP_NOSIZE
)
return
else:
win32api.SetCursorPos((x,y))
if hand.pinch_strength > 0.97 and self.clicked == 0:
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
self.clicked = 1
if hand.pinch_strength <= 0.95 and self.clicked == 1:
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
self.clicked = 0
return
def zoomDetect(self,z):
if abs(z - self.clickPoint) > 30.0:
#print "Zoom"
if self.zoomCoord is None:
self.zoomCoord = z
if (z - self.clickPoint) > 0.0:
self.Zoom(-1)
else:
self.Zoom(1)
elif self.zoomCoord - z > 10.0:
self.Zoom(-1)
#print "In"
self.zoomCoord = z
elif self.zoomCoord - z < -10.0:
self.Zoom(1)
#print "Out"
self.zoomCoord = z
def Zoom(self,zoomFactor):
x,y = win32api.GetCursorPos()
if zoomFactor < 0:
self.keyPress(win32con.VK_LCONTROL)
win32api.mouse_event(win32con.MOUSEEVENTF_WHEEL, x, y, 1, 0)
self.keyRelease(win32con.VK_LCONTROL)
else:
self.keyPress(win32con.VK_LCONTROL)
win32api.mouse_event(win32con.MOUSEEVENTF_WHEEL, x, y, -1, 0)
self.keyRelease(win32con.VK_LCONTROL)
def keyPress(self,key_code):
if win32api.GetAsyncKeyState(key_code):
return
while not win32api.GetAsyncKeyState(key_code):
win32api.keybd_event(key_code,0,win32con.WM_KEYDOWN,0)
def keyRelease(self,key_code):
if not win32api.GetAsyncKeyState(key_code):
return
while win32api.GetAsyncKeyState(key_code):
win32api.keybd_event(key_code,0,win32con.KEYEVENTF_KEYUP,0)
def hideCursor(self):
value = win32api.ShowCursor(False) + 1
while win32api.ShowCursor(False) > -1:
win32api.ShowCursor(False)
return value
def volumeSetter(self,circle):
endpoint = enumerator.GetDefaultAudioEndpoint(0,1)
volume = endpoint.Activate(IID_IAudioEndpointVolume, comtypes.CLSCTX_INPROC_SERVER, None )
if circle.radius >= 50 and circle.pointable.tip_velocity > 700:
level = volume.GetMasterVolumeLevel()
if (circle.pointable.direction.angle_to(circle.normal) <= Leap.PI/2):
if level + 0.1 < 0:
volume.SetMasterVolumeLevel(level + 0.1,None)
else:
if level - 0.1 > -64:
volume.SetMasterVolumeLevel(level - 0.1,None)<file_sep>/requirements.txt
pywin32==219
comtypes==1.1.2 | 71f30cfaed5a0fb9daa92b985583e65704f9f3ec | [
"Markdown",
"Python",
"Text",
"C++"
] | 7 | C++ | adbatbasic/LeapProjects | 0f5029e0a9ba19ec636ac7f43552862584f715e9 | 19bf74e70c6922ad689947322f56ee0d7db1cb0a |
refs/heads/master | <repo_name>isabella232/homebrew-formulae-4<file_sep>/Formula/releasekit.rb
class Releasekit < Formula
desc "Create GitHub releases from closed issues and pull requests"
homepage "https://github.com/zestia/releasekit"
url "https://github.com/zestia/releasekit/releases/download/v0.3.3/releasekit-darwin-amd64"
sha256 "4ee14e059d8825b5469691a0dbb1670d9e47ee6bda5cbf9d6d1f28c32ed0d9bb"
bottle :unneeded
def install
bin.install "releasekit-darwin-amd64" => "releasekit"
end
end | 52651e3a56a3ae80eb77b4d0b5be8a4e2e189ce3 | [
"Ruby"
] | 1 | Ruby | isabella232/homebrew-formulae-4 | b83dcac9e7c34f6db4c0a87fddfba61b686d94fc | 2e48de7870b5bdfecfef8e1ebced331d12b77efc |
refs/heads/main | <file_sep>import Computer from "./Computer";
import computers from "../computers";
import { ComputerListWrapper } from "../styles";
function ComputerList() {
const computerList = computers.map((computer) => (
<Computer key={computer.id} computer={computer} />
));
return (
<ComputerListWrapper>
{computerList}
</ComputerListWrapper>
);
}
export default ComputerList;
<file_sep>import ComputerList from "./Components/ComputerList.jsx";
import Header from "./Components/Header";
import { GlobalStyles } from "./styles";
import { ThemeProvider } from "styled-components";
const theme = {
textColor:"#f7f1e3",
backgroudColor:"#2c2c54"
}
function App() {
return (
<ThemeProvider theme={theme}>
<GlobalStyles />
<Header />
<ComputerList />
</ThemeProvider>
);
}
export default App;
<file_sep>class Computer {
constructor(name, price, imgURL) {
this.id = Computer.incrementId();
this.name = name;
this.price = price;
this.imgURL = imgURL;
}
static incrementId() {
if (!this.latestId) this.latestId = 1
else this.latestId++
return this.latestId
}
}
const computers = [
new Computer("ABS Master Gaming PC ","6,633.19SR","https://c1.neweggimages.com/ProductImage/83-360-021-10.jpg"),
new Computer("ROG Strix GL10DH ","3,537.39SR","https://c1.neweggimages.com/ProductImage/83-221-640-V01.jpg"),
new Computer("Acer Predator Orion","6,059.34SR","https://c1.neweggimages.com/ProductImage/83-101-820-V16.jpg"),
];
export default computers;
<file_sep>import { HeaderWrapper, HeaderStoreFront } from "../styles";
export default function Header() {
return (
<HeaderWrapper>
<h1>Computer Store</h1>
<h5>Your Place for a Custom PC</h5>
<HeaderStoreFront src="https://cdn.shopify.com/s/files/1/0944/0000/collections/best-gaming-computers-toronto-canada-store-local-near-me_2000x.png?v=1601770840" />
</HeaderWrapper>
);
}
<file_sep>import styled, { createGlobalStyle } from "styled-components";
export const GlobalStyles = createGlobalStyle`
body{
font-family: 'Staatliches', cursive;
background-color:${props=>props.theme.backgroudColor};
color:${props=>props.theme.textColor}
}
`;
export const HeaderWrapper = styled.div`
margin-top: 15px;
h1,
h5 {
margin-bottom: 1rem;
}
text-align: center;
`;
export const HeaderStoreFront = styled.img`
width: 80%;
margin: auto;
`;
export const ComputerListWrapper = styled.div`
display: flex;
justify-content: center;
padding: 35px;
flex-wrap: wrap;
`;
export const ComputerListItems = styled.div`
img {
height: 350px;
padding: 20px;
}
h4 {
padding: 15px;
}
p {
padding: 15px;
font-size: large;
}
text-align: center;
`;
<file_sep>import { ComputerListItems } from "../styles";
export default function Computer(props) {
return (
<ComputerListItems>
<h4>{props.computer.name}</h4>
<img src={props.computer.imgURL} />
<p>{props.computer.price}</p>
</ComputerListItems>
);
}
| 42f9cdec064617a3e1f6001f032a7d81bc619671 | [
"JavaScript"
] | 6 | JavaScript | mhussein15/react-store | b15a7188d27f06e27b485624b77f2e452f0f9998 | 2f445df627182f5961a5d84d8a3df004f5ba4bb9 |
refs/heads/master | <file_sep>const express = require('express');
const fs = require('fs');
const path = require('path');
const datas = JSON.parse(fs.readFileSync('./.exported'));
let server = express();
server.listen(8090);
console.log('running at 8090');
server.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
server.get('/list', (req, res) => {
let page = parseInt(req.query['page'] || 0);
console.log(req.query);
console.log('================');
console.log(req.query['page']);
let page_size = 8;
console.log(typeof datas);
let arr1 = datas.slice(page*page_size, (page+1)*page_size);
console.log(arr1);
let arr = arr1.map(item => {
return {
id: item.article['detailArticle|post'].id,
tag: item.tag,
title: item.title,
src: item.src,
summary: item.summary,
time: Math.floor(new Date(item.time).getTime()/1000),
catalogs: item.catalogs,
author: {
title: item.author_title,
href: item.author_href,
}
};
});
res.send(arr);
});
server.get('/img', (req, res)=>{
let src = req.query.src;
res.sendFile(path.resolve('img', src));
});
server.get('/detail', (req, res) => {
let id = req.query.id;
let data = null;
datas.forEach(item => {
if(item.article['detailArticle|post'].id == id){
data = item;
}
});
res.send(data);
})
<file_sep>export default {
a : 1,
show: function (){
console.log('i know how to use webpack');
}
}<file_sep># learn-vue
learn vue
## 用vue做了一个小例子
* 用vue做了一个切换卡片页面,用到了vue中的钩子函数、v-on、v-for、v-bind、组件化、组件间通信等知识,并尝试组件化。
* 用vue-cli重写todoList
## vue的webpack模板
* 创建webpack模板,详见[官网](https://vuejs-templates.github.io/webpack/)
* 组件间通信,如父子组件,其他组件
* 数据交互
* vuex统一状态管理
<file_sep>import mod1 from './1'
mod1.show();
console.log(mod1.a);<file_sep># 练习vue——webpack模板的笔记
新建项目并运行
======
```
//全局安装vue-cli
npm install -g vue-cli
//初始化webpack
vue init webpack my-project
//进入新建项目的文件夹
cd my-project
//运行项目
npm run dev
```
路由切换
=======
* 在文件夹'/src/component'下新建'user.vue'和'article.vue'文件,
* 在文件'/src/router/index.js'中注册文件对应的路由
* 在文件'App.vue'中添加`<router-link to="路由的name">必须添加内容,以使其在页面正常显示</router-link>`
父子组件通信
====
* 新建文件'list.vue'和'list_item.vue'
* 利用属性`this.$attrs`传递数据给子组件
* 利用属性`props`传递数据给子组件
* 利用`this.$emit('绑定的fn', arg)`传递数据给父组件
数据交互
====
* 利用koa框架构建本地服务器,提供数据,详见server文件夹
* 数据交互方法
* axios
* 局部引用-哪里要用就在那里引用
* 全局引用-`Vue.prototype.axios = axios`、在vue中注册、`this.axios.get(url)`就可以全局使用了
* fetch-`let items = await (await fetch(url)).json();`
统一状态管理--vuex
====
* 安装
```
npm i vuex -S
```
* 引用--`import Vuex from 'vuex'`
* 注册
```javascript
Vue.use(Vuex);
new Vue({
...
store,
...
})
```
* 创建
```javascript
const store = new Vuex.Store({
strict: true,
state: {},
mutations: {
fn(state, arg){
//todosomething
}
},
actions:{
fn(store, arg){
//todosomething
}
},
getters: {
}
})
```
* 在用到数据的组件里--`this.$store.dispatch('actions里定义的函数', arg)`<file_sep>const pathlib = require('path')
module.exports = {
mode: 'development',
entry: './js/es6_demo',
output: {
path: pathlib.resolve('dest'),
filename: 'bundle_babel.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loadr: 'babel-loader',
options: {
presets: ['env']
}
}
}
]
}
}<file_sep>import a from './common'
window.onload = function () {
document.onclick = function () {
alert(a.sum(2,3,6,8));
console.log('a');
}
}<file_sep>import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
const store = new Vuex.Store({
strict: true,
state: {
arr: [],
},
mutations: {
setArr(state, arg){
state.arr = arg;
// arg.forEach(item => {
// state.arr.push(item);
// });
// console.log(state.arr);
}
},
actions: {
async loadArr({commit}, arg){
let arr = await (await fetch('http://localhost:8081/list')).json();
commit('setArr', arr);
}
},
getters:{
async arr(state){
if(state.arr.length==0){
store.dispatch('loadArr');
}
return state.arr;
}
}
});
export default store;
<file_sep># demo36kr
> A Vue.js project
## Build Setup
``` bash
# install dependencies
npm install
# serve with hot reload at localhost:8080
npm run dev
# build for production with minification
npm run build
# build for production and view the bundle analyzer report
npm run build --report
# run unit tests
npm run unit
# run e2e tests
npm run e2e
# run all tests
npm test
```
For a detailed explanation on how things work, check out the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader).
今日学习总结
===========
* promise的原理和使用技巧(函数式编程)
* 柯里化--只传递给函数一部分参数来调用它,让它返回一个函数去处理剩余参数
* 回调函数resolve,reject
* 链式结构,因为没一个then函数返回的都是一个Promise对象
* 因为是纯函数,参数都是给定的,函数就像变量一样当作参数使用
* js的学习方向
* 搞定一个对象
* 函数(两种定义方式/两种返回结果方式,立即返回,间接返回/同步、异步)
* 三种逻辑结构(顺序、条件、循环)
* 多种数据结构操作方式(字符串、数组、对象)
* 虚拟机安装ubuntu,一开始就软件升级、安装nvm,node,vscode,调整整个界面的显示尺寸(xrandr)
<file_sep>function sleep(t){
return new Promise((reslove, reject) => {
setTimeout(() => {
reslove();
}, t);
})
}
(async () => {
for(let i=0; i<10; i++){
await sleep(1000);
console.log(i);
}
})()<file_sep>['module.exports'和'exports'的区别](https://cnodejs.org/topic/5231a630101e574521e45ef8)
## webpack入门
1. npm init
2. cnpm i webpack webpack-cli -D
3. 新建文件"webpack.config.js"
4. 在文件'package.json'中配置webpack启动脚本"webpack --config webpack.config.js"
5. 新建文件夹“js”,新建文件“1.js”和“2.js”
//1.js
```javascript
export default {
a : 1,
show: function (){
console.log('i know how to use webpack');
}
}
```
//2.js
```javascript
import mod1 from './1'
mod1.show();
console.log(mod1.a);
```
此时,在终端直接执行`node .\js\2.js`是会报错的,需经过webpack打包编译后才能执行
6. 配置文件"webpack.config.js"
//webpack.config.js
```javascript
const pathlib = require('path')
module.exports = {
mode: 'development',
entry: './js/2.js',
output: {
path: pathlib.resolve('dest'),
filename: 'bundle.js'
}
}
```
7. 在终端执行命令`npm run dev`,成功后,文件夹‘dest’下会生成文件'bundle.js'
8. 此时再执行命令`node .\dest\bundle.js`就能看到正确结果了
```
i know how to use webpack
1
```
## dev-server
1. 安装dev-server `npm i webpack-dev-server -D`
2. 新建'dev-server-webpack.config.js',它的作用就跟"webpack.config.js"一样,是配置文件
3. 在文件'package.json'的'script'中配置dev-server启动脚本"webpack-dev-server --watch --inline --config dev-server-webpack.config.js",
4. 在'js'文件夹中新建文件夹'common.js'和'index.js'
5. 配置文件"dev-server-webpack.config.js"
```javascript
const pathlib = require('path')
const Webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
mode: 'development', //模式,有两种开发和生产,这里选开发
entry: './js/index.js', //入口文件,还能配置多入口
output: { //输出文件路径和文件名
path: pathlib.resolve('dest'),
filename: 'bundleDev.js'
},
plugins:[
new Webpack.HotModuleReplacementPlugin(), //插件,热更新插件,配合启动脚本使用
],
devServer: { //dev-server配置
contentBase: pathlib.resolve('static'), //静态文件目录路径
port: 8090, //启动端口号
hot: true, //热更新配置
historyApiFallback: true, //404全部重定向到入口html文件
watchContentBase: true //html保存后自动更新,或者不加这个选项,直接在启动脚本中加参数“--watch-content-base”
}
}
```
6. 配置完成后,在终端输入"npm start", start是文件'package.json'的'script'的一个属性
7. 在浏览器启动端口“http://localhost:8090/index.html”,就可以看到起作用的页面了
## loader的简单使用方法
待续 | 7447285d71be7e06e0a5f59acfbcccb10a47b079 | [
"JavaScript",
"Markdown"
] | 11 | JavaScript | l328958741/learn-vue | 0219216245daa9814b5c09d6452e73057829f968 | fe1799e2399356de823a62640e80d8a21d2e0435 |
refs/heads/master | <file_sep>/*
* To change this license firster, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package linkedlist;
import java.util.ArrayList;
public class LinkedList extends LNode implements HW2Interface {
public LNode first;
public LinkedList() {
first = new LNode(); // First node'unu oluşturup listeyi construct ediyoruz
first = null;
}
@Override
public void Insert(int newElement, int pos) throws Exception{
if (pos < 0)
throw LinkedListException();
LNode Dummy;
Dummy = first;
if (pos == 0) // Add to the first location
{
LNode NewNode = new LNode();
NewNode.Element = newElement;
NewNode.link = first;
first = NewNode;
}
else
{
for (int i = 0; i < pos-1; i++)
{
Dummy = Dummy.link;
if (pos > 0 && Dummy == null)
throw LinkedListException();
}
LNode NewNode = new LNode();
NewNode.Element = newElement;
NewNode.link = Dummy.link;
Dummy.link = NewNode;
}
}
@Override
public int Delete(int pos) throws Exception {
int DeletedNodeElement;
if (pos < 1){
throw LinkedListException();
}
LNode Dummy;
if (pos == 1 && first != null){ // The First Element
DeletedNodeElement = first.Element;
first = first.link;
}
Dummy = first;
for (int i = 0; i < pos-2; i++)
{
Dummy = Dummy.link;
if (pos > 0 && Dummy == null)
throw LinkedListException();
}
DeletedNodeElement = Dummy.link.Element;
Dummy.link = Dummy.link.link;
return DeletedNodeElement;
}
@Override
public void Output(){
LNode Dummy;
Dummy = first;
System.out.print("The Elements in the list are : ");
while (Dummy != null){
System.out.print(Dummy.Element + " " );
Dummy = Dummy.link;
}
System.out.println("");
}
/*
ReverseLink metodu, linked list'i aynalar.
*/
@Override
public void ReverseLink() {
LNode prev = null;
LNode curr = first;
while(curr != null) {
LNode next = curr.link; // Her seferinde yeni node yaratmanın sebebi eskiyi tutmadan listeye koymak.
curr.link = prev; // Bulunduğumuz node'un ilerisi olarak gerisi gösterilir.
prev = curr; // Bulunduğumuz node'un gerisi olarak bulunduğumuz node gösterilir.
curr = next; // Bulunduğumuz node olarak da bir sonraki node gösterilerek üçlü aynalama yapılmış olur.
}
first = prev;
}
/*
SquashL metodu, listedeki bir elemandan kaçar tane sıralı olarak bulunduğunu bulur.
Burada liste değiştirilmek yerine, geçici bir liste yaratılarak önce ona ekleme yapılıp,
daha sonra ise oluşturulan geçici listenin ilk node'u, var olan listenin ilk node'u
olarak gösterilir. Böylelikle ekstra kod yazmak yerine, OOP'nin biz sağladığı olanakları
kullanarak, yazmış ve almış olduğumuz ReverseLink ve Insert metodlarını direkt kullanarak
bunu sağladık.
*/
@Override
public void SquashL() {
LNode temp;
LinkedList tempList = new LinkedList(); // Geçici bir liste oluşturduk
temp = this.first;
int count = 1;
while(temp.link != null) {
count = 1; // Count değişkeni 1 olarak başlar.
int tempElem = temp.Element;
while(temp != null && temp.Element == temp.link.Element){ // Bulunulan node bir sonrakine eşit olduğu ve bir sonraki
count++; // node null olmadığı sürece count değişkenini arttırıyoruz.
tempElem = temp.Element; // Buradaki sıkıntı, listenin son elemanının tekli olması zorunluluğu.
temp = temp.link; // Şartlar bozulana kadar listenin içinde ilerliyoruz.
}
try{
tempList.Insert(tempElem, 0); // Hangi elemanı sayıyorsak, onu listeye koyuyoruz.
tempList.Insert(count, 0); // Sayılan elemanın miktarını listeye koyuyoruz.
} // Listedeki sıranın tersi yönünde koyuyoruz. Çünkü elimizdeki
catch(Exception e){ // Insert metodunda yapabileceğimiz en kolay şey başa eleman eklemek.
LinkedListException(); // Elemanları ters yönde başa ekleyip, listeyi aynalarsak, istediğimiz
} // sonuca ekstra kod yazmadan ulaşmış oluruz.
temp = temp.link; // Listenin içinde ilerliyoruz.
}
try {
tempList.Insert(temp.Element, 0); // En son elemanı yukarıdaki döngüde kontrol edemiyoruz.
tempList.Insert(count, 0); // Kontrol şartlarımızda bir sonrakinin null olmama durumu var,
} // bu yüzden o elemanı okuma şansı olmadan döngüden çıkıyor.
catch(Exception e){ // Bundan dolayı son elemanı ve miktarını en sonda ekliyoruz
LinkedListException();
}
tempList.ReverseLink(); // Geçici listeyi ters çeviriyoruz.
this.first = tempList.first; // Var olan listemizi, geçici listemize eşitliyoruz.
}
/*
OplashL metodu, listedeki elemanları ikili olarak işler; sıradaki ilk node yerleştirilecek elemanı,
ikinci node ise yerleştirilme miktarını belirtir. Burada da SquashL metodundaki gibi geçici bir
liste oluşturup var olan metodları kullandık.
*/
@Override
public void OplashL() {
int tempElem;
int tempCount;
LinkedList tempList = new LinkedList();
LNode temp;
temp = this.first;
while(temp != null && temp.link != null) { // Döngünün çift kontrol yapmasının sebebi ilerleme miktarıdır. Döngünün sonunda açıklandı
tempElem = temp.Element; // Sıradaki ilk node yerleştirilecek elemanı gösteriyor.
tempCount = temp.link.Element; // Sıradaki ikinci node yerleştirilme miktarını gösteriyor.
for(int i = 0; i < tempCount; i++) { // Yerleştirilme miktarı kadar döngü döndürüyor ve
try {
tempList.Insert(tempElem, 0); // yerleştirilecek elemanı ekliyoruz.
} catch (Exception e) {
LinkedListException();
}
}
temp = temp.link.link; // Kod ikili çalıştığı için, listede iki adım ilerliyoruz.
}
tempList.ReverseLink();
this.first = tempList.first;
}
@Override
public Exception LinkedListException() {
Exception e = new Exception();
e.getMessage();
e.toString();
return null;
}
/*
toString metodu, Linked List'i String'e önce eleman eleman ArrayList'e atayıp,
daha sonra var olan ArrayList toString metoduyla String'e dönüştürür. Yaşasın OOP =)
*/
@Override
public String toString() {
String strList;
ArrayList intList = new ArrayList();
LNode temp;
int tempInt;
temp = this.first;
while(temp != null) {
tempInt = temp.Element;
intList.add(tempInt);
temp = temp.link;
}
strList = intList.toString();
System.out.println("The list is: " + strList);
return strList;
}
public static void main(String[] args) throws Exception {
LinkedList myList = new LinkedList();
try {
myList.Insert(3, 0);
myList.Insert(4, 0);
myList.Insert(1, 0);
myList.Insert(1, 0);
myList.Insert(1, 0);
myList.Insert(1, 0);
myList.Insert(1, 0);
myList.Insert(1, 0);
myList.Insert(1, 0);
myList.Insert(1, 0);
} catch (Exception ex) {
System.out.println(ex.toString());
}
myList.SquashL();
myList.Output();
myList.OplashL();
myList.Output();
myList.toString();
}
}
<file_sep>package hashClass;
public class Hash {
public int key;
public int value;
public ArrayList<HashPosition> positionList;
public Hash(int key, int value, int posX, int posY) {
this.key = key;
this.value = value;
HashPosition pos = new HashPosition(posX, posY);
positionList = new ArrayList();
// positionList.set(0, pos);
positionList.add(pos);
}
public Hash() {
}
public int keyOf() {
return key;
}
public int valueOf() {
return value;
}
}
<file_sep>package hashClass;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class HashTable implements HW4_Interface {
public ArrayList<ArrayList<Hash>> hashTable;
public ArrayList<String> storage = new ArrayList();
public int size;
public HashTable() {
}
/**
* FindHash method finds a string's hash key
* @param mystring is string which its Hash key to be found
* @return string's hash key
*/
@Override
public long FindHash(String mystring) {
long hashKey = 0;
char [] stringArray = mystring.toCharArray(); // Hash key'i bulunacak stringi charlara böler
for(int i = 0; i < mystring.length(); i++) {
hashKey = hashKey * 37 + stringArray[i]; // Hash key algoritması
hashKey %= 997; // Büyük bir asal sayıya göre modulosunu alarak collision ihtimalini azaltıyoruz
}
return hashKey;
}
/**
* wordFreq method finds the frequency of a word in a text file.
* @param storage is file to be read in ArrayList form
* @param word is the word which the frequency is found
* @return frequency of word
*/
private int wordFreq(ArrayList storage, String word) {
int frequency = 0;
if (word == null) {
return 0;
}
else {
for (int i = 0; i < storage.size(); i++)
if (storage.get(i) == word) // Eğer girilen text dosyasında kelimeyi bulursa rastlanma frekansını bir arttırır
frequency++;
}
return frequency;
}
/**
* BuildHash method reads a file and build the hash table.
* @param filename is file to be read
* @param size is horizontal size of hashTable. vertical size is always 10 since insertion to table is done by modulo of 10
*/
@Override
public void BuildHash(String filename, int size) {
int check = 0;
int posX = 0;
int posY = 0;
this.size = size;
hashTable = new ArrayList();
for (int x = 0; x < size; x++) {
hashTable.add(new ArrayList());
}
File file = new File(filename);
Scanner scanFile = null;
try {
scanFile = new Scanner(new FileReader(file));
} catch (FileNotFoundException ex) {
System.out.println("NO SUCH FILE!");
}
String word;
while(scanFile.hasNextLine()) {
word = scanFile.nextLine().replaceAll("[(){},.;!?<>%]", "");
storage.add(word);
}
String[] parse;
for(int y = 0; y < storage.size(); y++) {
parse = storage.get(y).split(" ");
for(int x = 0; x < parse.length; x++) {
HashPosition pos = new HashPosition(x + 1, y + 1);
String checkWord = parse[x];
int frequency = wordFreq(storage, checkWord);
int hashKey = (int) FindHash(checkWord);
int arraySize = hashTable.get(hashKey % 10).size();
Hash element = new Hash(hashKey, frequency, x + 1, y + 1);
if(arraySize == 0) {
hashTable.get(hashKey % 10).add(element); // ilk durum
hashTable.get(hashKey % 10).get(0).value++;
}
else {
for (int i = 0; i < hashTable.get(hashKey % 10).size(); i++) {
Hash temp;
temp = (Hash) hashTable.get(hashKey % 10).get(i);
if (temp.key == FindHash(checkWord)) {
check = 1;
posX = hashKey % 10;
posY = i;
break;
}
else {
check = 2;
posX = hashKey % 10;
posY = i;
}
}
if(check == 1) {
hashTable.get(posX).get(posY).value++; // eger varsa 1 ekle
hashTable.get(posX).get(posY).positionList.add(pos);
}
if (check == 2) {
hashTable.get(hashKey % 10).add(element); // yoksa o arrayin sonuna ekle
hashTable.get(hashKey % 10).get(hashTable.get(hashKey % 10).size() - 1).value++;
hashTable.get(posX).get(posY).positionList.add(pos);
}
}
}
}
}
/**
* Finds a word's repetition time on text. Prints repeating locations and repeating amount
* @param myword is word to be found its repetition time
* @return -1 if not found, any cardinal number representing its repetition time
*/
@Override
public int NumofWord(String myword) {
boolean found = false;
long key;
int verticalIndex;
int horizontalIndex;
key = FindHash(myword);
verticalIndex = (int) (key % 10);
for(horizontalIndex = 0; horizontalIndex < hashTable.get(verticalIndex).size(); horizontalIndex++) {
if(hashTable.get(verticalIndex).get(horizontalIndex).keyOf() == key) {
found = true;
System.out.println("\"" + myword + "\" is repeated " + hashTable.get(verticalIndex).get(horizontalIndex).valueOf() + " times.");
for(int m = 0; m < hashTable.get(verticalIndex).get(horizontalIndex).positionList.size() - 1; m++) {
System.out.print(hashTable.get(verticalIndex).get(horizontalIndex).positionList.get(m).posY + ". row, ");
System.out.println(hashTable.get(verticalIndex).get(horizontalIndex).positionList.get(m).posX + ". word");
}
break;
}
}
if(found)
return hashTable.get(verticalIndex).get(horizontalIndex).valueOf();
else
return -1;
}
/**
* Finds a word's repetition time on text. Represents polymorphism.
* @param myword is word to be found its repetition time
* @param helper is a boolean to check whether method is called within ShowMax method.
* @return -1 if not found, any cardinal number representing its repetition time
*/
public int NumofWord(String myword, boolean helper) {
boolean found = false;
long key;
int verticalIndex;
int horizontalIndex;
key = FindHash(myword);
verticalIndex = (int) (key % 10);
for(horizontalIndex = 0; horizontalIndex < hashTable.get(verticalIndex).size(); horizontalIndex++) {
if(hashTable.get(verticalIndex).get(horizontalIndex).keyOf() == key) {
found = true;
break;
}
}
if(found)
return hashTable.get(verticalIndex).get(horizontalIndex).valueOf();
else
return -1;
}
/**
* Decides whether a word exists in the file
* @param myword is word to be checked
* @return the hash key of the word if exists, else -1
*/
@Override
public int CheckWord(String myword) {
long key;
int verticalIndex;
int horizontalIndex;
boolean found = false;
key = FindHash(myword);
verticalIndex = (int) (key % 10);
for(horizontalIndex = 0; horizontalIndex < hashTable.get(verticalIndex).size(); horizontalIndex++) {
if(hashTable.get(verticalIndex).get(horizontalIndex).keyOf() == key) {
found = true;
System.out.println("\"" + myword + "\" is found! Hash key of \"" + myword + "\" is: " + hashTable.get(verticalIndex).get(horizontalIndex).keyOf());
break;
}
}
if(found)
return hashTable.get(verticalIndex).get(horizontalIndex).keyOf();
else
return -1;
}
/**
* Sorts the hash table in an descending way by word's frequency in text.
* @param Outfile is name of the file which the sorted hash table to be written.
*/
@Override
public void Sort(String Outfile) {
Hash temp;
for (int i = 0; i < hashTable.size(); i++) {
for (int j = 0; j < hashTable.get(i).size() - 1; j++) {
if (hashTable.get(i).get(j).value > hashTable.get(i).get(j + 1).value) /* bir satırda soldan sağa sıralama yapar*/
{
temp = hashTable.get(i).get(j);
hashTable.get(i).set(j, hashTable.get(i).get(j + 1));
hashTable.get(i).set(j + 1, temp);
}
}
}
}
/**
* Creates a text file and writes the hash table on to it.
* @param Outputfile is name of the file which the sorted hash table to be written.
*/
@Override
public void Display(String Outputfile) {
try (PrintWriter writer = new PrintWriter(Outputfile, "UTF-8")) {
for(int i = 0; i < 10; i++) {
System.out.print(i + " ");
writer.print(i + " ");
for(int j = 0; j < hashTable.get(i).size(); j++) {
System.out.print(hashTable.get(i).get(j).keyOf() + " ");
writer.print(hashTable.get(i).get(j).keyOf() + " ");
}
System.out.println("");
writer.println("");
}
}
catch (IOException e) {
System.out.println("I/O PROBLEM!");
}
}
/**
* Finds the maximum repeated word on a text file.
* @return the max repeated word on text
*/
@Override
public String ShowMax() {
String maxWord = "";
String [] parse;
boolean helper = true;
for(int i = 0;i < storage.size(); i++) {
parse = storage.get(i).split(" ");
for (String parse1 : parse) {
if (NumofWord(maxWord, helper) < NumofWord(parse1, helper)) {
maxWord = parse1;
}
}
}
System.out.println("Max repeated word is: \"" + maxWord + "\". It's repeated " + NumofWord(maxWord, helper) + " times.");
return maxWord;
}
}
| a3ec07337d79f278197a366f7de40cdf142cc417 | [
"Java"
] | 3 | Java | alinurc/javaClassImplementations | d41586a3da7d85d4998d00b709d6f79dafecbcdd | c556a3231aee37acf6336bc70f14565860c0f2c3 |
refs/heads/master | <file_sep><?php
include_once('../funcoesPHP.php');
include 'conexao.php';
if(isset($_POST['nome'])){
$nome = $_POST['nome'];
$email = $_POST['email'];
$comentario = $_POST['comentario'];
$nota = $_POST['nota'];
$captcha = $_POST['g-recaptcha-response'];
}
if($captcha != ''){
$secreto = '6LddWMAUAAAAAAW_PFJnWjOOS9OJ6EGpNwBERZwl';
$ip = $_SERVER['REMOTE_ADDR'];
$var = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secreto&response=$captcha&remoteip=$ip");
$resposta = json_decode($var, true);
if($resposta['success']){
if(empty($nome) || empty($email) || empty($comentario) || empty($nota)){
echo "Verifique se todos os campos obrigatórios foram preenchidos";
}else{
$nota = $nota + 0;
$sql = "INSERT INTO comentarios VALUES(null, '{$nome}', '{$email}', '{$comentario}', {$nota} , NOW(), 0)";
if(mysqli_query($con, $sql)){
echo "sucesso";
}else{
echo "Erro ao gravar no banco";
}
// Close connection
mysqli_close($con);
}
}else{
echo "Erro na Captcha. Por favor, tente novamente";
}
}else{
echo "Por favor, selecione a Captcha";
}
?>
<file_sep><?php
session_start();
include_once('../funcoesPHP.php');
include 'conexao.php';
$nome = $_POST['nome'];
$email = $_POST['email'];
$telefone = $_POST['telefone'];
$celular = $_POST['celular'];
$descricao = $_POST['descricao'];
$medida = $_POST['medida'];
$quantidade = $_POST['quantidade'];
date_default_timezone_set('America/Sao_Paulo');
$data_interesse = date('Y-m-d H:i:s', time()+1440*60);
function tratarImagem(){
$imagem = $_FILES["imagem"];
$destino = '../encomenda/' . $_FILES['imagem']['name'];
$nome_imagem = $_FILES['imagem']['name'];
$tipo = $_FILES['imagem']['type'];
// Pega a extensão
$extensao = pathinfo($nome_imagem, PATHINFO_EXTENSION);
// Converte a extensão para minúsculo
$extensao = strtolower($extensao);
if(strstr('.jpg;.jpeg;.gif;.png', $extensao)){
// Concatena a pasta com o nome
$destino = '../encomenda/' . $nome_imagem;
// tenta mover o arquivo para o destino
if(move_uploaded_file($imagem['tmp_name'], $destino)) {
return "sucesso";
}else{
return "Por favor, envie imagens de até 2,0 MB.";
}
}else{
return "Arquivo não suportado. Formatos permitidos: jpg, jpeg, gif e png.";
}
}
if(empty($nome) || empty($email) || empty($descricao) || empty($medida) || empty($quantidade)){
echo "Verifique se todos os campos obrigatórios foram preenchidos";
}else{
$sql_verificaemail = mysqli_query($con, "SELECT * FROM clientes WHERE email = '$email'");
if(!empty($_FILES['imagem']['name'])){
$resp = tratarImagem();
}else{
$nome_imagem = null;
}
if((isset($resp) && $resp === "sucesso") || !isset($resp)){
$nome_imagem = $_FILES['imagem']['name'];
if(mysqli_num_rows($sql_verificaemail)!=1){
$sql_cliente = "INSERT INTO clientes VALUES(null, '{$nome}', '{$email}', '{$telefone}', '{$celular}')";
if(mysqli_query($con, $sql_cliente)){
echo "sucesso";
}
$cliente_id = mysqli_insert_id($con);
}else{
while($row = mysqli_fetch_array($sql_verificaemail)){
$cliente_id = $row['id'];
}
}
$chave_confirmacao = geradorchave();
$sql_encomenda = "INSERT INTO encomenda VALUES (null, '{$descricao}', '{$medida}', {$quantidade}, '{$nome_imagem}', '{$cliente_id}', '{$chave_confirmacao}', '{$data_interesse}', 0, 0)";
if(mysqli_query($con, $sql_encomenda)){
if(linkconfirmacao($chave_confirmacao, $email) === "sucesso"){
echo "sucesso";
}
}
}else{
echo $resp;
}
}
?><file_sep><?php
session_start();
if(!empty($_POST['id_usuario']) && !empty($_POST['nome']) && !empty($_POST['email']) && !empty($_POST['perfil'])){
include_once 'conexao.php';
$nome = $_POST['nome'];
$email = $_POST['email'];
$perfil = $_POST['perfil'];
$id = $_POST['id_usuario'];
$sql = "UPDATE usuarios SET nome = '$nome', email = '$email', perfil = '$perfil' WHERE id_usuario = $id";
if(mysqli_query($con, $sql)){
echo "sucesso";
}else{
echo "Erro ao gravar no banco";
}
mysqli_close($con);
} else{
echo "Por favor, preencha todos os campos obrigatórios.";
}
?><file_sep><?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>MaurícioLuminárias</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="<KEY> crossorigin="anonymous">
<!-- Folha de Estilo -->
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script>
$(document).ready(function() {
$('#formEncomenda').submit(function(event) {
event.preventDefault();
// seleciona o botão de submit
var botao = $(this).find('input[type="submit"]');
// desabilita o botão para evitar multiplos envio
botao.prop("disabled", true).val("Enviando..").css('opacity', '0.5');
$.ajax({
type: "post",
url: "bd/gravar_pre_encomenda.php",
data: new FormData(this),
contentType: false,
processData: false,
success: function( data ){
if(data === "sucesso" || data === "sucessosucesso"){
window.location.href = "encomendaRealizada.php";
} else{
$("#resposta_ajax").removeClass("alert-success").addClass("alert-danger").css('display', 'block').html(data);
}
botao.prop("disabled", false).val("Enviar").css('opacity', '1');
}
});
});
});
//Máscara telefone
function formatar(mascara, documento){
var i = documento.value.length;
var saida = mascara.substring(0,1);
var texto = mascara.substring(i);
if (texto.substring(0,1) != saida){
documento.value += texto.substring(0,1);
}
}
</script>
</head>
<body class="bg-dark">
<div id="container6" class="container-fluid">
<?php include 'topo.php'; ?>
<div class="d-flex justify-content-center">
<div class="card mt-2 grow mt-4" style="width: 600px">
<div class="card-header">
<div class="d-flex justify-content-center social_icon">
<span><i class="fas fa-clipboard fa-3x"></i></span>
<h5 class="mt-2 ml-2">Formulário de Pré-Encomenda</h5>
</div>
</div>
<div class="card-body">
<div id="resposta_ajax" class="alert" style="display:none"></div>
<form id="formEncomenda" enctype="multipart/form-data" class="form-group" method="post">
<div class="input-group form-group d-flex">
<div class="input-group-prepend">
<span class="input-group-text"><i class="far fa-user"></i></span>
</div>
<input type="text" name="nome" class="form-control" placeholder="<NAME> *" required>
</div>
<div class="input-group form-group d-flex">
<div class="input-group-prepend">
<span class="input-group-text"><i class="far fa-envelope"></i></span>
</div>
<input type="email" name="email" class="form-control" placeholder="E-mail *" required>
</div>
<div class="form-group d-flex row">
<div class="col input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text" style="height: 38px;"><i class="fa fa-mobile"></i></span>
</div>
<input type="tel" name="celular" class="form-control" placeholder="Celular" maxlength="13" pattern="[0-9]{2} [0-9]{5}-[0-9]{4}" OnKeyPress="formatar('## #####-####', this)">
</div>
<div class="col input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text" style="height: 38px;"><i class="fa fa-phone"></i></span>
</div>
<input type="tel" name="telefone" class="form-control" placeholder="Telefone" maxlength="12" pattern="[0-9]{2} [0-9]{4}-[0-9]{4}" OnKeyPress="formatar('## ####-####', this)">
</div>
</div>
<div class="input-group form-group d-flex">
<div class="input-group-prepend">
<span class="input-group-text"><i class="far fa-clipboard"></i></span>
</div>
<input type="text" class="form-control" disabled placeholder="Descrição do Ambiente *">
<textarea class="form-control z-depth-1" name="descricao" id="exampleFormControlTextarea6" style="border: solid 1px rgba(192,192,192,0.5);border-radius: 5px;" placeholder="Ex: Empresa, Universidade, Museu, Restaurante, etc.
No ambiente possuímos móveis com cores em madeira..." rows="2" maxlength="255" required></textarea>
</div>
<div class="form-group d-flex row">
<div class="col input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text" style="height: 38px;"><i class="fas fa-list-ol">*</i></span>
</div>
<input type="text" name="medida" class="form-control" placeholder="Medidas: Ex: 1,5 x 2,0 m" required>
</div>
<div class="col input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text" style="height: 38px;"><i class="fas fa-list-ol">*</i></span>
</div>
<input type="number" name="quantidade" class="form-control" min="1" placeholder="Quantidade" required>
</div>
</div>
<label>Envie uma foto do ambiente para obtermos mais detalhes</label>
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text" style="height: 30px;"><i class="far fa-folder-open"></i></span>
</div>
<input type="file" name="imagem" class="upload">
</div>
<p class="text-info">Todos com <span class="text-danger">* </span>são obrigatórios</p>
<div class="card-footers mb-2">
<div class="d-flex justify-content-end links">
<input type="submit" name="enviarEncomenda" style="font-weight: bold;" class="nav-link btn btn-outline-dark">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
<file_sep><?php
session_start();
if(isset($_SESSION['logado'])):
header('Location: adm.php');
exit;
endif;
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<!-- Meta tags Obrigatórias -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title><NAME></title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="<KEY> crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/LoginEstilo.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script>
$(document).ready(function() {
$('#formLogar').submit(function(event) {
event.preventDefault();
// seleciona o botão de submit
var botao = $(this).find('input[type="submit"]');
// desabilita o botão para evitar multiplos envio
botao.prop("disabled", true).val("Entrando..").css('opacity', '0.5');
data = $("#formLogar").serialize();
$.ajax({
type: "post",
url: "bd/logar.php",
data: data,
success: function( data ){
if(data === "sucesso"){
window.location="adm.php";
}else{
$("#resposta_ajax").addClass("alert alert-danger").html(data);
}
botao.prop("disabled", false).val("Entrar").css('opacity', '1');
}
});
});
$('#show_senha').click(function(e) {
e.preventDefault();
if ( $('#senha').attr('type') == 'password' ) {
$('#senha').attr('type', 'text');
$('#show_senha').attr('class', 'fa fa-eye');
} else {
$('#senha').attr('type', 'password');
$('#show_senha').attr('class', 'fa fa-eye-slash');
}
});
});
</script>
</head>
<style>
body,
html {
background-image: url('imagens/Foto9.png');
}
</style>
<body>
<?php include 'topo.php'; ?>
<div class="container-fluid">
<div class="container-fluid float-left" id="main">
<!------ Início Conteúdo ----->
<div class="d-flex justify-content-center h-100">
<div class="card h-100">
<div class="card-header">
<h3><img src="imagens/logo.png" style="width: 50px;" alt=""></h3>
</div>
<div class="card-body">
<div id="resposta_ajax"></div>
<br>
<form id="formLogar" method="post">
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-envelope"></i></span>
</div>
<input name="email" type="email" class="form-control" placeholder="Email" required>
</div>
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-key"></i></span>
</div>
<input name="senha" id="senha" type="password" class="form-control" placeholder="Senha" required autocomplete="off">
<button type="button" id="show_senha" name="show_senha" class="fa fa-eye-slash"></button>
</div>
<div class="row align-items-center remember">
<input type="checkbox" id="autoSizingCheck">Lembrar-me
</div>
<div class="form-group">
<input id="btnlogar" name="btnlogar" type="submit" value="Entrar" class="btn float-right login_btn">
</div>
</form>
</div>
<div class="card-footers mb-2">
<div class="d-flex justify-content-center">
<a href="esqueceuSenha.php">Esqueceu sua senha?</a>
</div>
</div>
</div>
</div>
<!------ Fim Conteúdo ----->
</div>
</div>
</body>
</html>
<file_sep><?php
session_start();
if(isset($_SESSION['perfil'])):
header('Location: adm.php');
exit;
endif;
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<!-- Meta tags Obrigatórias -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title><NAME></title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="<KEY> crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/LoginEstilo.css">
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#formesqueceusenha').submit(function(event) {
event.preventDefault();
// seleciona o botão de submit
var botao = $(this).find('input[type="submit"]');
// desabilita o botão para evitar multiplos envio
botao.prop("disabled", true).val("Enviando..").css('opacity', '0.5');
data = $("#formesqueceusenha").serialize();
$.ajax({
type: "post",
url: $(this).attr('action'),
dataType: "json",
data: data,
}).done(function(data){
alert(data.status);
$('#formesqueceusenha')[0].reset();
botao.prop("disabled", false).val("Enviar").css('opacity', '1');
});
});
});
</script>
</head>
<style>
body,
html {
background-image: url('imagens/Foto10.png');
}
</style>
<body>
<?php include 'topo_adm.php'; ?>
<div class="container-fluid">
<div class="container-fluid float-left" id="main">
<div class="d-flex justify-content-center h-100">
<div class="card">
<div class="card-body" style="background-color:#363636;">
<form id="formesqueceusenha" action="bd/envianovasenha.php">
<br><br>
<label class="text-center" style="color:white">Digite seu email abaixo e nós enviaremos um link para redefinir sua senha </label>
<br><br><br>
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-envelope"></i></span>
</div>
<input type="email" name="email" class="form-control" placeholder="Email" required>
</div>
<br><br><br>
<div class="form-group">
<input id="btnenviaremail" name="btnenviaremail" type="submit" value="Enviar" class="btn float-right login_btn">
</div>
</form>
</div>
</div>
</div>
<!------ Fim Modal Esqueceu senha ----->
</div>
</div>
</body>
</html>
<file_sep><!-- Topo -->
<header class="justify-content-between">
<nav class="navbar navbar-expand-md">
<div>
<img src="imagens/LOGO.png" style="max-width:40px" alt="">
</div>
<!-- Collapse button -->
<button class="navbar-toggler text-white close-btn" data-toggle="collapse" data-target="#nav">
<span class="navbar-toggler-icon"><i class="fas fa-bars fa-1x"></i></span>
</button>
<div class="collapse navbar-collapse justify-content-between align-items-center" id="nav">
<ul class="navbar-nav ml-auto text-center">
<li class="nav-item d-inline">
<a class="nav-link active text-light" href="index.php">Início</a>
</li>
<li class="nav-item d-inline">
<a class="nav-link text-light" href="galeria.php">Galeria</a>
</li>
<li class="nav-item d-inline">
<a class="nav-link text-light" href="pre_encomenda.php">Encomendar</a>
</li>
<?php if(isset($_SESSION['perfil'])){ ?>
<li class="nav-item d-inline">
<a class="nav-link text-light" href="adm.php">Administração</a>
</li>
<?php } ?>
</ul>
<ul class="navbar-nav ml-auto justify-content-end" style="text-align: center;">
<?php if(!isset($_SESSION['perfil'])){ ?>
<li class="nav-item">
<a id="cadastrese" class="nav-link btn btn-outline border border-white text-light" style="font-weight:bold" href="adm.php"><i class="fas fa-user-circle mr-2"></i>Login</a>
</li>
<?php }else{ ?>
<li class="nav-item">
<a class="text-warning mr-3" href="alterarSenha.php" style="font-weight:bold;"><i class="mr-2 text-warning fas fa-key"></i></a>
<a class="text-warning" href="logoff.php" style="font-weight:bold;"><i class="mr-2 text-warning fas fa-sign-out-alt"></i>Sair</a>
</li>
<?php } ?>
</ul>
</div>
</nav>
</header>
<!-- Fim Topo -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<file_sep><?php
session_start();
if(!isset($_SESSION['logado'])){
header('Location: login.php');
exit;
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<!-- Meta tags Obrigatórias -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title><NAME></title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="<KEY> crossorigin="anonymous">
<!-- Folha de Estilo -->
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/admStyle.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script>
$(document).ready(function() {
$('#formCadastro').submit(function(event) {
event.preventDefault();
// seleciona o botão de submit
var botao = $(this).find('input[type="submit"]');
// desabilita o botão para evitar multiplos envio
botao.prop("disabled", true).val("Cadastrando..").css('opacity', '0.5');
data = $("#formCadastro").serialize();
$.ajax({
type: "post",
url: "bd/gravar.php",
data: data,
success: function( data ){
if(data === "sucesso"){
$("#resposta_ajax").removeClass("alert-danger").addClass("alert-success").css('display', 'block').html("Cadastro realizado com sucesso");
$('#formCadastro')[0].reset();
} else{
$("#resposta_ajax").removeClass("alert-success").addClass("alert-danger").css('display', 'block').html(data);
}
botao.prop("disabled", false).val("Cadastrar").css('opacity', '1');
}
});
});
});
</script>
</head>
<body>
<?php include 'topo_adm.php'; ?>
<?php include 'dashboard.php'; ?>
<div class="container-fluid animated zoomIn">
<div class="container-fluid float-left" id="main">
<!------ Início Conteúdo ----->
<div class="d-flex justify-content-center h-100">
<div class="card mt-5 h-100 " style="width: 400px;">
<div class="card-header">
<div class="d-flex justify-content-center social_icon">
<span><i class="fas fa-fw fa-user fa-3x"></i></span>
<h5 class="mt-2 ml-2">Cadastrar Usuário</h5>
</div>
</div>
<div class="card-body">
<div id="resposta_ajax" class="alert" style="display:none"></div>
<form id="formCadastro" method="post">
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-user"></i></span>
</div>
<input type="text" name="nome" class="form-control" placeholder="Nome" required>
</div>
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-envelope"></i></span>
</div>
<input type="email" name="email" class="form-control" placeholder="Email" required>
</div>
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-key"></i></span>
</div>
<input type="password" name="senha" class="form-control" placeholder="Senha" minlength="6" maxlength="8" required autocomplete="off">
</div>
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-key"></i></span>
</div>
<input type="password" name="confirmasenha" class="form-control" placeholder="<NAME>" minlength="6" maxlength="8" required autocomplete="off">
</div>
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-address-card"></i></span>
</div>
<select class="form-control" name="perfil" required>
<option value="" disabled selected>- Selecione -</option>
<option value="Administrador">Administrador</option>
<option value="Funcionário">Funcionário</option>
</select>
</div>
<div class="card-footers mb-2">
<div class="d-flex justify-content-end links">
<input value="Cadastrar" name="btncadastro" type="submit" style="font-weight: bold;" class="btn btn-warning">
</div>
</div>
</form>
</div>
</div>
<!------ Fim Conteúdo ----->
</div>
</div>
</div>
</body>
</html>
<file_sep><?php
include_once 'conexao.php';
$sql = 'SELECT nome, comentario, DATEDIFF(NOW(), data_criacao) AS data, nota FROM comentarios WHERE relevante = 1 ORDER BY RAND() LIMIT 1';
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) == 1){
$comentario = mysqli_fetch_assoc($result);
echo json_encode($comentario);
} else{
echo "Nenhum registro encontrado";
}
?><file_sep><center><h1 class="mt-5">Olá, <?php echo $_SESSION['nome'];?>. Bem vindo a área de administração.</h1></center>
<div class="m-5" style="margin-top: 40px">
<div class="row">
<div class="col-xl-3 col-sm-6 mb-3">
<div class="card text-white bg-primary o-hidden h-100">
<div class="card-body">
<div class="card-body-icon">
<i class="fas fa-fw fa-users"></i>
</div>
<div class="mr-5">Usuários</div>
</div>
<a class="card-footer text-white clearfix small z-1" href="listaUsuario.php">
<span class="float-left">Mais detalhes</span>
<span class="float-right">
<i class="fas fa-angle-right"></i>
</span>
</a>
</div>
</div>
<div class="col-xl-3 col-sm-6 mb-3">
<div class="card text-white bg-dark o-hidden h-100">
<div class="card-body">
<div class="card-body-icon">
<i class="fas fa-fw fa-list"></i>
</div>
<div class="mr-5">Clientes interessados</div>
</div>
<a class="card-footer text-white clearfix small z-1" href="listaEncomendas.php">
<span class="float-left">Mais detalhes</span>
<span class="float-right">
<i class="fas fa-angle-right"></i>
</span>
</a>
</div>
</div>
<div class="col-xl-3 col-sm-6 mb-3">
<div class="card text-white bg-secondary o-hidden h-100">
<div class="card-body">
<div class="card-body-icon">
<i class="fas fa-fw fa-comments"></i>
</div>
<div class="mr-5">Comentários</div>
</div>
<a class="card-footer text-white clearfix small z-1" href="listaComentarios.php">
<span class="float-left">Mais detalhes</span>
<span class="float-right">
<i class="fas fa-angle-right"></i>
</span>
</a>
</div>
</div>
<div class="col-xl-3 col-sm-6 mb-3">
<div class="card text-white bg-info o-hidden h-100">
<div class="card-body">
<div class="card-body-icon">
<i class="fas fa-image"></i>
</div>
<div class="mr-5">Gerenciador de Galeria</div>
</div>
<a class="card-footer text-white clearfix small z-1" href="gerenciadorGaleria.php">
<span class="float-left">Mais detalhes</span>
<span class="float-right">
<i class="fas fa-angle-right"></i>
</span>
</a>
</div>
</div>
</div>
</div><file_sep><?php
session_start();
if(isset($_POST['nome'])){
include 'conexao.php';
$nome = $_POST['nome'];
$email = $_POST['email'];
$senha = sha1($_POST['senha']);
$confirmasenha = sha1($_POST['confirmasenha']);
$perfil = $_POST['perfil'];
if(empty($nome) || empty($email) || empty($senha) || empty($confirmasenha) || empty($perfil)){
echo "Verifique se todos os campos obrigatórios foram preenchidos";
} else{
$sql_verificaemail = mysqli_query($con, "SELECT * FROM usuarios WHERE email = '$email'");
if(mysqli_num_rows($sql_verificaemail)!=1){
//Verifica se as senhas são iguais
if($senha == $confirmasenha){
//Insere no banco todos os dados informados
$sql_cadastro = "INSERT INTO usuarios VALUES(null, '{$nome}', '{$email}', '{$senha}', '{$perfil}', 'null', 'null')";
if(mysqli_query($con, $sql_cadastro)){
echo "sucesso";
}else{
echo "Erro ao conectar com o banco";
}
}else{
echo "Senhas diferentes";
}
}else{
echo "Email já existe. Tente outro.";
}
}
mysqli_close($con);
}
?><file_sep><?php
session_start();
if(isset($_POST['status']) && isset($_POST['id'])){
include_once 'conexao.php';
$id = $_POST['id'];
$status = $_POST['status'];
$sql = "UPDATE encomenda SET respondida = $status WHERE id = $id";
if(mysqli_query($con, $sql)){
if($status == 1){
echo "A encomenda $id foi marcada como respondida";
}else{
echo "A encomenda $id foi marcada como não respondida";
}
}
mysqli_close($con);
}
?><file_sep><?php
session_start();
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<!-- Meta tags Obrigatórias -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="<KEY> crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/LoginEstilo.css">
<title><NAME></title>
</head>
<style>
body,
html {
background-image: url('imagens/Foto10.png');
}
</style>
<body>
<?php
//Guarda na variável chave a chave que veio da url caso exista uma chave
$chave_confirmacao = isset($_GET["chave"]) ? $_GET["chave"] : "null";
include 'bd/conexao.php';
//Verifica se a chave da url existe no banco
$verificachave = mysqli_query($con, "SELECT * FROM encomenda WHERE chave_confirmacao = '$chave_confirmacao'");
//Caso a condição acima seja verdadeira, verifca se o link e válido e dá acesso ao usuário, caso não contrário, diz que a página não foi encontrada
if(mysqli_num_rows($verificachave) == 1){
//Verifica no banco se o link ainda é válido
$verificalink = mysqli_query($con, "SELECT * FROM encomenda WHERE chave_confirmacao = '$chave_confirmacao' AND data_expiracao_confirmacao >= NOW()");
//Se a condição acima for verdadeira, exibe a página
if(mysqli_num_rows($verificalink) == 1){
mysqli_query($con, "UPDATE encomenda SET confirmado = 1 WHERE chave_confirmacao = '$chave_confirmacao'");
?>
<?php include 'topo_adm.php'; ?>
<div class="container-fluid">
<div class="container-fluid float-left" id="main">
<!------ Início Conteúdo ----->
<div class="d-flex justify-content-center h-100">
<div class="card">
<div class="card-body" style="background-color:#363636;">
<br>
<p class="text-center mt-5" style="color:white"><b>Interesse confirmado com sucesso.</b></p>
<p class="text-center mt-5" style="color:white"><b>Aguarde que em breve entraremos em contato.</b></p>
</div>
</div>
</div>
<!------ Fim Conteúdo ----->
</div>
</div>
<?php
} else{
echo "<script language='javascript' type='text/javascript'>
alert('Link inválido');</script>";
}
} else{
echo "<h1>Página não encontrada</h1>";
}
?>
<!-- JavaScript (Opcional) -->
<!-- jQuery primeiro, depois Popper.js, depois Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html>
<file_sep><?php
include 'conexao.php';
$senhanova = sha1($_POST['senhanova']);
$confirmasenhanova = sha1($_POST['confirmasenhanova']);
$id = $_POST["id"];
if(empty($senhanova) || empty($confirmasenhanova)){
echo "Verifique se todos os campos obrigatórios foram preenchidos";
} else{
//Verifica se as senhas são iguais
if($senhanova == $confirmasenhanova){
//Grava a nova senha no banco de dados
$alterasenha = "UPDATE usuarios SET senha = '$<PASSWORD>' WHERE id_usuario = '$id'";
if(mysqli_query($con, $alterasenha)){
echo "sucesso";
}else{
echo "Erro ao connectar com o banco";
}
} else{
echo "Senhas diferentes";
}
}
mysqli_close($con);
?><file_sep>-- phpMyAdmin SQL Dump
-- version 4.9.0.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Tempo de geração: 18-Out-2019 às 01:32
-- Versão do servidor: 10.4.6-MariaDB
-- versão do PHP: 7.3.9
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Banco de dados: `mauricioluminarias`
--
CREATE DATABASE mauricioluminarias;
--
-- Estrutura da tabela `clientes`
--
use mauricioluminarias;
CREATE TABLE `clientes` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`nome` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`telefone` varchar(15) DEFAULT NULL,
`celular` varchar(15) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
CREATE TABLE `comentarios` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`nome` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`comentario` varchar(255) DEFAULT NULL,
`nota` int(11) DEFAULT NULL,
`data_criacao` datetime NOT NULL,
`relevante` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
CREATE TABLE `fotos` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`imagem` varchar(100) NOT NULL,
`tipo` varchar(100) NOT NULL,
`descricao` varchar(100) DEFAULT NULL,
`usuario_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `fotos`
ADD KEY `usuario_id` (`usuario_id`);
-- --------------------------------------------------------
CREATE TABLE `encomenda` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`descricao` varchar(255) NOT NULL,
`medida` varchar(100) NULL,
`qtd` int(11) NULL,
`fotoambiente` varchar(200) DEFAULT NULL,
`cliente_id` int(11) NOT NULL,
`chave_confirmacao` varchar(20) NOT NULL,
`data_expiracao_confirmacao` datetime NOT NULL,
`confirmado` tinyint(1) NOT NULL,
`respondida` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `encomenda`
ADD KEY `encomenda_ibfk_1` (`cliente_id`);
ALTER TABLE `encomenda`
ADD CONSTRAINT `encomenda_ibfk_1` FOREIGN KEY (`cliente_id`) REFERENCES `clientes` (`id`);
COMMIT;
-- --------------------------------------------------------
CREATE TABLE `usuarios` (
`id_usuario` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`nome` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
`senha` varchar(100) NOT NULL,
`perfil` enum('Administrador','Funcionário') NOT NULL,
`chave_senha` varchar(20) NOT NULL,
`data_expiracao_senha` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `usuarios` (`id_usuario`, `nome`, `email`, `senha`, `perfil`) VALUES
(1, 'admin', '<EMAIL>', '<PASSWORD>', 'Administrador');
ALTER TABLE `fotos`
ADD CONSTRAINT `fotos_ibfk_1` FOREIGN KEY (`usuario_id`) REFERENCES `usuarios` (`id_usuario`);
-- insert into fotos values(null,'Foto3.png','png',null,1);
-- insert into fotos values(null,'Foto4.png','png',null,1);
-- insert into fotos values(null,'Foto5.png','png',null,1);
-- insert into fotos values(null,'Foto6.png','png',null,1);
-- insert into fotos values(null,'Foto7.png','png',null,1);
-- insert into fotos values(null,'Foto8.png','png',null,1);
-- insert into fotos values(null,'Foto9.png','png',null,1);
-- insert into fotos values(null,'Foto10.png','png',null,1);
-- insert into fotos values(null,'Foto11.png','png',null,1);
-- insert into fotos values(null,'Foto12.png','png',null,1);
-- insert into fotos values(null,'Foto13.png','png',null,1);
-- insert into fotos values(null,'Foto14.png','png',null,1);
-- insert into fotos values(null,'Foto2.1.png','png',null,1);
<file_sep><?php
session_start();
if(!isset($_SESSION['logado'])){
header('Location: login.php');
exit;
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<!-- Meta tags Obrigatórias -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY> crossorigin="anonymous">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="<KEY> crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css">
<!-- Folha de Estilo -->
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/admStyle.css">
<title><NAME></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script>
$(document).ready(function() {
$('#formEditaUsuario').submit(function(event) {
event.preventDefault();
// seleciona o botão de submit
var botao = $(this).find('input[type="submit"]');
var id = $("#id").val();
// desabilita o botão para evitar multiplos envio
botao.prop("disabled", true).val("Enviando..").css('opacity', '0.5');
data = $("#formEditaUsuario").serialize();
$.ajax({
type: "post",
url: "bd/editaUsuario.php",
data: data + '&id_usuario=' + id,
success: function(data) {
if(data === "sucesso"){
$("#resposta_ajax").removeClass("alert-danger").addClass("alert-success").css('display', 'block').html("Alterações realizadas com sucesso");
} else{
$("#resposta_ajax").removeClass("alert-success").addClass("alert-danger").css('display', 'block').html(data);
}
botao.prop("disabled", false).val("Atualizar").css('opacity', '1');
}
});
});
});
</script>
</head>
<body>
<?php
include 'topo_adm.php';
include 'dashboard.php';
if(isset($_GET['id'])){
$id = $_GET['id'];
include 'bd/conexao.php';
$sql = "SELECT * FROM usuarios WHERE id_usuario=".$id;
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_array($result);
}
?>
<div class="container-fluid animated zoomIn">
<div class="container-fluid float-left">
<div class="d-flex justify-content-center h-100">
<div class="card mt-5 h-100" style="width: 400px;">
<div class="card-header">
<div class="d-flex justify-content-center social_icon">
<span><i class="fas fa-fw fa-user fa-3x"></i></span>
<h5 class="mt-2 ml-2">Editar Usuário</h5>
</div>
</div>
<div class="card-body">
<div id="resposta_ajax" class="alert" style="display:none"></div>
<form id="formEditaUsuario" method="post">
<input id="id" type="hidden" value="<?php echo $row['id_usuario'];?>">
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-user"></i></span>
</div>
<input type="text" name="nome" class="form-control" value="<?php echo $row['nome'];?>" required>
</div>
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-envelope"></i></span>
</div>
<input type="email" name="email" class="form-control" value="<?php echo $row['email'];?>" required>
</div>
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-address-card"></i></span>
</div>
<select class="form-control" name="perfil" required>
<option value="" disabled selected>- Selecione -</option>
<option value="Administrador">Administrador</option>
<option value="Funcionário">Funcionário</option>
</select>
</div>
<div class="card-footers mb-2">
<div class="d-flex justify-content-end links">
<input name="btneditar" type="submit" class="btn btn-warning" value="Atualizar">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<file_sep><?php
session_start();
if(!isset($_SESSION['logado'])){
header('Location: login.php');
exit;
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<!-- Meta tags Obrigatórias -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title><NAME></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="<KEY> crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
<script>
function format (d) {
// `d` is the original data object for the row
return '<tr>'+
'<td>'+d+'</td>'+
'</tr>';
}
$(document).ready(function() {
var table = $('#listar-comentarios').DataTable({
responsive: true,
"scrollX": true,
"columnDefs": [
{ "width": "100px", "targets": 0 },
{ "width": "100px", "targets": 1 },
{ "width": "200px", "targets": 2 },
{ "width": "400px", "targets": 3 },
{ "width": "100px", "targets": 4 },
{ "width": "100px", "targets": 5 },
],
"language": {
"url": "//cdn.datatables.net/plug-ins/1.10.20/i18n/Portuguese-Brasil.json"
}
});
$('#listar-comentarios').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
row.child(format(tr.data('child-value'))).show();
tr.addClass('shown');
}
});
$("input[name='status']").click(function(){
var status = $(this).prop('checked') ? 1 : 0;
var id = $(this).val();
var cod = $(this).parent().parent().find(':nth-child(2)').html();
$.ajax({
url: 'bd/atualizarRelevancia.php',
type: 'POST',
data: 'status='+status+'&id='+id+'&cod='+cod,
success: function( data ){
$("#resposta_ajax").addClass("alert alert-success").css('display', 'block').html(data);
}
});
});
});
</script>
</head>
<style>
table{
table-layout: fixed;
word-wrap:break-word;
}
</style>
<body>
<?php include 'topo_adm.php'; ?>
<?php include 'dashboard.php'; ?>
<div class="container animated zoomIn">
<div class="card mt-5 grow" style="width: 100%;">
<div class="card-header">
<div class="d-flex justify-content-center social_icon">
<span><i class="fas fa-fw fa-comments fa-3x"></i></span>
<h5 class="mt-2 ml-2">Lista de Comentários</h5>
</div>
</div>
<?php
include_once 'bd/conexao.php';
$sql = "SELECT * FROM comentarios ORDER BY data_criacao DESC";
$result = mysqli_query($con, $sql);
$totalRegistros = mysqli_num_rows($result);
if($totalRegistros > 0){?>
<div class="card-body">
<div id="resposta_ajax" class="alert" style="display:none"></div>
<form action="" method="post" >
<table id="listar-comentarios" class="table hover" cellspacing="0" style="width:100%">
<thead class="text-light" style="background-color:#343a40">
<tr>
<th></th>
<th>Cod</th>
<th>Nome</th>
<th>Comentário</th>
<th>Nota</th>
<th>Relevante</th>
</tr>
</thead>
<tbody>
<?php
$cont = 1;
while($row = mysqli_fetch_array($result)){
$id = $row['id'];
$data = date('d/m/Y H:i:s',strtotime($row['data_criacao']));
$email = $row['email'];
?>
<tr data-child-value="Email: <?php echo $email ?> <br>Data de Criação: <?php echo $data ?>">
<td class="details-control"><i class="fas fa-caret-down"></i></td>
<td><?php echo $cont ?></td>
<td><?php echo $row['nome'] ?></td>
<td><?php echo $row['comentario'] ?></td>
<td><?php echo $row['nota'] ?></td>
<td>
<input type="checkbox" name="status" value="<?php echo $id ?>" <?php if($row['relevante'] == 1){echo 'checked="checked"';} ?>/>
</td>
</tr>
<?php
$cont++;
}
?>
</tbody>
</table>
</form>
<?php
}else{
echo "Nenhum registro encontrado!";
}
mysqli_close($con);
?>
</div>
</div>
</div>
</body>
</html><file_sep><?php
session_start();
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<!-- Meta tags Obrigatórias -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="<KEY>="anonymous">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/LoginEstilo.css">
<title>Maurício Luminárias</title>
</head>
<style>
body,
html {
background-image: url('imagens/Foto10.png');
}
</style>
<body>
<?php include 'topo_adm.php'; ?>
<div class="container-fluid">
<div class="container-fluid float-left" id="main">
<!------ Início Conteúdo ----->
<div class="d-flex justify-content-center h-100">
<div class="card">
<div class="card-body" style="background-color:#363636;">
<br>
<p class="text-center mt-5" style="color:white"><b>Obrigado pelo seu interesse em nossas luminárias.</b></p>
<p class="text-center mt-5" style="color:white"><b>Para confirmar sua encomenda clique no link enviado para seu email.</b></p>
</div>
</div>
</div>
<!------ Fim Conteúdo ----->
</div>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html>
<file_sep><?php
session_start();
if(!isset($_SESSION['perfil'])){
header('Location: login.php');
exit;
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<!-- Meta tags Obrigatórias -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY> crossorigin="anonymous">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="<KEY> crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css">
<!-- Folha de Estilo -->
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/admStyle.css">
<title><NAME></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script>
$(document).ready(function() {
$('#formAlterarSenha').submit(function(event) {
event.preventDefault();
// seleciona o botão de submit
var botao = $(this).find('input[type="submit"]');
var id = $("#id").val();
// desabilita o botão para evitar multiplos envio
botao.prop("disabled", true).val("Enviando..").css('opacity', '0.5');
data = $("#formAlterarSenha").serialize();
$.ajax({
type: "post",
url: "bd/alteraSenha.php",
data: data + '&id=' + id,
success: function(data) {
if(data === "sucesso"){
$("#resposta_ajax").removeClass("alert-danger").addClass("alert-success").css('display', 'block').html("Senha alterada com sucesso");
$('#formAlterarSenha')[0].reset();
} else{
$("#resposta_ajax").removeClass("alert-success").addClass("alert-danger").css('display', 'block').html(data);
}
botao.prop("disabled", false).val("Alterar").css('opacity', '1');
}
});
});
});
</script>
</head>
<body>
<?php include 'topo_adm.php'; ?>
<div class="container-fluid animated zoomIn">
<div class="container-fluid float-left">
<div class="d-flex justify-content-center h-100">
<div class="card mt-5 h-100" style="width: 400px;">
<div class="card-header">
<div class="d-flex justify-content-center social_icon">
<span><i class="fas fa-fw fa-key fa-3x"></i></span>
<h5 class="mt-2 ml-2">Alterar Senha</h5>
</div>
</div>
<div class="card-body">
<div id="resposta_ajax" class="alert" style="display:none"></div>
<form id="formAlterarSenha" method="post">
<input id="id" type="hidden" value="<?php echo $_SESSION['id'];?>">
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-key"></i></span>
</div>
<input name="senhanova" type="password" class="form-control" placeholder="<PASSWORD>" required minlength="6" maxlength="8">
</div>
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-key"></i></span>
</div>
<input name="confirmasenhanova" type="password" class="form-control" placeholder="<NAME>" required minlength="6" maxlength="8">
</div>
<div class="card-footers mb-2">
<div class="d-flex justify-content-end links">
<input name="btneditar" type="submit" class="btn btn-warning" value="Alterar">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html><file_sep><?php
session_start();
if(!isset($_SESSION['logado'])){
header('Location: login.php');
exit;
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<!-- Meta tags Obrigatórias -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title><NAME></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="<KEY> crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
<script>
function format (d) {
// `d` is the original data object for the row
return '<tr>'+
'<td>'+d+'</td>'+
'</tr>';
}
$(document).ready(function() {
var table = $('#listar-encomendas').DataTable({
responsive: true,
"scrollX": true,
"columnDefs": [
{ "width": "100px", "targets": 0 },
{ "width": "100px", "targets": 1 },
{ "width": "150px", "targets": 2 },
{ "width": "200px", "targets": 3 },
{ "width": "300px", "targets": 4 },
{ "width": "150px", "targets": 5 },
],
"language": {
"url": "//cdn.datatables.net/plug-ins/1.10.20/i18n/Portuguese-Brasil.json"
},
});
$('#listar-encomendas').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
row.child(format(tr.data('child-value'))).show();
tr.addClass('shown');
}
});
$("input[name='status']").click(function(){
var status = $(this).prop('checked') ? 1 : 0;
var id = $(this).val();
var cod = $(this).parent().parent().find(':nth-child(1)').html();
$.ajax({
url: 'bd/encomendaRespondida.php',
type: 'POST',
data: 'status='+status+'&id='+id,
success: function( data ){
$("#resposta_ajax").addClass("alert alert-success").css('display', 'block').html(data);
}
});
});
});
</script>
</head>
<style>
table{
table-layout: fixed;
word-wrap:break-word;
}
</style>
<body>
<?php include 'topo_adm.php'; ?>
<?php include 'dashboard.php'; ?>
<div class="container animated zoomIn" >
<div class="card mt-5 grow" style="width: 100%;">
<div class="card-header">
<div class="d-flex justify-content-center social_icon">
<span><i class="fas fa-fw fa-list fa-3x"></i></span>
<h5 class="mt-2 ml-2">Lista de Interesses</h5>
</div>
</div>
<?php
include_once 'bd/conexao.php';
$sql = "SELECT c1.*, c2.* FROM clientes c1 INNER JOIN encomenda c2
ON c1.id = c2.cliente_id ORDER BY c2.confirmado DESC";
$result = mysqli_query($con, $sql);
$totalRegistros = mysqli_num_rows($result);
if($totalRegistros > 0){?>
<div class="card-body">
<div id="resposta_ajax" class="alert" style="display:none"></div>
<form action="" method="post">
<table id="listar-encomendas" class="table hover" cellspacing="0" style="width:100%">
<thead class="text-light" style="background-color:#343a40">
<th></th>
<th>Nº</th>
<th>Nome</th>
<th>E-mail</th>
<th>Foto</th>
<th>Respondido</th>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_array($result)){
$id = $row['id'];
$descricao = $row['descricao'];
$telefone = $row['telefone'];
$celular = $row['celular'];
$medida = $row['medida'];
$qtd = $row['qtd'];
$confirmado = $row['confirmado'];
?>
<tr data-child-value="Telefone: <?php echo $telefone ?> <br>Celular: <?php echo $celular ?> <br>Medida: <?php echo $medida ?> <br>Quantidade: <?php echo $qtd ?> <br>Descrição: <?php echo $descricao ?> <br>Confirmado: <?php echo ($confirmado == 1) ? "Sim" : "Não"; ?>">
<td class="details-control"><i class="fas fa-caret-down"></i></td>
<td><?php echo $id ?></td>
<td><?php echo $row['nome'] ?></td>
<td><a href="mailto:<?php echo $row['email'] ?>?body=Olá, <?php echo $row['nome'] ?>.%0A%0ANós da <NAME> estamos entranto em contato referente ao formulário preenchido em nosso site com os seguintes dados:%0A%0ADescrição: <?php echo $descricao ?>%0AMedida: <?php echo $medida ?>%0AQuantidade: <?php echo $qtd ?>%0AFoto: <?php echo $row['fotoambiente'] ?>%0A%0A"><?php echo $row['email'] ?></a></td>
<td>
<?php
if(!empty($row['fotoambiente'])){?>
<figure>
<img src="<?php echo isset($row['fotoambiente']) ? 'encomenda/'. $row['fotoambiente'] : "" ?>" style="width:100px;" />
<figcaption><?php echo $row['fotoambiente'] ?></figcaption>
</figure>
<?php
}?>
</td>
<td>
<input type="checkbox" name="status" value="<?php echo $id ?>" <?php if($row['respondida'] == 1){echo 'checked="checked"';} ?>/>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</form>
<?php
}else{
echo "Nenhum registro encontrado!";
}
mysqli_close($con);
?>
</div>
</div>
</div>
</body>
</html><file_sep><?php
session_start();
$id = $_SESSION['id'];
echo $id ."<br>" ;
include_once('../funcoesPHP.php');
include_once('conexao.php');
if(isset($_FILES['imagem'])){
$imagem = $_FILES["imagem"];
$descricao = $_POST['descricao'];
echo $descricao;
$destino = '../galeria/' . $_FILES['imagem']['name'];
$nome = $_FILES['imagem'][ 'name' ];
$tipo = $_FILES['imagem']['type'];
// Pega a extensão
$extensao = pathinfo ( $nome, PATHINFO_EXTENSION );
// Converte a extensão para minúsculo
$extensao = strtolower ( $extensao );
if (strstr('.jpg;.jpeg;.gif;.png', $extensao)){
// Concatena a pasta com o nome
$destino = '../galeria/' . $nome;
// tenta mover o arquivo para o destino
if (move_uploaded_file($_FILES['imagem']['tmp_name'], $destino)) {
$sql = "INSERT INTO fotos values (null,'{$nome}','png','{$descricao}',1)";
if (mysqli_query($con,$sql)){
header('location: ../gerenciadorGaleria.php?status=1');
}else{
header('location: ../gerenciadorGaleria.php?status=2');
// echo ($sql);
// echo "ERRO: " . mysqli_error($con) . "\n";
}
}else{
header('location: ../gerenciadorGaleria.php?status=3');
}
}else{
header('location: ../gerenciadorGaleria.php?status=4');
}
}else{
header('location:../gerenciadorGaleria.php?status=5');
}
?><file_sep><?php
$con = mysqli_connect("localhost", "root", "", "mauricioluminarias"); //1 - onde o banco está, 2 - usuário, 3 - senha, 4 - nome do banco
mysqli_set_charset($con, "utf8");
?><file_sep><?php
include 'conexao.php';
$id = $_GET['id'];
$deletar = "DELETE FROM fotos WHERE id = $id";
$query = mysqli_query($con,"SELECT * FROM fotos WHERE id = $id");
$buscar = mysqli_fetch_array($query);
if(mysqli_query($con,$deletar)){
unlink('../galeria/' . $buscar['imagem']);
header("location: ../gerenciadorGaleria.php?status=5");
}else{
header("location: ../gerenciadorGaleria.php?status=6");
}
?><file_sep><?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>MaurícioLuminárias</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="<KEY> crossorigin="anonymous">
<!-- Folha de Estilo -->
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" href="css/gallery-grid.css">
<link href="https://cdn.rawgit.com/sachinchoolur/lightgallery.js/master/dist/css/lightgallery.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<style>
body{
background-color:#4F4F4F;
}
.demo-gallery > ul {
margin-bottom: 0;
}
.demo-gallery > ul > li {
float: left;
margin-bottom: 15px;
margin-right: 20px;
width: 200px;
}
.demo-gallery > ul > li a {
border: 3px solid #FFF;
border-radius: 3px;
display: block;
overflow: hidden;
position: relative;
float: left;
}
.demo-gallery > ul > li a > img {
-webkit-transition: -webkit-transform 0.15s ease 0s;
-moz-transition: -moz-transform 0.15s ease 0s;
-o-transition: -o-transform 0.15s ease 0s;
transition: transform 0.15s ease 0s;
-webkit-transform: scale3d(1, 1, 1);
transform: scale3d(1, 1, 1);
height: 100%;
width: 100%;
}
.demo-gallery > ul > li a:hover > img {
-webkit-transform: scale3d(1.1, 1.1, 1.1);
transform: scale3d(1.1, 1.1, 1.1);
}
.demo-gallery > ul > li a:hover .demo-gallery-poster > img {
opacity: 1;
}
.demo-gallery > ul > li a .demo-gallery-poster {
background-color: rgba(0, 0, 0, 0.1);
bottom: 0;
left: 0;
position: absolute;
right: 0;
top: 0;
-webkit-transition: background-color 0.15s ease 0s;
-o-transition: background-color 0.15s ease 0s;
transition: background-color 0.15s ease 0s;
}
.demo-gallery > ul > li a .demo-gallery-poster > img {
left: 50%;
margin-left: -10px;
margin-top: -10px;
opacity: 0;
position: absolute;
top: 50%;
-webkit-transition: opacity 0.3s ease 0s;
-o-transition: opacity 0.3s ease 0s;
transition: opacity 0.3s ease 0s;
}
.demo-gallery > ul > li a:hover .demo-gallery-poster {
background-color: rgba(0, 0, 0, 0.5);
}
.demo-gallery .justified-gallery > a > img {
-webkit-transition: -webkit-transform 0.15s ease 0s;
-moz-transition: -moz-transform 0.15s ease 0s;
-o-transition: -o-transform 0.15s ease 0s;
transition: transform 0.15s ease 0s;
-webkit-transform: scale3d(1, 1, 1);
transform: scale3d(1, 1, 1);
height: 100%;
width: 100%;
}
.demo-gallery .justified-gallery > a:hover > img {
-webkit-transform: scale3d(1.1, 1.1, 1.1);
transform: scale3d(1.1, 1.1, 1.1);
}
.demo-gallery .justified-gallery > a:hover .demo-gallery-poster > img {
opacity: 1;
}
.demo-gallery .justified-gallery > a .demo-gallery-poster {
background-color: rgba(0, 0, 0, 0.1);
bottom: 0;
left: 0;
position: absolute;
right: 0;
top: 0;
-webkit-transition: background-color 0.15s ease 0s;
-o-transition: background-color 0.15s ease 0s;
transition: background-color 0.15s ease 0s;
}
.demo-gallery .justified-gallery > a .demo-gallery-poster > img {
left: 50%;
margin-left: -10px;
margin-top: -10px;
opacity: 0;
position: absolute;
top: 50%;
-webkit-transition: opacity 0.3s ease 0s;
-o-transition: opacity 0.3s ease 0s;
transition: opacity 0.3s ease 0s;
}
.demo-gallery .justified-gallery > a:hover .demo-gallery-poster {
background-color: rgba(0, 0, 0, 0.5);
}
.demo-gallery .video .demo-gallery-poster img {
height: 48px;
margin-left: -24px;
margin-top: -24px;
opacity: 0.8;
width: 48px;
}
.demo-gallery.dark > ul > li a {
border: 3px solid #04070a;
}
.home .demo-gallery {
padding-bottom: 80px;
}
</style>
</head>
<body class="">
<?php include 'topo.php'; ?>
<div class="container gallery-container text-center">
<h1 class="text-dark pt-5">Galeria de Fotos</h1>
<p class="text-center"><a href="pre_encomenda.php">Clique aqui</a> para fazer a sua encomenda</p>
<div class="tz-gallery">
<div class="demo-gallery">
<ul id="lightgallery" class="list-unstyled row d-flex justify-content-center">
<?php
include 'bd/conexao.php';
$sql = "select * from fotos";
$sql2 = "select count(id) from fotos";
$busca = mysqli_query($con, $sql);
$total = mysqli_num_rows($busca);
while($array = mysqli_fetch_array($busca)){
$id = $array['id'];
$imagem = 'galeria/' . $array['imagem'];
$descricao = $array['descricao'];
?>
<li class="col-xs-5 col-sm-3 col-md-3" data-responsive="<?php echo $imagem ?> 375,<?php echo $imagem ?> 480, <?php echo $imagem ?> 800," data-src="<?php echo $imagem ?>" data-sub-html="<h4><?php echo $descricao ?></>" data-pinterest-text="Pin it1" data-tweet-text="share on twitter 1">
<a href="">
<img class="img-responsive" src="<?php echo $imagem ?>" alt="Thumb-4">
</a>
</li>
<?php } ?>
</ul>
</div>
</div>
</div>
</body>
<script src="https://cdn.jsdelivr.net/picturefill/2.3.1/picturefill.min.js"></script>
<script src="https://cdn.rawgit.com/sachinchoolur/lightgallery.js/master/dist/js/lightgallery.js"></script>
<script src="https://cdn.rawgit.com/sachinchoolur/lg-pager.js/master/dist/lg-pager.js"></script>
<script src="https://cdn.rawgit.com/sachinchoolur/lg-autoplay.js/master/dist/lg-autoplay.js"></script>
<script src="https://cdn.rawgit.com/sachinchoolur/lg-fullscreen.js/master/dist/lg-fullscreen.js"></script>
<script src="https://cdn.rawgit.com/sachinchoolur/lg-zoom.js/master/dist/lg-zoom.js"></script>
<script src="https://cdn.rawgit.com/sachinchoolur/lg-hash.js/master/dist/lg-hash.js"></script>
<script src="https://cdn.rawgit.com/sachinchoolur/lg-share.js/master/dist/lg-share.js"></script>
<script>
lightGallery(document.getElementById('lightgallery'));
</script>
<script>
$('.coracao').on('click',(e) => {
$(e.target).closest($('.coracao')).toggleClass('far');
$(e.target).closest($('.coracao')).toggleClass('fas');
});
</script>
</html><file_sep><?php
session_start();
if(isset($_POST['nome']) && isset($_POST['id'])){
include_once 'conexao.php';
$nome = $_POST['nome'];
$id = $_POST['id'];
$sql = "DELETE FROM usuarios where id_usuario = $id";
if(mysqli_query($con, $sql)){
echo "Usuário $nome deletado com sucesso";
}
mysqli_close($con);
}
?>
<file_sep><?php
session_start();
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<!-- Meta tags Obrigatórias -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY> crossorigin="anonymous">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="<KEY> crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css">
<!-- Folha de Estilo -->
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/admStyle.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<title>Maurício Luminárias</title>
<script>
function excluir(id){
if(confirm('Deseja realmente excluir esta foto?')){
location.href = 'bd/deletarFoto.php?id=' + id;
}
}
</script>
</head>
<body>
<?php include 'topo_adm.php'; ?>
<?php include 'dashboard.php'; ?>
<div class="container animated zoomIn">
<?php
if(empty($_GET['status']) != 1 && $_GET['status'] == '1'){
?>
<div class="alert alert-success" role="alert">
Sua foto foi inserida com sucesso!
</div>
<?php
}elseif(empty($_GET['status']) != 1 && $_GET['status'] == '2'){
?>
<div class="alert alert-danger" role="alert">
Ops, houve um problema ao inserir a imagem no nosso banco de dados
</div>
<?php
}elseif(empty($_GET['status']) != 1 && $_GET['status'] == '3'){
?>
<div class="alert alert-danger" role="alert">
Ops, houve um problema ao mover a imagem
</div>
<?php
}elseif(empty($_GET['status']) != 1 && $_GET['status'] == '4'){
?>
<div class="alert alert-danger" role="alert">
Ops, Arquivo não suportado
</div>
<?php
}elseif(empty($_GET['status']) != 1 && $_GET['status'] == '5'){
?>
<div class="alert alert-success" role="alert">
Sua foto foi deletada com sucesso.
</div>
<?php
}elseif(empty($_GET['status']) != 1 && $_GET['status'] == '6'){
?>
<div class="alert alert-danger" role="alert">
Ops, houve um erro ao deletar sua foto.
</div>
<?php
}
?>
<div class="card mt-5 grow" style="width: 100%;">
<div class="card-header">
<div class="d-flex justify-content-center social_icon">
<span><i class="fas fa-images fa-3x"></i></span>
<h5 class="mt-2 ml-2">Lista de Fotos</h5>
</div>
</div>
<div class="card-body">
<form id="formcadastro" enctype="multipart/form-data" class="form-group" action="bd/inserirFotosGaleria.php" method="post">
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text" style="height: 30px;"><i class="far fa-folder-open"></i></span>
</div>
<input type="file" name="imagem" class="upload" >
</div>
<div class="input-group d-flex">
<div class="input-group-prepend">
<span class="input-group-text"><i class="far fa-clipboard"></i></span>
</div>
<input type="text" class="form-control" disabled placeholder="Descrição da Imagem">
<textarea class="form-control z-depth-1" name="descricao" id="exampleFormControlTextarea6" style="border: solid 1px; border-radius: 5px;" rows="1"></textarea>
</div>
<div class="card-footers mb-2">
<div class="d-flex justify-content-end links">
<input type="submit" style="font-weight: bold;" class="nav-link btn btn-outline-dark mt-2">
</div>
</div>
</form>
</div>
</div>
</div>
<div class="container mt-5 animated zoomIn" >
<table class="table border ">
<thead class="text-center thead-dark">
<tr style="font-size:20px;">
<th scope="col">Imagem</th>
<th scope="col">Descrição</th>
<th scope="col">Excluir</th>
</tr>
</thead>
<tbody class="text-center">
<?php
include 'bd/conexao.php';
$sql = "select * from fotos order by id desc";
$busca = mysqli_query($con, $sql);
while ($array = mysqli_fetch_array($busca)) {
$id = $array['id'];
$imagem = $array['imagem'];
$descricao = $array['descricao'];
?>
<tr>
<td><img src="<?php echo 'galeria/'. $imagem ?>" style="width:100px;" alt=""></td>
<td><?php echo $descricao ?></td>
<td>
<div class="row">
<div class="col">
<a href="#" onclick="excluir( <?php echo $id; ?> )"><i class="fas fa-trash-alt text-dark"></i></a>
</div>
</div>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
<!-- JavaScript (Opcional) -->
<!-- jQuery primeiro, depois Popper.js, depois Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html>
<file_sep><?php
session_start();
if(!isset($_SESSION['logado'])){
header('Location: login.php');
exit;
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<!-- Meta tags Obrigatórias -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title><NAME></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="<KEY> crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
<script>
$(document).ready(function() {
$('#listar-usuarios').DataTable({
responsive: true,
"scrollX": true,
"columnDefs": [
{ "width": "250px", "targets": 0, "searchable": false},
{ "width": "100px", "targets": 1 },
{ "width": "300px", "targets": 2 },
{ "width": "150px", "targets": 3 },
{ "width": "100px", "targets": 4 },
{ "width": "100px", "targets": 5 },
],
"language": {
"url": "//cdn.datatables.net/plug-ins/1.10.20/i18n/Portuguese-Brasil.json"
}
});
$(".deletarUsuario").click(function() {
if (confirm('Excluir usuário?')) {
var nome = $(this).parent().parent().find(':nth-child(2)').html();
var id = $(this).parent().parent().find(':nth-child(1)').html();
$.ajax({
url: 'bd/deletarUsuario.php',
type: 'POST',
data: 'nome=' + nome + '&id=' + id,
success: function(data) {
$("#resposta_ajax").addClass("alert alert-success").css('display', 'block').html(data);
}
});
}
});
});
</script>
</head>
<style>
table{
table-layout: fixed;
word-wrap:break-word;
}
</style>
<body>
<?php include 'topo_adm.php' ?>
<?php include 'dashboard.php'; ?>
<div class="container animated zoomIn">
<div class="card mt-5 grow" style="width: 100%;">
<div class="row">
<div class="col">
<div class="card-header">
<div class="d-flex justify-content-center social_icon">
<span><i class="fas fa-fw fa-users fa-3x"></i></span>
<h5 class="mt-2 ml-2">Lista de Usuários</h5>
</div>
</div>
</div>
</div>
<div class="card-body">
<div class="col d-flex justify-content-end">
<div class="btn btn-light">
<span style="color: blue" class="mr-2"><i class="fas fa-plus"></i></span>
<a href="cadastro_adm.php" style="text-decoration:none; color:blue">Adicionar Usuário</a>
</div>
</div>
<br>
<div id="resposta_ajax" class="alert" style="display:none"></div>
<form action="" method="post">
<table id="listar-usuarios" class="table hover" style="width:100%">
<thead class="text-light" style="background-color:#343a40">
<th style="display:none">Código</th>
<th>Nome</th>
<th>Email</th>
<th>Perfil</th>
<th>Editar</th>
<th>Excluir</th>
</thead>
<tbody>
<?php
include 'bd/conexao.php';
$query = mysqli_query($con, "SELECT id_usuario, nome, email, perfil FROM usuarios");
while($row = mysqli_fetch_array($query)){
$id = $row['id_usuario'];
echo "<tr>
<td style='display:none'>".$id."</td>
<td>".$row['nome']."</td>
<td>".$row['email']."</td>
<td>".$row['perfil']."</td>
<td>
<a href='editarUsuario.php?id=$id'><i class='fas fa-user-edit'></i></a>
</td>
<td>
<a class='deletarUsuario'><i class='fas fa-trash-alt'></i></a>
</td>
</tr>";
}
mysqli_close($con);
?>
</tbody>
</table>
</form>
</div>
</div>
</div>
</body>
</html>
<file_sep><?php
session_start();
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<!-- Meta tags Obrigatórias -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Maurício Luminárias</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="<KEY> crossorigin="anonymous">
<!-- Folha de Estilo -->
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
atualizar();
$('#formComentario').submit(function(event) {
event.preventDefault();
// seleciona o botão de submit
var botao = $(this).find('input[type="submit"]');
// desabilita o botão para evitar multiplos envio
botao.prop("disabled", true).val("Enviando..").css('opacity', '0.5');
data = $("#formComentario").serialize();
$.ajax({
type: "post",
url: "bd/_enviarComentario_.php",
data: data,
success: function(data){
if(data === "sucesso"){
$("#resposta_ajax").removeClass("alert-danger").addClass("alert-success").css('display', 'block').html("Comentário inserido com sucesso");
$('#formComentario')[0].reset();
} else{
$("#resposta_ajax").removeClass("alert-success").addClass("alert-danger").css('display', 'block').html(data);
}
botao.prop("disabled", false).val("Enviar").css('opacity', '1');
}
});
});
});
// // Quando carregar a página
// $(function() {
// // Faz a primeira atualização
// atualizar();
// });
function atualizar(){
// Fazendo requisição AJAX
$.post('bd/exibirComentarios.php', function (comentario) {
// Exibindo comentario
$('#nome').html(comentario.nome);
$('#comentario').html(comentario.comentario);
$('#data').html(comentario.data + ' dias atrás');
$('#teste').attr('checked', false);
$('#teste1').attr('checked', false);
$('#teste2').attr('checked', false);
$('#teste3').attr('checked', false);
$('#teste4').attr('checked', false);
$('#teste5').attr('checked', false);
if(comentario.nota == 1){
$('#teste1').attr('checked', true);
}else if(comentario.nota == 2){
$('#teste2').attr('checked', true);
}else if(comentario.nota == 3){
$('#teste3').attr('checked', true);
}else if(comentario.nota == 4){
$('#teste4').attr('checked', true);
}else if(comentario.nota == 5){
$('#teste5').attr('checked', true);
}
}, 'JSON');
}
// Definindo intervalo em que a função será chamada
setInterval("atualizar()", 5000);
</script>
</head>
<body>
<!-- ===========1º Container - Principal =========== -->
<div class="box" id="container1">
<?php include 'topo.php'; ?>
<div class="d-flex justify-content-end" style="height: 68%;">
<div class="d-flex align-items-center" id="C1main" style="width:50%;">
<div>
<h1 class="h1-principal display-lg-3">Luminárias Artesanais</h1>
<p>As melhores luminárias artesanais do Rio de Janeiro.</p>
<div id="cliqueAqui">
<a class="btn btn-md border border-dark mt-2" href="galeria.php" style="font-weight: bold;">Ver luminárias</a>
<a class="btn btn-md border border-dark mt-2" href="pre_encomenda.php" style="font-weight: bold;">Encomendar</a>
</div>
</div>
</div>
</div>
<div>
<ul style="list-style:none;" id="redeSociais">
<li class="mt-2"><a class="text-white" href="https://www.instagram.com/mauricioluminarias/"><img src="imagens/insta.png" style="width:40px;" alt=""></a></li>
<li class="mt-2"><a class="text-white" href="https://www.facebook.com/mauricio.luminarias.5"><img src="imagens/face.png" style="width:40px;" alt=""></a></li>
<li class="mt-2"><a class="text-white" href="mailto:<EMAIL>"><img src="imagens/email.png" style="width:40px;" alt=""></a></li>
<li class="mt-2"><a class="text-white" href="https://api.whatsapp.com/send?phone=5522988465242&text=Ol%C3%A1%2C%20tenho%20interesse%20em%20adquirir%20seus%20produtos"><img src="imagens/whats.png" style="width:40px;" alt=""></a></li>
</ul>
</div>
</div>
<!-- ===========2º Container - Fotos =========== -->
<div class="container box2 pb-4" id="container2">
<section class="container" id="carousel1">
<!--Carousel Wrapper-->
<div id="multi-item-example" class="carousel slide carousel-multi-item carousel-multi-item-2" data-ride="carousel">
<!--Controls-->
<div class="controls-top d-flex justify-content-center">
<a class="text-dark" href="#multi-item-example" data-slide="prev"><i class="fas fa-arrow-circle-left fa-2x p-3"></i></a>
<a class="text-dark" href="#multi-item-example" data-slide="next"><i class="fas fa-arrow-circle-right fa-2x p-3"></i></a>
</div>
<!--/.Controls-->
<!--Slides-->
<div class="carousel-inner" role="listbox">
<!--First slide-->
<div class="carousel-item active">
<div class="col-md-3 mb-3">
<div class="card" id="zoom">
<a href="galeria.php"><img class="img-fluid" src="imagens/Low/Mini3.png" alt="Card image cap"></a>
</div>
</div>
<div class="col-md-3 mb-3">
<div class="card" id="zoom">
<a href="galeria.php"><img class="img-fluid" src="imagens/Low/Mini4.png" alt="Card image cap"></a>
</div>
</div>
<div class="col-md-3 mb-3">
<div class="card" id="zoom">
<a href="galeria.php"><img class="img-fluid" src="imagens/Low/Mini6.png" alt="Card image cap"></a>
</div>
</div>
<div class="col-md-3 mb-3">
<div class="card" id="zoom">
<a href="galeria.php"><img class="img-fluid" src="imagens/Low/Mini7.png" alt="Card image cap"></a>
</div>
</div>
</div>
<!--/.First slide-->
<!--Second slide-->
<div class="carousel-item">
<div class="col-md-3 mb-3">
<div class="card" id="zoom">
<a href="galeria.php"><img class="img-fluid" src="imagens/Low/Mini8.png" alt="Card image cap"></a>
</div>
</div>
<div class="col-md-3 mb-3">
<div class="card" id="zoom">
<a href="galeria.php"><img class="img-fluid" src="imagens/Low/Mini9.png" alt="Card image cap"></a>
</div>
</div>
<div class="col-md-3 mb-3">
<div class="card" id="zoom">
<a href="galeria.php"><img class="img-fluid" src="imagens/Low/Mini10.png" alt="Card image cap"></a>
</div>
</div>
<div class="col-md-3 mb-3">
<div class="card" id="zoom">
<a href="galeria.php"><img class="img-fluid" src="imagens/Low/Mini15.png" alt="Card image cap"></a>
</div>
</div>
</div>
<!--/.Second slide-->
</div>
<!--/.Slides-->
</div>
<!--/.Carousel Wrapper-->
</section>
</div>
<div class="container box2 pb-4" id="container2">
<section class="container" id="carousel2">
<!--Carousel Wrapper-->
<div id="multi-item-example2" class="carousel slide carousel-multi-item carousel-multi-item-2" data-ride="carousel">
<!--Controls-->
<div class="controls-top d-flex justify-content-center" style="max-width:55%">
<a class="text-dark" href="#multi-item-example2" data-slide="prev"><i class="fas fa-arrow-circle-left fa-2x p-3"></i></a>
<a class="text-dark" href="#multi-item-example2" data-slide="next"><i class="fas fa-arrow-circle-right fa-2x p-3"></i></a>
</div>
<!--/.Controls-->
<!--Slides-->
<div class="carousel-inner" role="listbox">
<!--First slide-->
<div class="carousel-item active">
<div class="col-md-3 mb-3">
<div class="card" id="zoom" style="max-width:340px;">
<img class="img-fluid" src="imagens/Low/Mini3.png" style="min-width:auto;" alt="Imagens do maurício">
</div>
</div>
</div>
<!--/.First slide-->
<!--Second slide-->
<div class="carousel-item">
<div class="col-md-3 mb-3">
<div class="card" id="zoom" style="max-width:340px;">
<img class="img-fluid" src="imagens/Low/Mini4.png" style="min-width:auto;" alt="Imagens do maurício">
</div>
</div>
</div>
<!--/.Second slide-->
<!--third slide-->
<div class="carousel-item">
<div class="col-md-3 mb-3">
<div class="card" id="zoom" style="max-width:340px;">
<img class="img-fluid" src="imagens/Low/Mini6.png" style="min-width:auto;" alt="Imagens do maurício">
</div>
</div>
</div>
<!--/.third slide-->
</div>
<!--/.Slides-->
</div>
<!--/.Carousel Wrapper-->
</section>
</div>
<!-- ===========3º Container - Comentários =========== -->
<div class="box" id="container3">
<div class="row" style="color:white;align-items:center;padding-top:10%;">
<div class="col-lg-6">
<div class="ml-4 mb-4">
<h4>Comentários mais relevantes:</h4>
</div>
<div class="card ml-4 mr-4 d-block" style="border: solid 1px rgba(192,192,192,0.3);background:rgba(192,192,192,0.3);" id="comentarioPai">
<div class="row">
<div class="col-sm-8 balao d-flex mt-1" id="ocultar">
<p id="nome" class="text-light text-start"></p>
</div>
<div class="col" >
<div class="estrelas mt-1 text-center">
<input type="radio" id="teste" name="nota" value="" checked="checked">
<label for="teste1"><i class="fa estrelaLabel ml-1"></i></label>
<input type="radio" id="teste1" value="1" disabled="disabled">
<label for="teste2"><i class="fa estrelaLabel ml-1"></i></label>
<input type="radio" id="teste2" value="2" disabled="disabled">
<label for="teste3"><i class="fa estrelaLabel ml-1"></i></label>
<input type="radio" id="teste3" value="3" disabled="disabled">
<label for="teste4"><i class="fa estrelaLabel ml-1"></i></label>
<input type="radio" id="teste4"value="4" disabled="disabled">
<label for="teste5"><i class="fa estrelaLabel ml-1"></i></label>
<input type="radio" id="teste5" value="5" disabled="disabled">
</div>
</div>
</div>
<div class="ml-2">
<p id="data" class="text-light blockquote-footer"></p>
</div>
<div class="row container">
<div class="col-8" style="padding-left:-10px;">
<p id="comentario" class="text-justify text-light" style="opacity: 0.9;"></p>
</div>
</div>
</div>
</div>
<div class="col-lg-6">
<br>
<form id="formComentario" class="form form-group p-4 pb-5 mr-4 ml-4" method="post" style="border-radius: 5px;background-color:rgba(192,192,192,0.3);">
<div id="resposta_ajax" class="alert" style="display:none;"></div>
<label for="exampleFormControlTextarea6" class="d-block">Digite Seu Nome: *</label>
<input type="text" class=" form-control z-depth-1" maxlength="100" style="border: solid 1px; opacity: 0.5;" rows="3" name="nome" required placeholder="<NAME>">
<label for="exampleFormControlTextarea6" class="d-block">Digite Seu Email: *</label>
<input type="email" class=" form-control z-depth-1" maxlength="100" name="email" id="exampleFormControlTextarea6" style="border: solid 1px; opacity: 0.5;" rows="3" required placeholder="<EMAIL>">
<div class="form-group shadow-textarea">
<label for="exampleFormControlTextarea6">Deixe seu feedback abaixo: *</label>
<textarea class="form-control z-depth-1" maxlength="255" name="comentario" id="exampleFormControlTextarea6" minlength="6" maxlength="255" style="border: solid 1px; opacity: 0.5;" rows="3" required placeholder="Deixe seu elogio, ou faça uma crítica construtiva.."></textarea>
</div>
<div class="align-items-center mt-4"><h6>Dê sua nota:</h6>
<div class="estrelas">
<input type="radio" id="cm_star-empty" name="nota" value="" required checked/>
<label for="cm_star-1"><i class="fa estrelaLabel ml-1"></i></label>
<input type="radio" id="cm_star-1" name="nota" required value="1"/>
<label for="cm_star-2"><i class="fa estrelaLabel ml-1"></i></label>
<input type="radio" id="cm_star-2" name="nota" value="2" required/>
<label for="cm_star-3"><i class="fa estrelaLabel ml-1"></i></label>
<input type="radio" id="cm_star-3" name="nota" value="3" required/>
<label for="cm_star-4"><i class="fa estrelaLabel ml-1"></i></label>
<input type="radio" id="cm_star-4" name="nota" value="4" required/>
<label for="cm_star-5"><i class="fa estrelaLabel ml-1"></i></label>
<input type="radio" id="cm_star-5" name="nota" value="5" required/>
</div>
<div id="recaptcha" class="g-recaptcha pt-4" data-sitekey="<KEY>"></div>
<span class="msg-error error"></span>
</div>
<div class="form-group">
<input id="btnenviar" name="btnenviar" type="submit" class="nav-link btn btn-outline-light float-right login_btn" >
</div>
</form>
</div>
</div>
</div>
<!-- =========== 4º Container - <NAME> =========== -->
<div class="container box2 pt-2 mt-4" id="container4">
<section class="pr-5">
<div class="accordion" id="accordionExample">
<div class="card shadow-lg p-3 mb-5 bg-white rounded">
<div class="card-header" style="background-color:#FFA500" id="headingOne">
<h5 class="mb-0">
<button class="btn btn-link text-light nav-link" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="false" aria-controls="collapseOne">
<i class="fas fa-hand-point-up mr-3"></i>Saiba mais:
</button>
</h5>
</div>
<div id="collapseOne" class="collapse" aria-labelledby="headingOne" data-parent="#accordionExample">
<div class="d-flex">
<img width="186" height="186" id="ocultar" src="imagens/Foto5.png" class="d-flex justify-content-center pt-2" />
<div class="card-body font-italic text-justify float-right">
A empresa Maurício Luminárias foi criada em 1994, tendo como fundador, <NAME>. Iniciou seus trabalhos com carpete e marchetaria. Logo depois, entrou no negócio de luminárias artesanais tendo como público alvo turistas que visitam a sua cidade, Casimiro de Abreu - RJ. Atualmente seus produtos são fábricados em sua casa que fica em Cabo Frio - RJ e sua loja física localiza-se na Av. Amaral Peixoto 395 - Barra de São João. Mais de 25 anos no mercado o seu Maurício se tornou um grande artista se tornando referência em sua região.
</div>
</div>
</div>
<div id="DIVMaps">
<div class="d-flex justify-content-center">
<div class="mt-3">
<h1 class="text-center">Visite minha loja <i class="fas fa-map-marked-alt ml-2"></i></h1>
</div>
</div>
<div class="col d-flex justify-content-center">
<a href="">Av. <NAME> 395, Barra de São João - RJ <i class="fas fa-hand-point-up"></i></a>
</div>
</div>
</div>
</div>
</section>
</div>
<!-- JavaScript (Opcional) -->
<!-- jQuery primeiro, depois Popper.js, depois Bootstrap JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</body>
</html>
<file_sep><?php
session_start();
if(isset($_POST['email'])){
include 'conexao.php';
$email = $_POST['email'];
$senha = <PASSWORD>($_POST['senha']);
if(empty($email) || empty($senha)){
echo "Verifique se todos os campos obrigatórios foram preenchidos";
} else{
$sql = mysqli_query($con, "SELECT * FROM usuarios WHERE email = '$email' AND senha = '$senha'");
if(mysqli_num_rows($sql) == 1){
$dados = mysqli_fetch_array($sql);
$_SESSION['perfil'] = $dados['perfil'];
$_SESSION['id'] = $dados['id_usuario'];
$_SESSION['nome'] = $dados['nome'];
$_SESSION['logado'] = true;
echo "sucesso";
}else{
echo "Login incorreto";
}
}
}
?> | 6320f2c4997e229012c405a427d8a641bc872764 | [
"SQL",
"PHP"
] | 29 | PHP | Luana-jcg/MauricioLuminarias | 9bfb697cd67127fab61cec9f4793cc4d889d86c4 | 4afbd2c879959264dc33be74cfd786bd4222efcb |
refs/heads/master | <repo_name>quixxxy/go-rest<file_sep>/Dockerfile
FROM golang
ADD . /go/src/github.com/quixxxy/go-rest
RUN go get github.com/gorilla/mux
RUN go install github.com/quixxxy/go-rest/main
ENTRYPOINT /go/bin/main
EXPOSE 8080
<file_sep>/main/main.go
package main
import (
"log"
"net/http"
"github.com/gorilla/mux"
"encoding/json"
"strconv"
)
type Person struct {
ID string `json:"id,omitempty"`
Firstname string `json:"firstname,omitempty"`
Lastname string `json:"lastname,omitempty"`
Address *Address `json:"address,omitempty"`
}
type Address struct {
City string `json:"city,omitempty"`
State string `json:"state,omitempty"`
}
var people []Person
func GetPersonEndpoint(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
for _, item := range people {
if item.ID == params["id"] {
json.NewEncoder(w).Encode(item)
return
}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(&Person{})
}
func GetPeopleEndpoint(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(people)
}
func CreatePersonEndpoint(w http.ResponseWriter, req *http.Request) {
var person Person
_ = json.NewDecoder(req.Body).Decode(&person)
maxID := 0
for _, item := range people {
id, _ := strconv.Atoi(item.ID)
if id > maxID {
maxID = id
}
}
person.ID = strconv.Itoa(maxID + 1)
people = append(people, person)
w.WriteHeader(http.StatusCreated)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(people)
}
func UpdatePersonEndpoint(w http.ResponseWriter, req *http.Request) {
}
func DeletePersonEndpoint(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
for index, item := range people {
if item.ID == params["id"] {
people = append(people[:index], people[index+1:]...)
break
}
}
w.WriteHeader(http.StatusNoContent)
}
func main() {
router := mux.NewRouter()
people = append(people, Person{ID: "1", Firstname: "John", Lastname: "Doe", Address: &Address{City: "Los Angeles", State: "CA"}})
people = append(people, Person{ID: "2", Firstname: "Foo", Lastname: "Bar"})
router.HandleFunc("/people", GetPeopleEndpoint).Methods("GET")
router.HandleFunc("/people/{id}", GetPersonEndpoint).Methods("GET")
router.HandleFunc("/people", CreatePersonEndpoint).Methods("POST")
router.HandleFunc("/people/{id}", UpdatePersonEndpoint).Methods("PUT")
router.HandleFunc("/people/{id}", DeletePersonEndpoint).Methods("DELETE")
log.Fatal(http.ListenAndServe(":8080", router))
}
| da7dfc23a0abd61631f5c9fb732d2f629925d210 | [
"Go",
"Dockerfile"
] | 2 | Dockerfile | quixxxy/go-rest | 84682dbae7f3c192f30e89a175762cfb36d869ab | 392c9c671525b818b93cbb0c553806f074e61ad3 |
refs/heads/master | <file_sep>import React from "react";
import DocTitleOne from "../components/DocTitleOne";
import DocTitleTwo from "../components/DocTitleTwo";
function VisitCustom() {
return (
<React.Fragment>
<DocTitleOne />
<DocTitleTwo />
</React.Fragment>
);
}
export default VisitCustom;
<file_sep>import React, { useState, useEffect } from "react";
import { Button, FormControl, Input, InputLabel } from "@material-ui/core";
import "./App.css";
import Todo from "./component/Todo";
function App() {
const [todos, setTodos] = useState([]);
const [input, setInput] = useState("");
useEffect(() => {
console.log(todos);
}, [todos]);
const addTodo = (event) => {
event.preventDefault(); //stops refresh
console.log("Im Working");
setTodos([...todos, input]);
setInput(""); //clear the input after hitting submit
};
const deleteTodo = (val) => {
console.log(val);
const index = todos.indexOf(val);
const todoCpy = [...todos];
if (index > -1) {
todoCpy.splice(index, 1);
setTodos(todoCpy);
}
};
const updateList = (value, i) => {
console.log(value, i);
const newTodos = [...todos];
newTodos[i] = value;
setTodos(newTodos);
};
return (
<div className="App">
<h1>Hello World</h1>
<FormControl>
<InputLabel> Write a Todo</InputLabel>
<Input
value={input}
onChange={(event) => setInput(event.target.value)}
/>
</FormControl>
<Button
disabled={!input}
type="submit"
onClick={addTodo}
variant="contained"
color="secondary"
>
Add Todo
</Button>
<ul>
{todos.map((todo, i) => (
<Todo
key={i}
text={todo}
deleteTodo={deleteTodo}
updateList={updateList}
index={i}
/>
//<li>{todo}</li>
))}
</ul>
</div>
);
}
export default App;
| a8d65040ce9c0b7d230f73a06c8beeffc806bef9 | [
"JavaScript"
] | 2 | JavaScript | Rahulsinha197/practise | d0c2a801b9faf4622db746ff3101b79be59c16ca | 964fa9d241a230fe055f5da24a57afd15e9d8de0 |
refs/heads/master | <repo_name>aember/cinch-tyrant<file_sep>/spec/tyrant-targets_spec.rb
require_relative 'test-common'
require 'cinch/plugins/tyrant-targets'
describe Cinch::Plugins::TyrantTargets do
include Cinch::Test
let(:bot) {
make_bot(Cinch::Plugins::TyrantTargets) { |c|
self.loggers.stub('debug') { nil }
}
}
it 'makes a test bot' do
expect(bot).to be_a Cinch::Bot
end
describe '!targets' do
before :each do
@conn = FakeConnection.new
@tyrant = Tyrants.get_fake('testplayer', @conn)
expect(Tyrants).to receive(:get).with('testplayer').and_return(@tyrant)
@conn.respond('getFactionInfo', '', {'rating' => 1000})
end
let(:message) { make_message(bot, '!targets', channel: '#test') }
it 'informs the user when there are no targets' do
@conn.respond('getFactionRivals', 'rating%5Flow=0', {'rivals' => []})
@conn.respond('getFactionRivals', 'rating%5Fhigh=0', {'rivals' => []})
replies = get_replies_text(message)
expect(replies).to be == ['No targets!']
end
it 'shows the targets' do
@conn.respond('getFactionRivals', 'rating%5Flow=0', {'rivals' => []})
@conn.respond('getFactionRivals', 'rating%5Fhigh=0', {'rivals' => [
{
'faction_id' => '2000',
'rating' => '1050',
'name' => '<NAME>',
'infamy_gain' => 0,
'less_rating_time' => 0,
},
]})
replies = get_replies_text(message)
expect(replies).to be == ['6: THE ENEMY (1050)']
end
it 'hides infamy-gaining targets' do
@conn.respond('getFactionRivals', 'rating%5Flow=0', {'rivals' => []})
@conn.respond('getFactionRivals', 'rating%5Fhigh=0', {'rivals' => [
{
'faction_id' => '2000',
'rating' => '1050',
'name' => '<NAME>',
'infamy_gain' => 1,
'less_rating_time' => 0,
},
]})
replies = get_replies_text(message)
expect(replies).to be == ['No targets!']
end
it 'stars less-FP targets' do
@conn.respond('getFactionRivals', 'rating%5Flow=0', {'rivals' => []})
@conn.respond('getFactionRivals', 'rating%5Fhigh=0', {'rivals' => [
{
'faction_id' => '2000',
'rating' => '1050',
'name' => '<NAME>',
'infamy_gain' => 0,
'less_rating_time' => Time.now.to_i,
},
]})
replies = get_replies_text(message)
expect(replies).to be == ['3: THE ENEMY* (1050)']
end
end
end
<file_sep>/lib/cinch/plugins/tyrant-conquest-poll.rb
require 'cinch'
require 'cinch/tyrant/cmd'
require 'cinch/plugins/tyrant-conquest'
require 'set'
require 'tyrant'
require 'tyrant/cards'
require 'tyrant/conquest'
module Cinch; module Plugins; class TyrantConquestPoll
include Cinch::Plugin
POLL_INTERVAL = 60
INVASION_POLL_INTERVAL = 15
CLEM_CONFLICT = [
:invasion_switch,
:invasion_kill,
:cset_feedback,
:claim_feedback,
:free_feedback,
:stuck_feedback,
:check_feedback,
:status_feedback,
]
DEFAULT_SETTINGS = {
:invasion_start => true,
:invasion_win => true,
:invasion_loss => true,
:invasion_monitor => true,
:invasion_switch => true,
:invasion_kill => true,
:defense_start => true,
:defense_win => true,
:defense_loss => true,
:cset_feedback => true,
:claim_feedback => true,
:free_feedback => true,
:stuck_feedback => true,
:check_feedback => true,
:status_feedback => true,
}
timer POLL_INTERVAL, method: :check_conquest
timer INVASION_POLL_INTERVAL, method: :check_invasion
match(/cnews\s*(\S+)\s*(\S+)?/i, method: :cnews)
match(/ctrack(.*)/i, method: :ctrack)
COMMANDS = [
Cinch::Tyrant::Cmd.new('conquest', 'cnews', 'list',
lambda { |m| is_warmaster?(m) },
'Lists possible conquest news alert items'
),
Cinch::Tyrant::Cmd.new('conquest', 'cnews', '<item> <on|off>',
lambda { |m| is_warmaster?(m) },
'Turns a conquest news item (from !cnews list) on or off'
),
]
Struct.new('Slot', :commander, :hp, :defeated,
:attackers, :stuck,
:owner,
:deck, :deck_set_by, :deck_set_time,
:hash,
:original_format,
:change_time) {
def known?
self.deck && (!self.change_time || self.change_time < self.deck_set_time)
end
def list_stuck
self.stuck.to_a.map { |x|
TyrantConquest::safe_name(x)
}.join(', ')
end
def list_attackers
self.attackers.to_a.map { |x|
TyrantConquest::safe_name(x)
}.join(', ')
end
}
class MonitoredFaction
include Cinch::Helpers
attr_accessor :monitor_opts
attr_reader :tyrant
attr_reader :channel
attr_reader :invasion_tile, :invasion_info
attr_reader :invasion_start_time, :invasion_end_time
attr_reader :invasion_effect
attr_reader :last_check
attr_reader :max_hp
attr_reader :slots_alive
attr_reader :opponent
def initialize(tyrant, faction_id, channel, monitor_opts)
@tyrant = tyrant
@faction_id = faction_id
@channel = channel
@monitor_opts = monitor_opts
@invasion_tile = nil
@new_invasion = false
@invasion_info = Hash.new { |h, k|
h[k] = Struct::Slot.new(1000, 100, false, Set.new, Set.new)
}
@invasion_start_time = nil
@invasion_end_time = nil
@last_check = nil
@max_hp = '??'
@slots_alive = nil
@opponent = nil
end
def invasion_tile=(t)
return if @invasion_tile == t
@invasion_tile = t
@new_invasion = true
@invasion_info.clear if t
end
def check_invasion
return [] if @tyrant.nil?
return [] if !@invasion_tile
json = @tyrant.make_request('getConquestTileInfo',
"system_id=#{@invasion_tile}", reinit: false)
messages = []
return [] if json['duplicate_client']
@max_hp = json['system']['max_health']
@opponent = json['system']['faction_id']
@slots_alive = 0
json['system']['slots'].each{ |k, v|
# Only notify if ongoing invasion
unless @new_invasion
if v['defeated'] == '1' && !@invasion_info[k][:defeated]
# Defeated! Notify channel if requested
if @monitor_opts[:invasion_kill]
c = TyrantConquestPoll::cards
name = c[v['commander_id'].to_i % 10000].name
name = 'Foil ' + name if v['commander_id'].to_i > 10000
message = "[INVASION] Slot #{k} (#{name}) has been defeated!"
unless @invasion_info[k].stuck.empty?
stuck_people = @invasion_info[k].stuck.to_a.join(', ')
message += ' ' + stuck_people + ': you are free!'
end
messages.push(message)
end
# Since it's dead nobody is stuck or attacking anymore
@invasion_info[k].attackers.clear
@invasion_info[k].stuck.clear
elsif @invasion_info[k][:commander] != v['commander_id']
# Commander has changed!
@invasion_info[k][:change_time] = Time.now.to_i
# Notify channel if requested
if @monitor_opts[:invasion_switch]
c = TyrantConquestPoll::cards
name1 = c[@invasion_info[k][:commander].to_i % 10000].name
name1 = 'Foil ' + name1 if @invasion_info[k][:commander].to_i > 10000
name2 = c[v['commander_id'].to_i % 10000].name
name2 = 'Foil ' + name2 if v['commander_id'].to_i > 10000
hp = v['health']
message = "[INVASION] Slot #{k} (#{hp} HP) commander changed from #{name1} to #{name2}"
unless @invasion_info[k].attackers.empty?
attackers = @invasion_info[k].attackers.to_a.join(', ')
message += ' ' + attackers + ': be careful!'
end
messages.push(message)
end
end
end
@invasion_info[k][:commander] = v['commander_id']
@invasion_info[k][:hp] = v['health']
@invasion_info[k][:defeated] = v['defeated'] == '1'
@slots_alive += 1 if v['defeated'] != '1'
}
@new_invasion = @invasion_tile.nil?
@invasion_start_time = json['system']['attack_start_time'].to_i
@invasion_end_time = json['system']['attack_end_time'].to_i
@invasion_effect = json['system']['effect']
@invasion_effect &&= @invasion_effect.to_i
@last_check = Time.now.to_i
messages
end
end
@cards = {}
@report_channel = nil
class << self
attr_accessor :cards
attr_accessor :report_channel
end
def initialize(*args)
super
@factions_by_id = {}
@all_factions = {}
shared[:conquest_factions] = @all_factions
@poller = Tyrants.get(config[:poller])
@map_json = @poller.make_request('getConquestMap')
@map_hash = {}
@map_json['conquest_map']['map'].each { |t| @map_hash[t['system_id']] = t }
shared[:conquest_map_hash] = @map_hash
@ctrack_enabled = true
@reset_acknowledged = false
self.class.cards = shared[:cards_by_id]
self.class.report_channel = config[:report_channel]
channel_configs = config[:channels] || {}
BOT_FACTIONS.each { |faction|
next if faction.id < 0
channel = faction.channel_for(:conquest)
args = DEFAULT_SETTINGS.merge(channel_configs[channel] || {})
tyrant = faction.player ? Tyrants.get(faction.player) : nil
monitored_faction = MonitoredFaction.new(
tyrant, faction.id, channel, args
)
@factions_by_id[faction.id] = monitored_faction
faction.channels.each { |chan|
@all_factions[chan] = monitored_faction
}
}
@map_hash.each { |id, t|
current_attacker = t['attacking_faction_id'].to_i
if current_attacker != 0
if f = @factions_by_id[current_attacker]
f.invasion_tile = id
end
end
}
end
def send_message(faction, tile, verb, enemy, enable_sym)
return unless faction.monitor_opts[enable_sym]
prefix = '[CONQUEST] '
Channel(faction.channel).send(prefix + tile + " #{verb} #{enemy}")
end
def check_invasion
@factions_by_id.each_value { |faction|
next unless faction.monitor_opts[:invasion_monitor]
messages = faction.check_invasion
messages.each { |m| Channel(faction.channel).send(m) }
}
end
def check_conquest
@map_json = @poller.make_request('getConquestMap')
tiles_owned = @map_json['conquest_map']['map'].count { |t|
t['faction_id']
}
if tiles_owned == 0
if !@reset_acknowledged
@factions_by_id.each_value { |faction|
Channel(faction.channel).send("[CONQUEST] MAP RESET!!!")
}
Channel(self.class.report_channel).send("[CONQUEST] MAP RESET!!!")
end
@reset_acknowledged = true
@map_json['conquest_map']['map'].each { |t|
@map_hash[t['system_id']] = t
}
return
end
@reset_acknowledged = false
no_attack_factions = Set.new(@factions_by_id.keys)
@map_json['conquest_map']['map'].each { |t|
id = t['system_id']
prev_t = @map_hash[id]
@map_hash[id] = t
# Premature optimization?
# Don't calculate these unless necessary,
# but also don't calculate them more than once
name = nil
prefix = nil
current_owner = t['faction_id'].to_i
old_owner = prev_t['faction_id'].to_i
if old_owner != current_owner
name ||= TyrantConquest::tile_name(t)
prefix ||= '[CONQUEST] ' + name + ' '
current = (t['faction_name'] || '(neutral)').sanitize
old = (prev_t['faction_name'] || '(neutral)').sanitize
if @ctrack_enabled
o = "#{old}[#{old_owner.to_i}]"
c = "#{current}[#{current_owner.to_i}]"
message = "#{prefix}#{o} -> #{c}"
Channel(self.class.report_channel).send(message)
end
if f = @factions_by_id[current_owner]
send_message(f, name, 'Conquered from', old, :invasion_win)
end
if f = @factions_by_id[old_owner]
send_message(f, name, 'Lost to', current, :defense_loss)
end
end
current_attacker = t['attacking_faction_id'].to_i
old_attacker = prev_t['attacking_faction_id'].to_i
if old_attacker != current_attacker
name ||= TyrantConquest::tile_name(t)
prefix ||= '[CONQUEST] ' + name + ' '
owner = (t['faction_name'] || '(neutral)').sanitize
if old_attacker != 0 && old_attacker != current_owner
attacker = (prev_t['attacking_faction_name'] || '(noname)').sanitize
if @ctrack_enabled
o = "#{owner}[#{current_owner.to_i}]"
a = "#{attacker}[#{old_attacker.to_i}]"
message = "#{prefix}#{o} holds off #{a}"
Channel(self.class.report_channel).send(message)
end
if f = @factions_by_id[current_owner]
send_message(f, name, 'Defended against', attacker, :defense_win)
end
if f = @factions_by_id[old_attacker]
send_message(f, name, 'Failed invasion against', owner,
:invasion_loss)
end
end
if current_attacker != 0
attacker = (t['attacking_faction_name'] || '(noname)').sanitize
if @ctrack_enabled
o = "#{owner}[#{current_owner.to_i}]"
a = "#{attacker}[#{current_attacker.to_i}]"
message = "#{prefix}#{o} invaded by #{a}"
Channel(self.class.report_channel).send(message)
end
if f = @factions_by_id[current_owner]
send_message(f, name, 'Under attack by', attacker, :defense_start)
end
if f = @factions_by_id[current_attacker]
f.invasion_tile = id
send_message(f, name, 'New invasion against', owner, :invasion_start)
end
end
end
no_attack_factions.delete(current_attacker) if current_attacker != 0
}
no_attack_factions.each { |x| @factions_by_id[x].invasion_tile = nil }
end
def cnews(m, option, switch)
return unless is_warmaster?(m)
faction = @all_factions[m.channel.name]
if option.downcase == 'list'
m.reply(faction.monitor_opts.to_s)
return
end
if option.downcase == 'clem'
if switch == 'on'
new_state = true
m.reply('Setting all clemmy commands on')
elsif switch == 'off'
new_state = false
m.reply('Setting all clemmy commands off')
else
m.reply("wat? #{m.user.name} smells")
return
end
CLEM_CONFLICT.each { |s| faction.monitor_opts[s] = new_state }
return
end
option_sym = option.to_sym
if !faction.monitor_opts.has_key?(option_sym)
m.reply("#{option} is not a valid conquest news item")
return
end
msg = "#{option} was #{faction.monitor_opts[option_sym] ? 'on' : 'off'}"
if switch == 'on'
faction.monitor_opts[option_sym] = true
m.reply(msg + ", and now it is on")
elsif switch == 'off'
faction.monitor_opts[option_sym] = false
m.reply(msg + ", and now it is off")
else
m.reply(msg + ", and it is staying that way")
end
end
def ctrack(m, switch)
return unless m.user.master?
msg = "Conquest track was #{@ctrack_enabled ? 'on' : 'off'}"
if switch == ' on'
@ctrack_enabled = true
m.reply(msg + ", and now it is on")
elsif switch == ' off'
@ctrack_enabled = false
m.reply(msg + ", and now it is off")
else
m.reply(msg + ", and it is staying that way")
end
end
end; end; end
<file_sep>/spec/tyrant-update_spec.rb
require_relative 'test-common'
require 'cinch/plugins/tyrant-update'
describe Cinch::Plugins::TyrantUpdate do
include Cinch::Test
let(:bot) {
make_bot(Cinch::Plugins::TyrantUpdate) { |c|
self.loggers.stub('debug') { nil }
}
}
it 'makes a test bot' do
expect(bot).to be_a Cinch::Bot
end
end
<file_sep>/spec/test-common.rb
require 'cinch'
require 'cinch/test'
require 'rspec/mocks'
BOT_NICK = 'testbot'
# =================== TIMER SETUP ===================
FakeTimerInfo = Struct.new(:interval, :method)
class FakeTimer
attr_reader :interval, :method
def initialize(interval, method, &block)
@interval = interval
@method = method
@block = block
end
def fire!
@block.call
end
end
module Cinch
module Plugin
module ClassMethods
attr_reader :fake_timers
def timer(interval, opts = {})
@fake_timers ||= []
@fake_timers << FakeTimerInfo.new(interval, opts[:method])
end
end
def __register_timers
# pass
end
def get_timers
self.class.fake_timers.map { |t|
FakeTimer.new(t.interval, t.method, &self.method(t.method))
}
end
end
end
class FakeChannel
attr_reader :messages
def initialize
@messages = []
end
def send(msg)
@messages << msg
end
end
# =================== PERMISSION LIST ===================
BOT_MASTERS = []
def is_friend?(m)
true
end
def is_member?(m)
true
end
def is_warmaster?(m)
true
end
def is_officer?(m)
true
end
# =================== CONVENIENCE ===================
def get_replies_text(message)
get_replies(message).map(&:text)
end
# =================== BOT CHANNELS ===================
ChannelInfo = Struct.new(:player, :player_id, :faction_id, :main_channel) do
alias :id :faction_id
def channel_for(_)
self[:main_channel]
end
def channels
[self[:main_channel]]
end
end
BOT_CHANNELS = {
'#test' => ChannelInfo.new('testplayer', 1, 1000, '#test')
}
BOT_FACTIONS = BOT_CHANNELS.values
BOT_IDS = {
1000 => BOT_CHANNELS['#test']
}
# =================== TYRANT CONNECTION ===================
class Tyrants
def self.get_fake(name, connection)
Tyrant.new(
connection: connection,
platform: 'faketype',
tyrant_version: 'fakeversion',
user_agent: 'fakeagent',
name: name,
user_id: 1,
flash_code: 'flashcode',
auth_token: '<PASSWORD>',
faction_id: 1000,
faction_name: 'faction 1000',
client_code_dir: '/dev/null'
)
end
end
class DeflatedResponse
def initialize(response)
@response = response
end
def inflate
@response
end
def to_str
@response
end
end
class FakeConnection
def initialize
RSpec::Mocks::setup(self)
end
def respond(message, params, response)
regex = req_regex(message)
expected_params =
if params && !params.empty?
/^#{params}&flashcode=/
elsif params
# Params present but is blank string
/^flashcode=/
else
# nil?!
raise "No params specified for #{message}"
end
expect(self).to receive(:request).with(regex, expected_params, anything).and_return(DeflatedResponse.new(JSON::dump(response)))
end
def cached_gzip_request(path, data, headers, key, delay)
self.request(path, data, headers)
end
private
def req_regex(message)
/\/api\.php\?user_id=\d+&message=#{message}/
end
end
# =================== CONQUEST ===================
def make_tile(id, owner_id = nil, attacker_id = nil, cr: 1, x: 0, y: 0)
t = {
'system_id' => id,
'rating' => cr,
# These keys are always present even if tile is neutral and unattacked.
'faction_id' => nil,
'attacking_faction_id' => nil,
'x' => x,
'y' => y,
}
if owner_id
t['faction_id'] = owner_id
t['faction_name'] = "faction #{owner_id}"
end
if attacker_id
t['attacking_faction_id'] = attacker_id
t['attacking_faction_name'] = "faction #{attacker_id}"
end
t
end
# =================== CARDS ===================
FakeCard = Struct.new(:id, :name, :type) do
def hash
Tyrant::Cards::hash_of_id(self[:id])
end
end
<file_sep>/spec/tyrant-faction-chat_spec.rb
require_relative 'test-common'
require 'cinch/plugins/tyrant-faction-chat'
describe Cinch::Plugins::TyrantFactionChat do
include Cinch::Test
let(:bot) {
make_bot(Cinch::Plugins::TyrantFactionChat) { |c|
self.loggers.stub('debug') { nil }
}
}
before :each do
@conn = FakeConnection.new
@tyrant = Tyrants.get_fake('testplayer', @conn)
expect(Tyrants).to receive(:get).with('testplayer').and_return(@tyrant)
@conn.respond('getFactionMessages', '', {'messages' => [
{'post_id' => '60', 'message' => 'm1', 'user_id' => '1'},
]})
@chan = FakeChannel.new
bot.plugins[0].stub(:Channel).and_return(@chan)
end
it 'makes a test bot' do
expect(bot).to be_a Cinch::Bot
end
it 'does nothing if there are no new messages' do
@conn.respond('getNewFactionMessages', 'last_post=60', {'messages' => []})
bot.plugins[0].get_timers[0].fire!
expect(@chan.messages).to be == []
end
context 'with new messages' do
before :each do
@conn.respond('getNewFactionMessages', 'last_post=60', {'messages' => [
{'post_id' => '61', 'message' => 'm2', 'user_id' => '2'},
]})
expect(Tyrant).to receive(:get_name_of_id).with('2').and_return('usertwo')
bot.plugins[0].get_timers[0].fire!
end
it 'posts new messages' do
expect(@chan.messages).to be == ['[FACTION] usertwo: m2']
end
it 'updates last post before doing next poll' do
@conn.respond('getNewFactionMessages', 'last_post=61', {'messages' => []})
bot.plugins[0].get_timers[0].fire!
end
end
# TODO: !chat (on|off)
end
<file_sep>/lib/cinch/plugins/tyrant-vault.rb
require 'cinch'
require 'cinch/tyrant/cmd'
require 'tyrant'
module Cinch; module Plugins; class TyrantVault
include Cinch::Plugin
match(/vault/i, method: :vault)
match(/revault/i, method: :revault)
COMMANDS = [
Cinch::Tyrant::Cmd.new('vault', 'vault', '', true,
'Shows the current contents of the Tyrant "Core" vault.'
),
]
def initialize(*args)
super
@vault = ['Orbo'] * 8
@vault_time = 0
end
def vault(m)
return unless is_friend?(m)
if @vault_time < Time.now.to_i
result = _revault
m.reply('failed to update vault') unless result
end
time_left = format_time(@vault_time - Time.now.to_i)
m.reply('[VAULT] ' + @vault.join(', ') + '. Available for ' + time_left)
end
def revault(m)
return unless m.user.master?
result = _revault
m.reply('failed to update vault') unless result
end
def _revault
json = Tyrants.get(config[:checker]).make_request('getMarketInfo')
if !json['cards_for_sale'] || !json['cards_for_sale_starting']
return false
end
@vault = json['cards_for_sale'].map { |x|
card = shared[:cards_by_id][x.to_i]
card ? card.name : 'Unknown card ' + x
}
@vault_time = json['cards_for_sale_starting'].to_i + 3 * HOUR
true
end
end; end; end
<file_sep>/lib/cinch/plugins/tyrant-targets.rb
require 'cinch'
require 'cinch/tyrant/cmd'
require 'cinch/tyrant/simple-memory-cache'
require 'tyrant/rivals'
module Cinch; module Plugins; class TyrantTargets
include Cinch::Plugin
DEFAULT_CONFIG = [nil, nil]
match(/t(?:argets)?(?:\s+(.+))?$/i)
COMMANDS = [
Cinch::Tyrant::Cmd.new('war', 'targets', '',
lambda { |m| is_warmaster?(m) },
'Shows factions who are currently open to attack. ' +
'An asterisk denotes reduced FP gain.'
),
]
FLOOD_INITIAL_TIME = 15
FLOOD_INCREASE = 2
def initialize(*args)
super
@our_fp_cache = Cinch::Tyrant::SimpleMemoryCache.new
@targets_cache = Cinch::Tyrant::SimpleMemoryCache.new
# Flood protection
@last_request = {}
@wait_times = {}
end
def execute(m, name)
return unless is_warmaster?(m)
channel = BOT_CHANNELS[m.channel.name]
user = channel.player
tyrant = Tyrants.get(user)
now = Time.now.to_i
last = @last_request[m.channel.name]
timer = @wait_times[m.channel.name] || FLOOD_INITIAL_TIME
@last_request[m.channel.name] = now
# They are requesting too soon!
if last && now - last < timer
# Double the time remaining on this channel's timer
@wait_times[m.channel.name] -= (now - last)
@wait_times[m.channel.name] *= FLOOD_INCREASE
# Warn them if it's their first time messing it up
if timer == FLOOD_INITIAL_TIME
m.reply('Requesting targets too often. Cool down a bit.', true)
end
return
else
@wait_times[m.channel.name] = FLOOD_INITIAL_TIME
end
args = (config[:channels] || {})[channel.id] || DEFAULT_CONFIG
targets, _ = @targets_cache.lookup(tyrant.faction_id, 15) {
tyrant.get_rivals_raw(*args)
}
info, _ = @our_fp_cache.lookup(tyrant.faction_id, 600) {
tyrant.make_request('getFactionInfo')
}
our_fp = info['rating'] ? info['rating'].to_i : nil
if name
targets = targets.select { |target|
target['name'].downcase.include?(name.downcase)
}
else
targets = targets.select { |target| target['infamy_gain'] == 0 }
end
targets = ::Tyrant.rivalize(targets, our_fp)
m.reply(targets.empty? ? 'No targets!' : ::Tyrant.format_rivals(targets))
end
end; end; end
<file_sep>/spec/tyrant-declare_spec.rb
require_relative 'test-common'
require 'cinch/plugins/tyrant-declare'
describe Cinch::Plugins::TyrantDeclare do
include Cinch::Test
let(:bot) {
make_bot(Cinch::Plugins::TyrantDeclare) { |c|
self.loggers.stub('debug') { nil }
}
}
it 'makes a test bot' do
expect(bot).to be_a Cinch::Bot
end
describe '!declare' do
let(:message) { make_message(bot, '!declare aa', channel: '#test') }
before :each do
@conn = FakeConnection.new
@tyrant = Tyrants.get_fake('testplayer', @conn)
expect(Tyrants).to receive(:get).with('testplayer').and_return(@tyrant)
message.user.stub(:master?).and_return(true)
end
it 'refuses if there is nobody with this name' do
@conn.respond('getFactionRivals', 'name=aa', {'rivals' => []})
replies = get_replies_text(message)
expect(replies).to be == ['No, there is nobody with that name']
end
it 'refuses if the request is ambiguous' do
@conn.respond('getFactionRivals', 'name=aa', {'rivals' => [
{
'faction_id' => '2001',
'rating' => '1',
'name' => 'baa',
'infamy_gain' => 0,
'less_rating_time' => 0,
},
{
'faction_id' => '2002',
'rating' => '2',
'name' => 'kaa',
'infamy_gain' => 0,
'less_rating_time' => 0,
},
]})
replies = get_replies_text(message)
expect(replies).to be == ['No, that is ambiguous, 2']
end
it 'refuses if the declaration would incur infamy' do
@conn.respond('getFactionRivals', 'name=aa', {'rivals' => [
{
'faction_id' => '2001',
'rating' => '1',
'name' => 'baa',
'infamy_gain' => 1,
'less_rating_time' => 0,
},
]})
replies = get_replies_text(message)
expect(replies).to be == ['No, that would get us infamy']
end
context 'when declaration would earn less FP' do
before :each do
@conn.respond('getFactionRivals', 'name=aa', {'rivals' => [
{
'faction_id' => '2001',
'rating' => '1',
'name' => 'baa',
'infamy_gain' => 0,
'less_rating_time' => Time.now.to_i,
},
]})
end
it 'refuses if the declaration would earn less FP' do
replies = get_replies_text(message)
expect(replies).to be == ['Are you sure? That would give reduced FP']
end
it 'declares with confirmation' do
m = make_message(bot, '!declare --yes-really aa', channel: '#test')
m.user.stub(:master?).and_return(true)
@conn.respond(
'declareFactionWar', 'target_faction_id=2001&infamy_gain=0',
{'result' => true}
)
replies = get_replies_text(m)
expect(replies).to be == [true]
end
end
it 'declares the war if everything is fine' do
@conn.respond('getFactionRivals', 'name=aa', {'rivals' => [
{
'faction_id' => '2001',
'rating' => '1',
'name' => 'baa',
'infamy_gain' => 0,
'less_rating_time' => 0,
},
]})
@conn.respond(
'declareFactionWar', 'target_faction_id=2001&infamy_gain=0',
{'result' => true}
)
replies = get_replies_text(message)
expect(replies).to be == [true]
end
end
end
<file_sep>/spec/tyrant-vault_spec.rb
require_relative 'test-common'
require 'cinch/plugins/tyrant-vault'
describe Cinch::Plugins::TyrantVault do
include Cinch::Test
let(:bot) {
make_bot(Cinch::Plugins::TyrantVault, {:checker => 'testplayer'}) { |c|
self.loggers.stub('debug') { nil }
}
}
it 'makes a test bot' do
expect(bot).to be_a Cinch::Bot
end
describe '!vault' do
let(:message) { make_message(bot, '!vault', channel: '#test') }
before :each do
@conn = FakeConnection.new
@tyrant = Tyrants.get_fake('testplayer', @conn)
expect(Tyrants).to receive(:get).with('testplayer').and_return(@tyrant)
end
it 'shows vault cards' do
bot.plugins[0].stub(:shared).and_return({:cards_by_id => {
1 => FakeCard.new(1, 'My first card'),
2 => FakeCard.new(2, 'Another awesome card'),
}})
@conn.respond('getMarketInfo', '', {
'cards_for_sale' => ['1', '2'],
'cards_for_sale_starting' => Time.now.to_i,
})
replies = get_replies_text(message)
expect(replies.shift).to be =~
/^\[VAULT\] My first card, Another awesome card\. Available for \d\d:\d\d:\d\d$/
expect(replies).to be == []
end
end
# TODO: revault?!
end
<file_sep>/spec/tyrant-conquest-commands_spec.rb
require_relative 'test-common'
require 'cinch/plugins/tyrant-conquest-commands'
describe Cinch::Plugins::TyrantConquestCommands do
include Cinch::Test
let(:bot) {
make_bot(Cinch::Plugins::TyrantConquestCommands) { |c|
self.loggers.stub('debug') { nil }
}
}
it 'makes a test bot' do
expect(bot).to be_a Cinch::Bot
end
# TODO TyrantConquestCommands tests
end
<file_sep>/spec/tyrant-war_spec.rb
require_relative 'test-common'
require 'cinch/plugins/tyrant-war'
describe Cinch::Plugins::TyrantWar do
include Cinch::Test
let(:bot) {
make_bot(Cinch::Plugins::TyrantWar) { |c|
self.loggers.stub('debug') { nil }
}
}
it 'makes a test bot' do
expect(bot).to be_a Cinch::Bot
end
describe '!war' do
before :each do
@conn = FakeConnection.new
@tyrant = Tyrants.get_fake('testplayer', @conn)
expect(Tyrants).to receive(:get).with('testplayer').and_return(@tyrant)
end
let(:message) { make_message(bot, '!war', channel: '#test') }
it 'informs the user when there are no wars' do
@conn.respond('getActiveFactionWars', '', {'wars' => {}})
replies = get_replies_text(message)
expect(replies).to be == ['No wars!']
end
it 'shows wars' do
@conn.respond('getActiveFactionWars', '', {'wars' => {
'1' => {
'faction_war_id' => '1',
'name' => 'THE ENEMY',
'attacker_faction_id' => '1000',
'defender_faction_id' => '1001',
'start_time' => Time.now.to_i.to_s,
'duration' => '6',
'atk_pts' => '0',
'def_pts' => '0',
},
}})
replies = get_replies_text(message)
expect(replies.shift).to be =~
/^\s*1 - faction 1000 vs THE ENEMY 0-0 \(\+0\) \d\d:\d\d:\d\d left$/
expect(replies).to be == []
end
end
describe '!war <id>' do
before :each do
@conn = FakeConnection.new
@tyrant = Tyrants.get_fake('testplayer', @conn)
expect(Tyrants).to receive(:get).with('testplayer').and_return(@tyrant)
end
let(:message) { make_message(bot, '!war 1', channel: '#test') }
# TODO: If ID is invalid?
it 'shows war stats' do
@conn.respond('getFactionWarInfo', 'faction_war_id=1', {
'faction_war_id' => '1',
'name' => '<NAME>',
'attacker_faction_id' => '1000',
'defender_faction_id' => '1001',
'start_time' => Time.now.to_i.to_s,
'duration' => '6',
'atk_pts' => '0',
'def_pts' => '0',
})
@conn.respond('getOldFactionWars', '', {'wars' => {
}})
@conn.respond('getFactionWarRankings', 'faction_war_id=1', {'rankings' => {
'1000' => {},
'1001' => {},
}})
replies = get_replies_text(message)
expect(replies.shift).to be =~
/^\s*1 - faction 1000 vs THE ENEMY 0-0 \(\+0\) \d\d:\d\d:\d\d left$/
# TODO: eh, somewhat better checking
expect(replies.shift).to be =~ /Active players/
expect(replies).to be == []
end
end
# TODO: !war <id> <player>
# TODO: !war -v <id>
# TODO: !ws
end
| 0076feff778c18815f3b92b329e10a63e57f5a2c | [
"Ruby"
] | 11 | Ruby | aember/cinch-tyrant | a70f5b4ff2b39c2bc93e2af256c6d4abc5d78164 | d522a72b2c01bb74717a58a6d9edc216642a17d0 |
refs/heads/master | <repo_name>ksurakka/ustate<file_sep>/src/ustate.ts
export type HandlerFuncWithoutParam<TState> = (state:TState, dispatcher: Dispatcher<any>) => TState;
export function isHandlerFuncWithoutParam<TState>(handler: any): handler is HandlerFuncWithoutParam<TState> {
return typeof handler == 'function' && handler.length==1;
}
export type HandlerFuncWithParam<TState, TParam> = (state:TState, param:TParam, dispatcher: Dispatcher<any>) => TState;
export function isHandlerFuncWithParam<TState>(handler: any): handler is HandlerFuncWithParam<TState, any> {
return typeof handler == 'function' && handler.length>1;
}
export type HandlerFunc<TState> = HandlerFuncWithParam<TState, any> | HandlerFuncWithoutParam<TState>;
export type StateSelectorWithoutParam<TState, TSelectedState> = (state:TState) => TSelectedState;
export type StateSelectorWithParam<TState, TSelectedState, TParam> = (state:TState, param:TParam) => TSelectedState;
export type StateSelector<TState, TSelectedState> = StateSelectorWithoutParam<TState, TSelectedState> | StateSelectorWithParam<TState, TSelectedState, any>;
export type NestedSelectorWithoutParam<TState, TNestedState> = () => {
get: (state:TState) => TNestedState;
update: (state:TState, nestedState:TNestedState) => TState;
}
export type NestedSelectorWithParam<TState, TNestedState, TParam> = (param:TParam) => {
get: (state:TState) => TNestedState;
update: (state:TState, nestedState:TNestedState) => TState;
}
export type NestedHandlersWithoutParam<TState, TNestedState, THandlers extends Handlers<TNestedState>> = {
selector: NestedSelectorWithoutParam<TState, TNestedState>,
handlers: THandlers
}
export type NestedHandlersWithParam<TState, TNestedState, THandlers extends Handlers<TNestedState>, TParam> = {
selector: NestedSelectorWithParam<TState, TNestedState, TParam>,
handlers: THandlers
}
function isNestedHandlersWithoutParam<TState>(handlers:any): handlers is NestedHandlersWithoutParam<TState, any, any> {
return (handlers as NestedHandlersWithoutParam<TState, any, any>).selector?.length==0;
}
function isNestedHandlersWithParam<TState>(handlers:any): handlers is NestedHandlersWithParam<TState, any, any, any> {
return (handlers as NestedHandlersWithoutParam<TState, any, any>).selector?.length==1;
}
export type Handlers<TState> = {
[key:string]: HandlerFunc<TState> | NestedHandlersWithoutParam<TState, any, any> | NestedHandlersWithParam<TState, any, any, any>;
}
export type DispatcherFuncWithParam<TParam> = (param:TParam) => void;
export type DispatcherFuncWithoutParam = () => void;
export type Dispatcher<THandlers> = {
[key in keyof THandlers]: THandlers[key] extends HandlerFuncWithoutParam<any> ? DispatcherFuncWithoutParam :
THandlers[key] extends HandlerFuncWithParam<any, infer TParam> ? DispatcherFuncWithParam<TParam> :
THandlers[key] extends NestedHandlersWithoutParam<any, any, infer TNestedHandlers> ? Dispatcher<TNestedHandlers> :
THandlers[key] extends NestedHandlersWithParam<any, any, infer TNestedHandlers, infer TParam> ? (param:TParam) => Dispatcher<TNestedHandlers> :
never;
};
export type ChangeListenerFunc<TState> = (state:TState, oldState:TState) => void;
export type RemoveListenerFunc = () => void;
export type StateMachine<TState, THandlers> = {
onChange: (listener:ChangeListenerFunc<TState>) => RemoveListenerFunc;
getState: () => TState;
dispatcher: Dispatcher<THandlers>
}
type DispatcherQueue = {
push: (dispatchFunc:() => void) => void;
}
function createDispatcher<TState, THandlers extends Handlers<TState>>(
handlers:THandlers,
getState: () => TState,
updateState: (newState:TState, oldState:TState) => void,
queue: DispatcherQueue
): Dispatcher<THandlers> {
const nestedDispatcherCache:{
[key:string]: Dispatcher<any>
} = {};
const dispatcher:Dispatcher<THandlers> = Object.keys(handlers).reduce((dispatcher, key) => {
const handler = handlers[key];
let dispatcherItem:DispatcherFuncWithoutParam | DispatcherFuncWithParam<any> |
Dispatcher<any> | undefined = undefined;
if (isHandlerFuncWithoutParam<TState>(handler)) {
dispatcherItem = () => {
queue.push(() => {
const state = getState();
const newState = handler(state, dispatcher);
updateState(newState, state);
});
}
} else if (isHandlerFuncWithParam<TState>(handler)) {
dispatcherItem = (param:any) => {
queue.push(() => {
const state = getState();
const newState = handler(state, param, dispatcher);
updateState(newState, state);
});
}
} else if (isNestedHandlersWithParam(handler)) {
dispatcherItem = (param:any) => {
const cacheKey = key+JSON.stringify(param);
if (!nestedDispatcherCache[cacheKey]) {
nestedDispatcherCache[cacheKey] =
createDispatcher(
handler.handlers,
() => {
const selector = handler.selector(param);
return selector.get(getState())
},
(newNestedState) => {
const state = getState();
const selector = handler.selector(param);
const newState = selector.update(state,newNestedState);
updateState(newState as any, state)
},
queue
)
}
return nestedDispatcherCache[cacheKey];
};
} else if (isNestedHandlersWithoutParam(handler)) {
dispatcherItem = createDispatcher(
handler.handlers,
() => {
const selector = handler.selector();
return selector.get(getState())
},
(newNestedState) => {
const state = getState();
const selector = handler.selector();
const newState = selector.update(state,newNestedState);
updateState(newState as any, state)
},
queue
);
}
return {
...dispatcher,
...dispatcherItem ? {[key] : dispatcherItem} : {}
}
}, {} as Dispatcher<THandlers>); // TODO: tseggaa miten voi alustaa ilman "as"
return dispatcher as Dispatcher<THandlers>;
}
export function createMachine<TState, THandlers extends Handlers<TState>>(
initialState:TState, handlers:THandlers): StateMachine<TState, THandlers> {
let state = {...initialState};
let executing = false;
let queuedFuncs:(()=>void)[] = [];
const queue:DispatcherQueue = {
push: (func:() => void) => {
queuedFuncs.push(func);
if (!executing) {
executing = true;
while(queuedFuncs.length) {
const nextFunc = queuedFuncs.shift();
nextFunc && nextFunc();
}
executing = false;
}
}
}
const dispatcher = createDispatcher(
handlers,
() => state,
(newState, oldState) => {
state = newState;
},
queue
);
return {
getState: () => state,
onChange: (listener:ChangeListenerFunc<TState>) => () => undefined,
dispatcher: dispatcher,
};
}
// Testing
type InnerState = {
age: number;
}
type FooState = {
name: string;
inner: InnerState;
collection: InnerState[];
}
const initialFooState:FooState = {
name: '<NAME>',
inner: {
age: 40
},
collection: [
{
age: 120
},
{
age: 75
},
]
};
const fooHandlers = {
add: (state:FooState, text:string):FooState => {
console.log('add', text)
return state;
},
noParam: (state:FooState):FooState => {
console.log('noParam');
return state;
},
noParamAndDispatcher: (state:FooState, dispatcher:Dispatcher<any>):FooState => {
console.log('noParamAndDispatcher');
return state;
},
param: (state:FooState, someVal:number):FooState => {
console.log('param', someVal);
return state;
},
paramAndDispatcher: (state:FooState, someVal:number, dispatcher:Dispatcher<any>):FooState => {
console.log('paramAndDispatcher');
return state;
},
myInner: {
selector: () => ({
get: (state:FooState) => state.inner,
update: (state:FooState, inner:InnerState) => ({...state, inner})
}),
handlers: {
increase: (state:InnerState, amount:number):InnerState => {
return state;
}
}
},
collection: {
selector: (index: number) => ({
get: (state:FooState) => state.collection[index],
update: (state:FooState, inner:InnerState) => ({...state, collection: state.collection.map((item, idx) => idx==index ? inner : item)})
}),
handlers: {
decrease: (state:InnerState, amount:number):InnerState => {
return {...state, age: state.age-amount};
}
}
}
}
const m = createMachine(initialFooState, fooHandlers);
const d = m.dispatcher;
// d.paramAndDispatcher(5);
// d.param(14);
// d.noParam();
// d.noParamAndDispatcher();
// d.myInner.increase(45);
// d.collection(1).decrease(12);
// function nested<
// TState,
// TNestedState,
// TParam = 'xxx', // this is the trick
// // StateSelectorWithoutParam<TState, TNestedState> |
// // StateSelectorWithParam<TState,TNestedState, TParam>
// >(
// //selector: ((state:TState) => any) | ((state:TState, p:TParam) => any),
// selector: StateSelectorWithoutParam<TState, TNestedState> | StateSelectorWithParam<TState,TNestedState, TParam>
// // handlers: THandlers
// ): TParam extends 'xxx' ? number : string
// // TStateSelector extends StateSelectorWithParam<TState, TNestedState, infer TSelectorParam> ? number :
// // TStateSelector extends StateSelectorWithoutParam<TState, TNestedState> ? any : any
// {
// return 10 as any;
// }
<file_sep>/README.md
# μState
A simple state management library<file_sep>/test/dispatcher.test.ts
import * as ustate from '../src/ustate';
type TestState = {
val: number;
}
test('Dispatcher func without param', () => {
let callCount = 0;
const m = ustate.createMachine(
{
val: 1
},
{
add: (state:TestState) => {
callCount++;
return {
...state,
val: state.val+1
}
}
}
);
expect(callCount).toBe(0);
expect(m.getState().val).toBe(1);
m.dispatcher.add();
expect(callCount).toBe(1);
expect(m.getState().val).toBe(2);
});
test('Dispatcher func with param', () => {
let callCount = 0;
const m = ustate.createMachine(
{
val: 1
},
{
add: (state:TestState, amount:number) => {
callCount++;
return {
...state,
val: state.val+amount
}
}
}
);
expect(callCount).toBe(0);
expect(m.getState().val).toBe(1);
m.dispatcher.add(5);
expect(callCount).toBe(1);
expect(m.getState().val).toBe(6);
});
test('Nested dispatcher without param', () => {
type SubState = {
some: string;
}
type RootState = {
val: number;
sub: SubState
}
let callCount = 0;
const m = ustate.createMachine(
{
val: 1,
sub: {
some: 'foo'
}
},
{
sub: {
selector: () => ({
get: (state:RootState) => state.sub,
update: (state:RootState, newSub:SubState) => ({...state, sub:newSub})
}),
handlers: {
reverse: (state:SubState) => {
callCount++;
return {
...state,
some: state.some.split('').sort(()=>-1).join('')
}
}
}
}
}
);
expect(callCount).toBe(0);
expect(m.getState().sub.some).toBe('foo');
m.dispatcher.sub.reverse();
expect(callCount).toBe(1);
expect(m.getState().sub.some).toBe('oof');
});
test('Nested dispatcher with param', () => {
type SubState = {
some: string;
}
type RootState = {
val: number;
subCollection: SubState[]
}
let callCount = 0;
const m = ustate.createMachine(
{
val: 1,
subCollection: [{
some: 'first'
}, {
some: 'second'
}]
},
{
sub: {
selector: (index:number) => ({
get: (state:RootState) => state.subCollection[index],
update: (state:RootState, newSub:SubState) => ({...state, subCollection: state.subCollection.map((sub, idx) => idx==index ? newSub : sub)})
}),
handlers: {
reverse: (state:SubState) => {
callCount++;
return {
...state,
some: state.some.split('').sort(()=>-1).join('')
}
}
}
}
}
);
expect(callCount).toBe(0);
expect(m.getState().subCollection[1].some).toBe('second');
m.dispatcher.sub(1).reverse();
expect(callCount).toBe(1);
expect(m.getState().subCollection[1].some).toBe('dnoces');
});
<file_sep>/test/ustate.test.ts
import * as ustate from '../src/ustate';
test('Foo test', () => {
// expect(ustate.createMachine).toBe('TBD');
});
| e37320f7f0b6553e8dfee2eedd5476246ee5f1c6 | [
"Markdown",
"TypeScript"
] | 4 | TypeScript | ksurakka/ustate | fb3c12bb7396d855e22db81193fc887792ab3487 | 0602c29f22c7fbf60d07edeba3f940164dcc37d5 |
refs/heads/main | <file_sep>from pytube import YouTube
import time
import sys
import os
import youtube_dl
print("\033[1;32;40m")
def banner():
os.system('clear')
time.sleep(1)
print (" YOUTUBE VIDEO DOWNLOADER AND YOUTUBE VIDEO TO MP3 CONVERTER ")
time.sleep(1)
print ("##########################################")
time.sleep(1)
print ( """
_______________________________
| |
| Coded by H3LL0-H4CK3R |
| Thanks for using my tool |
|______________________________|\n""")
time.sleep(1)
print("############################################\n")
time.sleep(1)
def load():
def spinning_cursor():
while True:
for cursor in '|/-\\':
yield cursor
spinner = spinning_cursor()
for _ in range(50):
sys.stdout.write(next(spinner))
sys.stdout.flush()
time.sleep(0.1)
sys.stdout.write('\b')
def downloadVideo():
print("\033[1;32;40m")
print("PROGRAM STARTED")
time.sleep(1)
print("DOWNLODE YOUTUBE VIDEOS WITH MY TOOL ")
print("\033[1;31;40m")
time.sleep(1)
print("\033[1;32;40m")
print("###################################")
print("\033[1;32;40m")
time.sleep(1)
print("\033[1;32;40m")
link = input("Enter Your Link Here : ")
print("\033[1;36;40m")
print ("Please wait")
time.sleep(1)
print("\033[1;32;40m")
print("Downloding...")
YouTube(link).streams.first().download()
print("\033[1;35;40m")
print("Video downloaded successfully")
time.sleep(1)
print("\033[1;33;40m ")
print("PROGRAM FINISHED")
sys.exit(0)
def downloadMusic():
print("\033[1;32;40m")
print("PROGRAM STARTED")
time.sleep(1)
print("###################################")
print("\033[1;36;40m")
time.sleep(1)
print("YOU CAN CONVERT YOUTUBE VIDEOS TO MP3 WITH MY TOOL ")
print("\033[1;31;40m")
time.sleep(1)
print("###################################")
print("\033[1;32;40m")
time.sleep(1)
link = input("Enter Your Link Here : ")
print("\033[1;36;40m")
print ("Please wait")
time.sleep(1)
print("\033[1;32;40m")
print("Converting...")
params ={
'format': 'bestaudio/best',
'postprocessors':[{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'MP3',
'preferredquality': '192',
}],
}
youtube= youtube_dl.YoutubeDL(params)
try:
youtube.download([link])
except:
print("")
time.sleep(1)
print (" VIDEO TO MP3 CONVERTED SUCCESSFULLY ")
time.sleep(1)
print ("PROGRAM FINISHED ")
sys.exit(0)
def main():
banner()
load()
print("[1] YT VIDEO DOWNLOADER [2] YT VIDEO TO MP3 CONVERTER ")
print('')
option=input('Enter the option : ')
if option=='1' or option=='01':
downloadVideo()
elif option=='2' or option=='02':
downloadMusic()
else:
print("\033[1;31;40m")
print ('Invalid Option!')
sys.exit(0)
main()
main()
<file_sep><a href="https://telegram.im/@H3LLO_H4CK3R"><img title="Follow ME On Telegram" src="https://img.shields.io/badge/Follow Me On Telegram-black?style=for-the-badge&logo=Telegram"></a>
[](https://github.com/H3LLO-H4CK3R-2)
[](https://github.com/H3LLO-H4CK3R-2?tab=repositories)

# HOW TO USE
cd Yt-Video-Mp3-Converter
ls
you can choose any
your choice
for downlode youtube videos choose [ Yt-Downloder.py ]
for convert youtube videos to mp3 choose [ Yt-Mp3-Converter.py ]
after converting and downloding
mv your mp3 or video to sdcard
example
mv your-file.mp3 /sdcard
mv your-file.mp4 /sdcard
after this you can play all the things
# FINISHED

<file_sep>pkg install lolcat
clear
echo "INSTALLING PAKAGES" |lolcat
sleep 3
pip install pytube
pip install youtube_dl
pip install pytube3
echo " INSTALLING COMPLETED" |lolcat
sleep 3
echo " Thanks For Using My Tool " |lolcat
sleep 3
echo " FINISHED " |lolcat
| 3fb7f4a168649a42dbb2dd4660715a04c6a6e62d | [
"Markdown",
"Python",
"Shell"
] | 3 | Python | H3LLO-H4CK3R-2/Yt-Video-Mp3-Converter | 40c3545481375b5b4466f9796f5df4e9a9547672 | 33aca0cef461af3a69e040cf5cf6d75081bbe520 |
refs/heads/master | <file_sep>
import React, { Component, Fragment } from 'react';
import MyName from './MyName';
import Counter from './Counter';
import './App.css'
class App extends Component {
render(){
const name = 'react';
const value = 1;
{/*스타일을 이렇게 지정할 수도 있어요. */}
const style = {
backgroundColor : 'black',
padding: '16px',
color: 'white',
fontSize: '12pt'
}
return(
<Fragment>
{/* 주석은 이렇게 씁니다. */}
<div style={style}>
Hello {name};
<h1 //태그사이에도
>Check</h1>
</div>
<div className="App">
Bye
</div>
<div>
{
//삼항연산자를 사용할 수도 있고
1 + 1 == 2
? (<div>맞아요!</div>)
: (<div>틀려요!</div>)
//익명함수인 화살표 함수로도 쓸 수 있습니다.
(() => {
if (value === 1) return (<div>하나</div>)
})()
}
</div>
{/*
리액트에서 데이터를 다루는 방법 : props
부모 컴포넌트가 자식 컴포넌트에게 주는 값 입니다.
자식 컴포넌트에서는 받아오기만 하고 props를 수정할 수 없어요
*/}
<MyName name="리액트"/>
{/*
<MyName />
name을 생략했을 때 어떻게 되는지 확인 해보기
*/}
<Counter />
</Fragment>
);
}
}
export default App;
<file_sep>import React, { Component } from 'react'
class Counter extends Component{
state = {
number: 0
}
//컴포넌트가 새로 만들어 질 때마다 호출되는 함수
constructor(props) {
super(props);
console.log('constructor');
}
//화면에 나타나기 직전에 호출되는 API - v16.3이후 deprecated
componentWillMount() {
console.log('componentWillMount (deprecated) ');
}
//화면에 나타나게 되었을 때 호출, 외부 라이브러리 연동 및 DOM 변경 등의 작업
componentDidMount() {
console.log('componentDidMount');
}
//최적화 하는 작업에서 유용하게 사용됨.
//리턴 값이 true일 때만 렌더링 가능! (false이면 render() 호출 안함)
shouldComponentUpdate(nextProps, nextState){
console.log('shouldComponentUpdate');
if(nextState.number % 5 === 0) return false;
return true;
}
//shouldComponentUpdate에서 true를 반환했을 때 호출
//애니메이션 효과 초기화 하거나, 이벤트 리스너 없애기
componentWillUpdate(nextProps, nextState){
console.log('componentWillUpdate - deprecated');
}
//render() 호출한 뒤에 발생한다.
//
componentDidUpdate(preProps, prevState){
console.log('componentDidUpdate');
}
handleIncrease = () => {
//state의 값을 바뀌기 위해서는 setState!!
const { number } = this.state;
this.setState({
number: number + 1
});
}
handleDecrease = () => {
this.setState(
({ number }) => ({
number: number -1
})
);
}
render(){
console.log('render');
return(
<div>
<h1>Counter</h1>
<div>값-> {this.state.number}</div>
<button onClick={this.handleIncrease}>+</button>
<button onClick={this.handleDecrease}>-</button>
</div>
//이벤트 이름은 camelCase로, 전달값은 함수!
//전달값이 메소드일 경우, 렌더링 될 떄마다 호출되어서 무한루프에 빠지게 된다!
);
}
}
export default Counter; | ff38e749bb870f19b86aadf213d2cf87ea2a8e97 | [
"JavaScript"
] | 2 | JavaScript | Oaroomy/React_Tutorial | 0ff7896a2cf57e50de57dac4289b9d054589aebd | bacba19b2927d7c796ef819a77b42588112ab759 |
refs/heads/master | <repo_name>nataliasayang/ml-mini-course<file_sep>/python_machine_learning_mini-course.py
# -*- coding: utf-8 -*-
"""
Machine learning Mastery
Python Machine Learning Mini-Course
https://machinelearningmastery.com/python-machine-learning-mini-course/
"""
#Lesson 1: Download and Install Python and SciPy ecosystem.
#Lesson 2: Get Around In Python, NumPy, Matplotlib and Pandas.
#Practice assignment, working with lists and flow control in Python.
#Practice working with NumPy arrays.
#Practice creating simple plots in Matplotlib.
#Practice working with Pandas Series and DataFrames.
import numpy
import pandas
import matplotlib.pyplot as plt
myarray = numpy.array([[1, 2, 3], [4, 5, 6]])
rownames = ['a', 'b']
colnames = ['one', 'two', 'three']
mydataframe = pandas.DataFrame(myarray, index=rownames, columns=colnames)
print(mydataframe)
df = pandas.read_csv("avg_temp_dc_by_month.csv")
print(df)
ax = plt.gca()
df.plot(kind='line', x='Month', y='High F', color='red', ax=ax)
df.plot(kind='line', x='Month', y='Low F', color='blue', ax=ax)
df.plot(kind='line', x='Month', y='Avg F', color='yellow', ax=ax)
plt.title('Monthly Temperatures in Washington, D.C.')
plt.show() | 77a89be450af78c5007173b77903919cd6c34242 | [
"Python"
] | 1 | Python | nataliasayang/ml-mini-course | 3789d422d66f57adfbfcfe55527736737f3bb752 | b935f726019da3fc4a19ac6442f4204e1a2435cb |
refs/heads/master | <file_sep># ids2019-m16-traffic-violations
Project M16: Analysis of traffic violations in Estonia
data being analyzed: https://opendata.riik.ee/andmehulgad/liiklusjarelevalve-alased-syyteod/
# starting out
run `./fetch.sh` to download the dataset. open up the notebooks and take a look
<file_sep>#!/bin/sh
sudo apt install libgeos++-dev libproj-dev
pip install geoplot
pip install geopandas
<file_sep>#!/bin/bash
cd notebooks
jupyter nbconvert --execute Data\ Cleaning.ipynb
rm Data\ Cleaning.html
mkdir images
<file_sep>#!/bin/bash
rm -rf data/
echo "getting last 5 years worth"
mkdir data
cd data
wget https://opendata.smit.ee/ppa/csv/liiklusjarelevalve_2.csv
echo "getting map outline from maaamet"
mkdir map
cd map
wget https://geoportaal.maaamet.ee/docs/haldus_asustus/maakond_shp.zip
unzip maakond_shp.zip
| b008468a5be03cac32156fc2d9c60ecd8bd0493c | [
"Markdown",
"Shell"
] | 4 | Markdown | snemvalts/ids2019-m16-traffic-violations | 0b3602b79bbb27c8e61c5bf0bf3c80786b139f21 | 00089c1675af5b96d3af1f682b2be4f66f05594b |
refs/heads/master | <repo_name>DOXNPN/pygame<file_sep>/memoryPuzzle-2.py
import pygame,sys,random
from pygame.locals import *
PADWIDTH=6
PADHEIGHT=5
BOXSIZE=60
GAPSIZE=10
ALLPOTO=15
WINX=600
WINY=500
TEXT='You Are Win!'
text='press esc to quit'
#-------红 绿 蓝
WHITE=(255,255,255)
BLUE =( 0, 0,255)
RED =(255, 0, 0)
BLACK=( 0, 0, 0)
X=int((WINX-(BOXSIZE+GAPSIZE)*PADWIDTH)/2)
Y=int((WINY-(BOXSIZE+GAPSIZE)*PADHEIGHT)/2)
screen=pygame.display.set_mode((WINX,WINY))
pygame.display.set_caption('猜图案')
#-------------------------------------------------------------------------------------------------------------------------
# 主函数
def main():
gameover=False
pygame.init()
mx,my=0,0
imagePad=imageLoad()
firstSelect=None
startGameAnimation(imagePad)
font=pygame.font.SysFont('arial',64)
font1=pygame.font.SysFont('arial',32)
font2=pygame.font.SysFont('arial',20)
score=0
p=0
while True:
drawGamePad()
mouseClick=False
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
if event.type==MOUSEMOTION:
mx,my=event.pos
if event.type==MOUSEBUTTONUP:
mx,my=event.pos
mouseClick=True
if isInBox(mx,my): # 检验鼠标是否落在白色图标上,若在则使图标显示为蓝色。
boxx,boxy=getBoxfromPixel(mx,my)
left,top=xyTolefttop(mx,my)
pygame.draw.rect(screen,BLUE,(left,top,BOXSIZE,BOXSIZE))
if not imagePad[boxx][boxy][1] and mouseClick: # 当鼠标在该白色图标上,且该图标未被点击过,此时点击该图标
# 并将其属性设置为True
imagePad[boxx][boxy][1]=True
if firstSelect==None: #firstSelect值为空时代表此前未发生点击图标事件,
#当点击图标时将该图标坐标赋值给firstSelect.
#代表第一次点击图标,当第二次点击图标时,条件判断选择执行else。
firstSelect=(boxx,boxy)
else:
if imagePad[firstSelect[0]][firstSelect[1]][0]==imagePad[boxx][boxy][0]:
imagePad[firstSelect[0]][firstSelect[1]][2],imagePad[boxx][boxy][2]=True,True
p=10
elif imagePad[firstSelect[0]][firstSelect[1]][0]!=imagePad[boxx][boxy][0]:
imagePad[firstSelect[0]][firstSelect[1]][1],imagePad[boxx][boxy][1]=False,False
p=-1
firstSelect=None
score+=p
pygame.draw.rect(screen,BLACK,(0,0,100,30))
screen.blit(font2.render('score:'+str(score),True,(255,255,255)),(0,0))
if score==-10:
gameover=True
for x in range(PADWIDTH):
for y in range(PADHEIGHT):
left,top=getlefttopfromBox(x,y)
if imagePad[x][y][1] or imagePad[x][y][2]:
image=pygame.image.load(imagePad[x][y][0])
screen.blit(image,(left,top))
if hasWon(imagePad):
pygame.time.wait(1000)
screen.fill(WHITE)
screen.blit(font.render(TEXT,True,(0,0,0)),(WINX/2-180,WINY/2-30))
screen.blit(font1.render(text,True,(0,0,0)),(WINX/2-100,WINY/2+50))
screen.blit(font1.render('Score:'+str(score),True,(0,0,0)),(WINX/2-100,WINY/2+90))
for event in pygame.event.get():
if event.type==KEYDOWN:
if event.key==K_ESCAPE:
pygame.quit()
sys.exit()
if gameover:
screen.fill(WHITE)
screen.blit(font1.render('press Q to quit.',True,(0,0,0)),(WINX/2-100,WINY/2+50))
screen.blit(font.render('GAME OVER',True,(0,0,0)),(WINX/2-210,WINY/2-30))
for event in pygame.event.get():
if event.type==KEYUP:
if event.key==K_q:
pygame.quit()
sys.exit()
pygame.display.update()
#(1)------------------------------------------------------------------------------------------------------------------------
def gamePad(val):
'''函数创建存储游戏板数据的二维列表,由 imageLoad函数调用,用于加载图片使用'''
padlist=[]
for i in range(PADWIDTH):
padlist.append([val]*PADHEIGHT)
return padlist
#(2)------------------------------------------------------------------------------------------------------------------------
def potoArray():
'''函数返回存储有游戏图片的列表,由imageLoad函数调用,用于加载图片使用。'''
potolist=[]
for i in range(ALLPOTO):
potolist.append('%d.png'%(i+1))
potolist*=2
random.shuffle(potolist)
return potolist
#(3)------------------------------------------------------------------------------------------------------------------------
def imageLoad():
'''把图片数据加载到游戏板数据列表中,函数返回一个二维列表,该列表存储图片信息和bool值的元组'''
p=potoArray()
g=gamePad(False)
for x in range(PADWIDTH):
for y in range(PADHEIGHT):
g[x][y]=[p[0],False,False]
del p[0]
return g # 存储图片信息和状态信息的三维列表['i.png',False,False]。第二个元素是检验数据项是否被点击的
# 状态,若被点击则为真,否则为假。第三个元素是检验两个图标是否相同的状态,若相同则为真,否则为假。
#(4)------------------------------------------------------------------------------------------------------------------------
def getlefttopfromBox(boxx,boxy):
'''从方块坐标中获取像素坐标'''
left=X+boxx*(BOXSIZE+GAPSIZE)
top=Y+boxy*(BOXSIZE+GAPSIZE)
return (left,top)
#(5)------------------------------------------------------------------------------------------------------------------------
def isInBox(x,y):
'''判断像素坐标是否在方块坐标内,若在返回真,若不在返回假'''
for boxx in range(PADWIDTH):
for boxy in range(PADHEIGHT):
p=getlefttopfromBox(boxx,boxy)
if x in range(p[0],p[0]+BOXSIZE) and y in range(p[1],p[1]+BOXSIZE):
return True
return False
#(6)------------------------------------------------------------------------------------------------------------------------
def getBoxfromPixel(x,y):
'''获取像素坐标所在位置的方块坐标'''
for boxx in range(PADWIDTH):
for boxy in range(PADHEIGHT):
p=getlefttopfromBox(boxx,boxy)
if x in range(p[0],p[0]+BOXSIZE) and y in range(p[1],p[1]+BOXSIZE):
return (boxx,boxy)
return (None,None)
#(7)------------------------------------------------------------------------------------------------------------------------
def drawGamePad():
'''绘制游戏板'''
for boxx in range(PADWIDTH):
for boxy in range(PADHEIGHT):
p=getlefttopfromBox(boxx,boxy)
pygame.draw.rect(screen,WHITE,(p[0],p[1],BOXSIZE,BOXSIZE))
#(8)--------------------------------------------------------------------------------------------------------------------------
def xyTolefttop(x,y):
'''从鼠标当前坐标中获取方块所在位置的像素坐标'''
boxx,boxy=0,0
boxx,boxy=getBoxfromPixel(x,y)
left,top=getlefttopfromBox(boxx,boxy)
return (left,top)
#(9)--------------------------------------------------------------------------------------------------------------------------
def startGameAnimation(imageload): #所接受参数应为存储游戏数据板数据的三维列表,是函数imageLoad的返回值。
drawGamePad()
for x in range(PADWIDTH):
for y in range(PADHEIGHT):
left,top=getlefttopfromBox(x,y)
image=pygame.image.load(imageload[x][y][0])
screen.blit(image,(left,top))
pygame.display.update()
pygame.time.wait(3000)
#(10)-----------------------------------------------------------------------------------------------------------------------
def hasWon(imageload): #参数类型同函数(9)
for x in range(PADWIDTH):
for y in range(PADHEIGHT):
if not imageload[x][y][2]:
return False
else:
return True
#-----------------------------------------------------------------------------------------------------------------------------
if __name__=='__main__':
main()
| 6a621ab32f1dfe880bf3a0185dd118ae53a8af27 | [
"Python"
] | 1 | Python | DOXNPN/pygame | 965739ad81ca2049c8b0da36babbaf4cc8963b04 | d21d5899a7fdbb5b10ae1780cca44c617e7f9996 |
refs/heads/master | <repo_name>shcig/Models<file_sep>/Adaptor_for Diamond_nozzle.lua
function circle(radius, split_number, base_height)
pts={}
for i=1.0, split_number, 1.0
do
parameter=2 * math.pi * i/split_number
x = radius * math.cos(parameter)
y = radius * math.sin(parameter)
pts[i]=v(x,y,base_height)
end
return pts
end
screw_head=linear_extrude( v(0,0,2.5) , circle(3.2,6,0))
c00=translate(-70,11.5,11.5)*rotate(0,90,0)*cylinder(1.5,30)
c01=translate(-70,11.5,-11.5)*rotate(0,90,0)*cylinder(1.5,30)
c10=translate(-70,-11.5,-11.5)*rotate(0,90,0)*cylinder(1.5,30)
c11=translate(-70,-11.5,11.5)*rotate(0,90,0)*cylinder(1.5,30)
base_cube=translate(-17.5,0,-17)*(D(D(translate(-5,0,0)*cube(50),cube(50)),translate(-10,0,35)*cube(50)))
c20=translate(-50,15.25,0)*rotate(0,90,0)*cylinder(1.5,10)
c21=translate(-50,-15.25,0)*rotate(0,90,0)*cylinder(1.5,10)
base_cube=D(base_cube,c00)
base_cube=D(base_cube,c10)
base_cube=D(base_cube,c01)
base_cube=D(base_cube,c11)
base_cube=D(base_cube,c20)
base_cube=D(base_cube,c21)
hide=translate(-47.5,0,0)*rotate(0,90,0)*cylinder(3,2.5)
hide1=translate(0,15.25,0)*hide
hide2=translate(0,-15.25,0)*hide
base_cube=D(base_cube,hide1)
base_cube=D(base_cube,hide2)
hide=translate(2.5,0,0)*hide
hide3=translate(11.5,11.5,-45)*screw_head
hide4=translate(-11.5,11.5,-45)*screw_head
hide5=translate(11.5,-11.5,-45)*screw_head
hide6=translate(-11.5,-11.5,-45)*screw_head
base_cube=rotate(0,-90,0)*base_cube
base_cube=D(base_cube,hide3)
base_cube=D(base_cube,hide4)
base_cube=D(base_cube,hide5)
base_cube=D(base_cube,hide6)
emit(D(base_cube,hide3))
<file_sep>/README.md
# Models
Models for 3D printing
| ed1dac25ac1239d0aa99d24886059256de97b8d2 | [
"Markdown",
"Lua"
] | 2 | Lua | shcig/Models | 5e6a4e771651f1adafb148c167fce908c8eed662 | 9d181a55cb24285594a6d3820ca610080ed477ee |
refs/heads/master | <file_sep><?php
namespace Akilli\Event;
/**
* Dispatcher Interface
*
* @author <NAME>
*/
interface Dispatcher
{
/**
* Notifies listeners about specified event with optional event data
*
* @param string $id
* @param Event $event
*
* @return $this
*/
public function trigger(string $id, Event $event = null): Dispatcher;
/**
* Attaches listener to specified event
*
* @param string $id
* @param callable $listener
* @param int $priority
*
* @return $this
*/
public function on(string $id, callable $listener, int $priority = 0): Dispatcher;
/**
* Detaches listener from specified event
*
* @param string $id
* @param callable $listener
*
* @return $this
*/
public function off(string $id, callable $listener): Dispatcher;
}
<file_sep><?php
namespace Akilli\Event;
/**
* Dispatcher Aware
*
* @author <NAME>
*/
interface DispatcherAware
{
/**
* Returns the dispatcher
*
* @return Dispatcher
*/
public function getDispatcher(): Dispatcher;
/**
* Sets the dispatcher
*
* @param Dispatcher $dispatcher
*
* @return $this
*/
public function setDispatcher(Dispatcher $dispatcher): DispatcherAware;
}
| 101572dee6d7d235c4f2b0f4be5ed28665817896 | [
"PHP"
] | 2 | PHP | akilli/event | 0c41c673b0865ea8d8c61f68619826043eb515ea | fb455e290f6e740463f40a9bafd0dee331a89965 |
refs/heads/master | <repo_name>amarjitbh/mitsShare<file_sep>/app/Providers/AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Schema;
use App\PropertyTypeSection;
use Illuminate\Support\Facades\View;
use App\PropertyType;
use Illuminate\Support\Facades\Input;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
Schema::defaultStringLength(191);
app('view')->composer('layouts.nav', function ($view) {
$action = app('request')->route()->getAction();
$controller = class_basename($action['controller']);
//$url = app('request')->url();
list($controller, $action) = explode('@', $controller);
if(($controller == "PropertyTypeSectionFieldController") && ($action == "create"))
{
$paramater = app('request')->route()->parameters();
$propertysectionid = $paramater["propertysectionid"];
$PropertyTypeSection = PropertyTypeSection::find($propertysectionid);
$propertytype_id = $PropertyTypeSection->propertytype()->first();
//print_r($propertytype_id);
}
$view->with(compact('controller', 'action', 'propertytype_id'));
}
);
Validator::extend('unique_custom', function ($attribute, $value, $parameters)
{
// Get the parameters passed to the rule
//unique_custom:property_type_section_fields,id,'. $id_value.',name,property_type_section_id,' . $arr_propertytypesectionid
$new_parameters = $parameters;
unset($new_parameters[0]);
unset($new_parameters[1]);
unset($new_parameters[2]);
unset($new_parameters[3]);
unset($new_parameters[4]);
$table = $parameters[0];
$ignore_field = $parameters[1];
$ignore_id = $parameters[2];
$field1 = $parameters[3];
$field2 = $parameters[4];
//list($table, $field1, $field2) = $parameters;
// Check the table and return true only if there are no entries matching
// both the first field name and the user input value as well as
// the second field name and the second field value
$table= "property_type_section_fields";
$query = \DB::table($table)->select();
$query->where($field1, $value);
//return DB::table($table)
/*
foreach($values as $value)
{
$query->where($field1, $value);
}
*/
if($ignore_field != "NULL")
{
$query->where($ignore_field, '<>', $ignore_id);
}
$query->whereIn($field2, $new_parameters);
return $query->count() == 0;
});
Validator::extend('not_contains', function($attribute, $value, $parameters)
{
// Banned words
$words = array('Basic Information', 'basic information');
foreach ($words as $word)
{
$word = strtolower(str_replace(' ', '', $word));
$value = strtolower(str_replace(' ', '', $value));
if($value == $word)
{
return false;
}
}
return true;
});
Validator::extend('custom_distinct', function($attribute, $value, $parameters, $validator) {
$inputs = $validator->getData();
$sections = $inputs['property_type_section_name'];
$counter = 0;
foreach($sections as $section_value){
$sections[$counter] = strtolower(str_replace(' ', '', $section_value));
$counter++;
}
if(count($sections) != count(array_unique($sections)))
{
return false;
}
else
{
return true;
}
});
\Validator::extend('alpha_spaces', function ($attribute, $value) {
if(!empty($value) && is_array($value) == false){
return preg_match('/^[\pL\s-.]+$/u', $value);
}else {
return true;
}
});
\Validator::extend('alpha_space_numeric', function($attribute, $value){ //pr(is_array($value),1);
if(!empty($value) && is_array($value) == false){
return preg_match('/^[a-z0-9 .\-]+$/i', $value);
}else{
return true;
}
});
/* Files Number Limit */
\Validator::extend('upload_count', function($attribute, $value, $parameters) {
$countedValue = count($value);
return ($countedValue > $parameters[0]) ? false : true;
//$files = Input::file($parameters[0]);pr($files,1);
//return (count($files) <= $parameters[1]) ? true : false;
});
$propertyTypes = PropertyType::where(['deleted_at' => NULL])
->get(['name','id'])->toArray();
View::share('propertyTypes',$propertyTypes );
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
<file_sep>/database/migrations/2017_10_10_042409_add_display_to_filter_to_property_type_section_fields.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddDisplayToFilterToPropertyTypeSectionFields extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('property_type_section_fields', function($table) {
$table->integer('display_to_filter');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('property_type_section_fields', function($table) {
$table->dropColumn('display_to_filter');
});
}
}
<file_sep>/database/seeds/TemplateLogEmailSeed.php
<?php
use Illuminate\Database\Seeder;
class TemplateLogEmailSeed extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run(){
DB::table('template_logs')->truncate();
DB::table('template_logs')->insert([
[
'action_id' => '1',
'type'=>'1',
'tags'=>'#user_name#,#click_here#',
'message'=>'Dear #user_name# ,<br /><br />
Thank your for registering with shareAir. To verify your account, please click on the following link.
<br /><br />#click_here# to verify your email.
<br /><br />
Regards,<br />
ShareAir Team',
'created_at' => date('Y-m-d h:i:s'),
],[
'action_id' => '1',
'type'=>'1',
'tags'=>'#user_name#,#click_here#',
'message'=>"Dear #user_name# ,<br /><br />
A password reset was requested for your account. Please click on the link below to reset your password. If you didn't make this request, ignore this email.
<br /><br />#click_here# to reset you password.<br /><br />
",
'created_at' => date('Y-m-d h:i:s'),
],[
'action_id' => '1',
'type'=>'1',
'tags'=>'#user_name#,#click_here#',
'message'=>"Dear #user_name# ,<br /><br />
#buyer_name# has requested to book #property_name# from #from_date# to #end_date#. <br /> #click_here# to accept/reject this request.
<br /><br />
Regards,<br />
ShareAir Team" ,
'created_at' => date('Y-m-d h:i:s'),
],[
'action_id' => '1',
'type'=>'1',
'tags'=>'#user_name#,#click_here#',
'message'=>"Dear #user_name# ,<br /><br />
#messages#
Regards,<br />
ShareAir Team",
'created_at' => date('Y-m-d h:i:s'),
],[
'action_id' => '1',
'type'=>'1',
'tags'=>'#user_name#',
'message'=>"Dear #user_name# ,<br /><br />
Your property '#property_name#' has been booked by #buyer_name# from #from_date# to #end_date#.
<br /><br />
Regards,<br />
ShareAir Team" ,
'created_at' => date('Y-m-d h:i:s'),
],[
'action_id' => '1',
'type'=>'1',
'tags'=>'#user_name#',
'message'=>"Dear #user_name# ,<br /><br />
Your request for the property '#property_name#' has been confirmed/booked from #from_date# to #end_date#.
<br /><br />
Regards,<br />
ShareAir Team",
'created_at' => date('Y-m-d h:i:s'),
],[
'action_id' => '1',
'type'=>'1',
'tags'=>'#user_name#',
'message'=>"Dear #user_name# ,<br /><br />
You have a pending request for property '#property_name#'. Please #click_here# to approve the booking.
<br /><br />
Regards,<br />
ShareAir Team",
'created_at' => date('Y-m-d h:i:s'),
],[
'action_id' => '1',
'type'=>'1',
'tags'=>'#user_name#',
'message'=>"Dear #user_name# ,<br /><br />
It's been 48 hr, but still #buyer_name# has not booked the property '#property_name#'.<br />
If you want to cancel the booking. Please #click_here#.<br /><br />
Regards,<br />
ShareAir Team",
'created_at' => date('Y-m-d h:i:s'),
],
]);
}
}
<file_sep>/database/migrations/2017_09_25_080314_create_property_availaibility_dates_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreatePropertyAvailaibilityDatesTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::disableForeignKeyConstraints();
if (!Schema::hasTable('property_availaibility_dates')) {
Schema::create('property_availaibility_dates', function(Blueprint $table)
{
$table->unsignedBigInteger('id', true);
$table->unsignedInteger('property_availaibility_id');
$table->foreign('property_availaibility_id')->references('id')->on('property_availaibility');
$table->date('date');
});
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('property_availaibility_dates');
}
}
<file_sep>/database/migrations/2017_09_21_045203_drop_property_table_column.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class DropPropertyTableColumn extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('properties', function (Blueprint $table) {
$table->dropColumn('property_type_section_field_id');
$table->dropColumn('property_type_section_field_value');
$table->dropColumn('is_option');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('properties', function (Blueprint $table) {
$table->integer('property_type_section_field_id');
$table->string('property_type_section_field_value');
$table->boolean('is_option');
});
}
}
<file_sep>/database/seeds/InputFieldTypeTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class InputFieldTypeTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('input_field_types')->truncate();
DB::table('input_field_types')->insert([
['field_name' => \Config::get('constants.INPUT_TYPE_FIELD.1')],
['field_name' => \Config::get('constants.INPUT_TYPE_FIELD.2')],
['field_name' => \Config::get('constants.INPUT_TYPE_FIELD.3')],
['field_name' => \Config::get('constants.INPUT_TYPE_FIELD.4')],
['field_name' => \Config::get('constants.INPUT_TYPE_FIELD.5')],
['field_name' => \Config::get('constants.INPUT_TYPE_FIELD.6')],
['field_name' => \Config::get('constants.INPUT_TYPE_FIELD.7')],
['field_name' => \Config::get('constants.INPUT_TYPE_FIELD.8')],
['field_name' => \Config::get('constants.INPUT_TYPE_FIELD.9')],
['field_name' => \Config::get('constants.INPUT_TYPE_FIELD.10')],
['field_name' => \Config::get('constants.INPUT_TYPE_FIELD.11')],
['field_name' => \Config::get('constants.INPUT_TYPE_FIELD.12')],
['field_name' => \Config::get('constants.INPUT_TYPE_FIELD.13')],
]);
}
}
<file_sep>/database/seeds/DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$this->call(InputFieldTypeTableSeeder::class);
$this->call(ValidationTableSeeder::class);
$this->call(AdminSeeder::class);
$this->call(SellerSeeder::class);
$this->call(CancellationPolicy::class);
$this->call(TemplateLogEmailSeed::class);
}
}
<file_sep>/app/BookingDates.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BookingDates extends Model
{
protected $table = 'booking_dates';
protected $fillable = ['booking_id', 'date'];
}
<file_sep>/app/User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'first_name', 'last_name', 'dob', 'email', 'password', 'mobile_number', 'registration_token', 'role', 'is_verified', 'about_me', 'image'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function role(){
return $this->role;
}
public function userReviews(){
return $this->HasMany('App\PropertyReviews','rating_to_user','id');//->select(array('rating_to_user','rating', 'reason_for_rating', 'comments'));
}
public function getReminderEmail(){
return $this->email;
}
public function getRememberToken(){
return $this->remember_token;
}
public function setRememberToken($value){
$this->remember_token = $value;
}
public function getRememberTokenName(){
return 'remember_token';
}
}
<file_sep>/app/PropertyTypeSectionFieldOption.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class PropertyTypeSectionFieldOption extends Model
{
//
use SoftDeletes;
protected $dates = ['deleted_at'];
public function propertytypesectionfield(){
return $this->belongsTo('App\PropertyTypeSectionField');
}
public function getDisplayValues( $ids ){
return $this
->whereIn('id',$ids)
->pluck('display_value','id')
->toArray();
}
}
<file_sep>/app/Http/Controllers/Admin/PropertyTypeController.php
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\PropertyType;
use App\PropertyTypeSection;
use App\InputFieldType;
use App\Validation;
use App\User;
use App\PropertyTypeSectionField;
use App\PropertyTypeSectionFieldOption;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
class PropertyTypeController extends Controller
{
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create(Request $request){
return view('admin/property_type.create');
//return view('Propertytype.create');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(){
$PropertyTypes = PropertyType::orderBy('id', 'desc')->Paginate(10);
return view('admin/property_type.index', compact('PropertyTypes'));
//return view('Propertytype.index', compact('PropertyTypes'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request) {
$rules = [
'property_type_field_name' => 'required',
'property_type_section_name.*' => 'required|not_contains',
'property_type_section_name' => 'custom_distinct',
];
$customMessages = [
'property_type_field_name.required' => 'The Property Field is required',
'property_type_section_name.*required' => 'The Section Field is Required',
'property_type_section_name.*not_contains' => 'Sorry the Field name is already in Use',
'property_type_section_name.*distinct' => 'Please Donot Use duplicate section names',
'property_type_section_name.custom_distinct' => 'Please Donot Use duplicate section names',
];
$this->validate($request, $rules, $customMessages);
$PropertyType = new PropertyType;
$PropertyType->name = $request->property_type_field_name;
if($PropertyType->name) {
$PropertyType->save();
$property_type_id = $PropertyType->id;
$PropertyTypeSection = new PropertyTypeSection;
$PropertyTypeSection->name = "Basic Information";
$PropertyTypeSection->property_type_id = $PropertyType->id;
$PropertyTypeSection->order_id = 1;
$PropertyTypeSection->save();
$property_section_field_constants = array(
0=>array(
"field_name" => "Name",
"field_identifier"=>"basic_name",
"input_field_type_id"=> Config::get('constants.ADMIN_DEFAULT_PROPERTY_FEILDS_TYPE_ID.1'),
"validation_string" => "required",
),
1=>array(
"field_name" => "Location",
"field_identifier"=>"basic_location",
"input_field_type_id"=> Config::get('constants.ADMIN_DEFAULT_PROPERTY_FEILDS_TYPE_ID.2'),
"validation_string" => "required",
),
2=>array(
"field_name" => "Feature Image",
"field_identifier"=>"basic_feature_image",
"input_field_type_id"=> Config::get('constants.ADMIN_DEFAULT_PROPERTY_FEILDS_TYPE_ID.3'),
"validation_string" => "",
),
3=>array(
"field_name" => "Price",
"field_identifier"=>"basic_price",
"input_field_type_id"=> Config::get('constants.ADMIN_DEFAULT_PROPERTY_FEILDS_TYPE_ID.4'),
"validation_string" => "required",
),
4=>array(
"field_name" => "Description",
"field_identifier"=>"basic_description",
"input_field_type_id"=> Config::get('constants.ADMIN_DEFAULT_PROPERTY_FEILDS_TYPE_ID.5'),
"validation_string" => "required",
)
);
$property_section_field_constants_counter = 1;
foreach($property_section_field_constants as $field){
$validationString = '';
if($field["field_identifier"] == 'basic_feature_image' && empty($field["validation_string"])){
$validationString = 'required,upload_count:5';
}else if($field["field_identifier"] == 'basic_feature_image' && !empty($field["validation_string"])){
$validationString = $field["validation_string"].'required,upload_count:5';
}else{
$validationString = $field["validation_string"];
}
$PropertyTypeSectionField = new PropertyTypeSectionField;
$PropertyTypeSectionField->property_type_section_id = $PropertyTypeSection->id;
$PropertyTypeSectionField->name = $field["field_name"];
$PropertyTypeSectionField->input_field_type_id = $field["input_field_type_id"];
$PropertyTypeSectionField->field_identifier = $field["field_identifier"];
$PropertyTypeSectionField->validations = $validationString;
$PropertyTypeSectionField->order_id = $property_section_field_constants_counter;
$PropertyTypeSectionField->save();
$property_section_field_constants_counter++;
}
$property_type_section_counter =1;
foreach($request->property_type_section_name as $value) {
$PropertyTypeSection = new PropertyTypeSection;
$PropertyTypeSection->name = $value;
$PropertyTypeSection->property_type_id = $PropertyType->id;
$PropertyTypeSection->order_id = $property_type_section_counter;
if($PropertyTypeSection->name){
$PropertyTypeSection->save();
}
$property_type_section_counter++;
}
}
return redirect()->route('propertytype.edit', $property_type_id)->with('status', 'Property Type Saved successfully!');
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id) {
/*$PropertyType = new PropertyType;
$PropertyTypeSection = new PropertyTypeSection;*/
//Get all the information associated with given ID
$PropertyType = PropertyType::find($id);
$PropertyTypeSections = PropertyTypeSection::where('property_type_id', $id)->orderBy('order_id', 'asc')->get();
$InputFieldTypes = InputFieldType::all();
$Validations = Validation::all();
//And return to edit.blade.php view file.
return view('admin/property_type.edit', compact('PropertyType', 'PropertyTypeSections', 'InputFieldTypes', 'Validations'));
//return view('Propertytype.edit', compact('PropertyType', 'PropertyTypeSections', 'InputFieldTypes', 'Validations'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id) {
$rules = [
'property_type_field_name' => 'required',
'property_type_section_name.*' => 'required|distinct',
];
$customMessages = [
'property_type_field_name.required' => 'The Property Field is required',
'property_type_section_name.*required' => 'The Section Field is Required',
'property_type_section_name.*distinct' => 'Please Donot Use duplicate section names',
];
$customMessages = array_unique($customMessages);
$this->validate($request, $rules, $customMessages);
$arr_PropertyTypeSections = PropertyTypeSection::select('id')->where('property_type_id', $request->property_type_id)->get()->toArray();
foreach($arr_PropertyTypeSections as $value){
$arr_PropertyTypeSections_ids[] = $value["id"];
}
$PropertyTypeSections_diff = array_diff($arr_PropertyTypeSections_ids ,$request->property_type_section_id);
if(sizeof($PropertyTypeSections_diff) >0 ){
PropertyTypeSection::whereIn('id', $PropertyTypeSections_diff)->delete();
}
if($request->property_type_id && $request->property_type_field_name){
//store
$PropertyType = PropertyType::find($request->property_type_id);
$PropertyType->name = $request->property_type_field_name;
$PropertyType->save();
print_r($request->property_type_id);
print_r($request->property_type_section_name);
$custom_query_part1 = "";
$custom_query_part2 = "";
$counter = 0;
$PropertyTypeSectionCounter = 1;
foreach($request->property_type_section_name as $value) {
// update information
if($request->property_type_section_id[$counter] && $value){
$section_id = $request->property_type_section_id[$counter];
$custom_query_part1 .= " WHEN id = $section_id THEN $PropertyTypeSectionCounter ";
$custom_query_part2 .= " WHEN id = $section_id THEN " . "'" .$value . "'";
$existingOptionid_arr[] = $request->property_type_section_id[$counter];
} else if(!$request->property_type_section_id[$counter] && $value) {
$PropertyTypeSection = new PropertyTypeSection;
$PropertyTypeSection->name = $value;
$PropertyTypeSection->order_id = $PropertyTypeSectionCounter;
$PropertyTypeSection->property_type_id = $request->property_type_id;
$PropertyTypeSection->save();
}
$counter++;
$PropertyTypeSectionCounter++;
}
$custom_query_part3 = implode(",", $existingOptionid_arr);
$main_query = "UPDATE property_type_sections
SET order_id = CASE
$custom_query_part1
ELSE order_id END,
name = CASE
$custom_query_part2
ELSE name
END
WHERE id IN ($custom_query_part3);";
DB::update($main_query);
if(!empty($id)) {
(new PropertyType())->where(['id' => $id])->update(['updated_at' => date('Y-m-d H:i:s')]);
}
}
return redirect()->back()->with('status', 'Property Type Updated successfully');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$PropertyType = PropertyType::find($id);
$PropertyType->delete();
//$deletedRows = PropertyTypeSection::where('property_type_id', $id)->delete();
//reture to index.blade.php with a success method.
//return redirect('/propertytype/')->with('status', 'Property Type Deleted successfully!');
return redirect()->back()->with('status', 'Property Type Deleted successfully!');
}
}<file_sep>/app/Http/Requests/Seller/PropertyReviewsRequest.php
<?php
namespace App\Http\Requests\Seller;
use Illuminate\Foundation\Http\FormRequest;
class PropertyReviewsRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'rating' => 'required',
'reason_for_rating' => 'required',
'comments' => 'required|max:150',
];
}
/*=====================================
Function to display Custom Messages
========================================*/
public function messages() {
return [
'rating.required' => 'Please Enter rating.',
'reason_for_rating.required' => 'Please select reason.',
'comments.required' => 'Please enter reviews.',
'comments.max' => 'Comment can not be more than 150 character long.',
];
}
}
<file_sep>/app/Http/Requests/Seller/EditProfile.php
<?php
namespace App\Http\Requests\Seller;
use Illuminate\Foundation\Http\FormRequest;
class EditProfile extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'first_name' => array( 'required', 'max:30' ),
//'last_name' => array( 'required','alpha_num', 'max:30' ),
'last_name' => array( 'required', 'max:30' ),
'mobile_number' => 'required|numeric',
'pic' => 'max:1024|mimes:jpeg,jpg,png',
];
}
public function messages() {
return [
'first_name.required' => 'First Name can not be left empty.',
'first_name.max' => 'Name can not exceed more than 30 character ',
'first_name.alpha_num' => 'Please enter only numbers and alphabets',
'last_name.required' => 'Last Name can not be left empty.',
'last_name.max' => 'Name can not exceed more than 30 character ',
'last_name.alpha_num' => 'Please enter only numbers and alphabets',
'pic.mimes' => 'Invalid file extension.',
'pic.max' => 'Image size can not be greater than 1 mb.'
];
}
}
<file_sep>/database/migrations/2018_01_05_064938_add_is_request_to_availability_dates.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddIsRequestToAvailabilityDates extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('property_availaibility_dates', function($table) {
$table->boolean('is_requested')->comment = "0->No Request For Date, 1->Request For Date";
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('property_availaibility_dates', function($table) {
$table->dropColumn('is_requested');
});
}
}
<file_sep>/app/Http/Requests/UserRegistration.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UserRegistration extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|email|max:255|unique:users',
'mobile_number' => 'required|numeric|min:1|unique:users',
'password' => '<PASSWORD>',
'password_confirmation' => '<PASSWORD>|same:password'
];
}
/*=====================================
Function to display Custom Messages
========================================*/
public function messages() {
return [
'first_name.required' => 'Please Enter First Name.',
'last_name.required' => 'Please Enter Last Name.',
'email.required' => 'Please Enter Your Email.',
'mobile_number.required' => 'Please Enter Your Mobile number.',
'password.required' => 'Please Enter Password.',
'password.min' => 'Password should be at least 12 characters long.',
'password_confirmation' => 'Please Enter Confirmed Password.',
'password_confirmation.same' => 'New password and confirm password do not match.Please enter both again.',
];
}
}
<file_sep>/database/seeds/ValidationTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class ValidationTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('validations')->truncate();
DB::table('validations')->insert([
['validation_text' => 'Required',
'validation' => 'required'
],
['validation_text' => 'Date',
'validation' => 'date'
],
['validation_text' => 'Numeric',
'validation' => 'numeric'
],
['validation_text' => 'Alpha Numeric',
'validation' => 'alpha_space_numeric'
],
['validation_text' => 'Alpha',
'validation' => 'alpha_spaces'
],
['validation_text' => 'Email',
'validation' => 'email'
],
['validation_text' => 'Url',
'validation' => 'url'
],
['validation_text' => 'File Count',
'validation' => 'upload_count'
]
]);
}
}
<file_sep>/app/Bookings.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Bookings extends Model {
protected $table = 'bookings';
protected $fillable = ['utc_time','through_approval','policy_id','is_approved','booking_id', 'property_id', 'user_id', 'total_amount', 'payment_status', 'property_owner_id'];
/*===============================================
Get Property Booking Dates Using Property id
Param 1 : Property Id
Join With : booking_dates
===================================================*/
public function getBookingDates( $propertyId ){
return $this
->join('booking_dates', 'bookings.booking_id','=','booking_dates.booking_id')
->where(array('bookings.property_id' => $propertyId))
->select('booking_dates.date')
->get()
->toArray();
}
/*===============================================
Get Property Booking Dates Using booking id
Param 1 : Property Id
Join With : booking_dates
===================================================*/
public function getBookingDatesByBookingID( $bookingId ){
return $this
->join('booking_dates', 'bookings.booking_id','=','booking_dates.booking_id')
->where(array('bookings.booking_id' => $bookingId))
->select('booking_dates.date')
->get()
->toArray();
}
/*===============================================
Get Property Booking policy Using booking id
Param 1 : booking Id
Join With : properties
===================================================*/
public function getPolicyRecord( $bookingId ){
return $this
->leftjoin('cancellation_policy', 'bookings.policy_id','=','cancellation_policy.id')
// ->join('booking_dates', 'bookings.booking_id','=','booking_dates.booking_id')
->where(array('bookings.booking_id' => $bookingId))
->select('bookings.property_owner_id','bookings.policy_id','cancellation_policy.id','cancellation_policy.duration','bookings.is_approved','bookings.property_id')
->first()
->toArray();
}
/*==============================
Get UpComing Properties
Param 1 : User Id
Join With : booking_dates
================================*/
public function getUpcomingProperties( $userId ){
$current_date = getServerUtcTime();
return $this
->join( 'booking_dates', 'bookings.booking_id', '=','booking_dates.booking_id' )
->where( array( 'bookings.user_id' =>$userId ,'bookings.is_approved' => 1,'bookings.payment_status' => 1) )
->Where('booking_dates.date','>=', $current_date)
->select( 'bookings.booking_id', 'bookings.property_id' )
->groupBy('bookings.booking_id');
}
/*==============================
Get Apporove Properties for user
Param 1 : User Id
Join With : booking_dates
================================*/
public function getApproveProperties( $useId ){
$current_date = getServerUtcTime();
return $this
->join( 'booking_dates', 'bookings.booking_id', '=','booking_dates.booking_id' )
->where( array( 'bookings.user_id' =>$useId ,'bookings.is_approved' => 1,'bookings.through_approval' => 1) )
->Where('booking_dates.date','>=', $current_date)
->select( 'bookings.booking_id', 'bookings.property_id' )
->groupBy('bookings.booking_id');
}
/*==============================
Get UpComing Properties
Param 1 : User Id
Join With : booking_dates
================================*/
public function getBookedUpcomingProperties( $useId ){
$current_date = getServerUtcTime();
return $this
->join( 'booking_dates', 'bookings.booking_id', '=','booking_dates.booking_id' )
->where( array( 'bookings.property_owner_id' =>$useId ,'bookings.is_approved' => 1,'bookings.payment_status' => 1 ) )
->Where('booking_dates.date','>=', $current_date)
->select( 'bookings.booking_id', 'bookings.property_id' )
->groupBy('bookings.booking_id');
}
/*==============================
Get Approve Properties
Param 1 : User Id
Join With : booking_dates
================================*/
public function getBookedApproveProperties( $useId,$bookingId = null){
$current_date = getServerUtcTime();
return $this
->join( 'booking_dates', 'bookings.booking_id', '=','booking_dates.booking_id' )
->where( array( 'bookings.property_owner_id' =>$useId ,
'bookings.is_approved' => 1,'bookings.through_approval' => 1 ) )
->where(function($q) use ($bookingId){
if(!empty($bookingId)) {
$q->where(['bookings.booking_id' => $bookingId]);
}
})
->Where('booking_dates.date','>=', $current_date)
->select( 'bookings.booking_id', 'bookings.property_id' )
->groupBy('bookings.booking_id');
}
/*==============================
Get Pending Properties
Param 1 : User Id
Join With : booking_dates
================================*/
public function getBookedPendingProperties( $userId ){
$current_date = getServerUtcTime();
return $this
->join( 'booking_dates', 'bookings.booking_id', '=','booking_dates.booking_id' )
->where( array( 'bookings.property_owner_id' =>$userId ,'bookings.is_approved' => 0,'bookings.through_approval' => 1 ) )
// ->Where('booking_dates.date','>=', $current_date)
->select( 'bookings.booking_id', 'bookings.property_id' )
->groupBy('bookings.booking_id');
}
/*==============================
Get Pending Properties
Param 1 : User Id
Join With : booking_dates
================================*/
public function getPendingProperties( $useId ){
$current_date = getServerUtcTime();
return $this
->join( 'booking_dates', 'bookings.booking_id', '=','booking_dates.booking_id' )
->where( array( 'bookings.user_id' =>$useId ,'bookings.is_approved' => 0,'bookings.through_approval' => 1 ) )
//->Where('booking_dates.date','>=', $current_date)
->select( 'bookings.booking_id', 'bookings.property_id' )
->groupBy('bookings.booking_id');
}
/*==============================
Get Rejected Booking
Param 1 : User Id
Join With : booking_dates
================================*/
public function getBookedRejectedProperties( $useId ){
return $this
->join( 'booking_dates', 'bookings.booking_id', '=','booking_dates.booking_id' )
->where( array( 'bookings.property_owner_id' =>$useId ,'bookings.is_approved' => 2,'bookings.through_approval' => 1 ) )
->select( 'bookings.booking_id', 'bookings.property_id' )
->groupBy('bookings.booking_id');
}
public function getRejectedProperties( $useId ){
return $this
->join( 'booking_dates', 'bookings.booking_id', '=','booking_dates.booking_id' )
->where( array( 'bookings.user_id' =>$useId ,'bookings.is_approved' => 2,'bookings.through_approval' => 1 ) )
->select( 'bookings.booking_id', 'bookings.property_id' )
->groupBy('bookings.booking_id');
}
/*==============================
Get UpComing Properties
Param 1 : "User Id
Join With : booking_dates
================================*/
public function getPastBookingProperties( $useId ){
$current_date = getServerUtcTime();
return $this
->join( 'booking_dates', 'bookings.booking_id', '=','booking_dates.booking_id' )
->where( array( 'bookings.user_id' =>$useId,'bookings.payment_status' => 1 ) )
->Where('booking_dates.date','<', $current_date)
->select( 'bookings.booking_id', 'bookings.property_id' )
->groupBy('bookings.booking_id');
}
/*==============================
Get UpComing Properties
Param 1 : "User Id
Join With : booking_dates
================================*/
public function getBookedPastBookingProperties( $useId ){
$current_date = getServerUtcTime();
return $this
->join( 'booking_dates', 'bookings.booking_id', '=','booking_dates.booking_id' )
->where( array( 'bookings.property_owner_id' =>$useId,'bookings.payment_status' => 1 ) )
->Where('booking_dates.date','<', $current_date)
->select( 'bookings.booking_id', 'bookings.property_id' )
->groupBy('bookings.booking_id');
}
/*public function getUpcomingProperties( $useId ){
$current_date = getServerUtcTime();
return $this
->join( 'booking_dates', 'bookings.booking_id', '=','booking_dates.booking_id' )
->where( array( 'bookings.user_id' =>$useId ) )
->Where('booking_dates.date','>=', $current_date)
->select( 'bookings.booking_id', 'bookings.property_id', 'booking_dates.date' )
->groupBy('bookings.booking_id');
}*/
}
<file_sep>/app/PropertyFieldValue.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PropertyFieldValue extends Model
{
protected $table = 'properties_field_values';
protected $fillable = [
'property_id','property_type_section_field_id','property_type_section_field_value','is_option', 'updated_at'
];
/*=====================================================================
Get Property Details Property id
Param 1 : Property Id
Join With : property_type_section_fields, property_type_sections
======================================================================*/
public function getPropertyDetail( $propertyId ){
return $this
->join('property_type_section_fields', 'properties_field_values.property_type_section_field_id' ,'=','property_type_section_fields.id')
->join('property_type_sections', 'property_type_section_fields.property_type_section_id','=','property_type_sections.id')
->join('properties', 'properties.id', '=', 'properties_field_values.property_id')
->where(array('properties_field_values.property_id' => $propertyId,'property_type_sections.deleted_at' => null,'property_type_section_fields.deleted_at' => null))
->select('properties.seller_id','properties_field_values.is_option','properties_field_values.property_type_section_field_value',
'property_type_section_fields.name as field_name','property_type_sections.name as section',
'property_type_sections.id','property_type_section_fields.order_id', 'property_type_sections.order_id as orderId',
'property_type_section_fields.field_identifier', 'property_type_section_fields.input_field_type_id', 'properties.is_approved_checked'
)
->orderBy( 'orderId', 'ASC')
->orderBy('property_type_section_fields.order_id',"ASC")
->orderBy('orderId',"ASC")
->get()
->toArray();
}
}
<file_sep>/app/Http/Controllers/Admin/AdminProfile.php
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use App\Http\Requests\Admin\ChangePassword;
use Hash;
class AdminProfile extends Controller
{
public function changePasswordView(){
return view('admin.change_password');
}
/*===============================
Function for Change Password
=================================*/
public function ChangeAdminPassword( ChangePassword $request ){
try{
$user = Auth::user();
if(Hash::check($request->old_password, Auth::user()->password)){
if(Hash::check($request->password, Auth::user()->password)){
return redirect('/change-password')->with('error', 'Sorry, Please choose different password.');
} else {
$data['password'] = <PASSWORD>( $request->password );
if( $user->update( $data ) ) {
return redirect('/change-password')->with('message', 'Password Updated successfully.');
} else {
return redirect('/change-password')->with('error', 'Sorry, Password can not be Changed.');
}
}
} else {
return redirect('/change-password')->with('error', 'Old password is not correct.');
}
}catch(\Expection $e){
echo $e->getMessage();
die();
}
}
}
<file_sep>/database/seeds/CancellationPolicy.php
<?php
use Illuminate\Database\Seeder;
class CancellationPolicy extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('cancellation_policy')->delete();
DB::table('cancellation_policy')->insert(array(
array('policy_name'=>'Flexible','duration'=>'1d','created_at' => date('Y-m-d H:i:s'),'updated_at' => date('Y-m-d H:i:s')),
array('policy_name'=>'Moderate','duration'=>'5d','created_at' => date('Y-m-d H:i:s'),'updated_at' => date('Y-m-d H:i:s')),
array('policy_name'=>'Strict','duration'=>'2w','created_at' => date('Y-m-d H:i:s'),'updated_at' => date('Y-m-d H:i:s')),
array('policy_name'=>'Very Strict','duration'=>'1m','created_at' => date('Y-m-d H:i:s'),'updated_at' => date('Y-m-d H:i:s')),
));
}
}
<file_sep>/app/Http/Controllers/Seller/SellerProfile.php
<?php
namespace App\Http\Controllers\Seller;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\Seller\ChangePassword;
use App\Http\Requests\Seller\EditProfile;
use Illuminate\Support\Facades\Input;
use Hash;
use Auth;
class SellerProfile extends Controller
{
/*====================
Load Profile View
======================*/
public function myProfile(){
$active = 'myProfile';
return view('seller.my_profile', compact( 'active' ));
}
/*===============================
Function For Editing Profile
==================================*/
public function editProfile( EditProfile $request ) {
$user = Auth::user();
$data = $request->all();
$data['first_name'] = $request->input( 'first_name');
$data['last_name'] = $request->input( 'last_name') ;
$data['mobile_number'] = $request->input( 'mobile_number') ;
$data['about_me'] = $request->input( 'about_me') ;
$img = Input::file('pic');
if( $img != '' ) {
$image = $img->getClientOriginalName();
$path = public_path(\Config::get('constants.IMAGE_FOLDER_NAME').DIRECTORY_SEPARATOR);
$img->move($path,$image);
$data['image'] = $image;
}
if( $user->update( $data ) ) {
return redirect('/seller/my-profile')->with('message', 'Profile Updated successfully.');
}
}
/*=============================
Load Change Password View
===============================*/
public function changePasswordView() {
$active = 'changePassword';
return view('seller.change_password', compact( 'active' ));
}
/*===============================
Function for Change Password
=================================*/
public function changeSellerPassword( ChangePassword $request ){
$user = Auth::user();
if(Hash::check($request->old_password, Auth::user()->password)){
if(Hash::check($request->password, Auth::user()->password)){
return redirect('/seller/change-password-view')->with('error', 'Sorry, Please choose different password.');
} else {
$data['password'] = <PASSWORD>( $request->password );
if( $user->update( $data ) ) {
return redirect('/seller/change-password-view')->with('message', 'Password Updated successfully.');
} else {
return redirect('/seller/change-password-view')->with('error', 'Sorry, Password can not be Changed.');
}
}
} else {
return redirect('/seller/change-password-view')->with('error', 'Old password is not correct.');
}
}
}
<file_sep>/app/Http/Requests/Seller/PropertiesFieldValues.php
<?php
namespace App\Http\Requests\Seller;
use App\PropertyTypeSection;
use App\Validation;
use Illuminate\Support\MessageBag;
use \Validator;
use Illuminate\Foundation\Http\FormRequest;
class PropertiesFieldValues extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
private $attribute = [];
private $messages = [];
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$requestUrl = \Request::all();
$id = $requestUrl['property_types_id'];
$propertyTypesSections = (new PropertyTypeSection())
->rightjoin('property_type_section_fields', 'property_type_section_fields.property_type_section_id','=', 'property_type_sections.id')
->where('property_type_sections.property_type_id' , $id)
->select('property_type_section_fields.id as property_type_section_fields_id','property_type_section_fields.name', 'validations','input_field_type_id')
->get()->toArray();
$validations = [];
foreach($propertyTypesSections as $index => $propertyTypesSection) {
if(!empty($requestUrl['property_id']) && $propertyTypesSection['input_field_type_id']) {
$explodeValidations = explode(',', $propertyTypesSection['validations']);
$validations[$propertyTypesSection['property_type_section_fields_id'] . '_' . str_replace(' ', '', $propertyTypesSection['name'])] = ($propertyTypesSection['input_field_type_id'] == \Config::get('constants.ADMIN_DEFAULT_PROPERTY_FEILDS_TYPE_ID.3')) ? '' : str_replace(',', '|', ($propertyTypesSection['validations'] == 'numeric' ? 'nullable,numeric': $propertyTypesSection['validations']));
if (!empty($propertyTypesSection['validations'])) {
foreach ($explodeValidations as $explodeValidation) {
$this->attribute[$propertyTypesSection['property_type_section_fields_id'] . '_' . $propertyTypesSection['name']] = $propertyTypesSection['name'];
}
}
}else{
$explodeValidations = explode(',', $propertyTypesSection['validations']);
$validations[$propertyTypesSection['property_type_section_fields_id'] . '_' . str_replace(' ', '', $propertyTypesSection['name'])] = str_replace(',', '|', ($propertyTypesSection['validations'] == 'numeric' ? 'nullable,numeric': $propertyTypesSection['validations']));
if (!empty($propertyTypesSection['validations'])) {
foreach ($explodeValidations as $explodeValidation) {
$this->attribute[$propertyTypesSection['property_type_section_fields_id'] . '_' . $propertyTypesSection['name']] = $propertyTypesSection['name'];
}
}
}
}
//pr($this->attribute);
//pr($validations,1);
return $validations;
}
public function messages() {
return $this->messages;
}
public function attributes(){
return $this->attribute;
}
}
<file_sep>/app/PropertyType.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class PropertyType extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $table = 'property_types';
protected $fillable = [
'name', 'deleted_at'
];
public function getPropertyTypeInformation(){
return $this
->join('property_type_sections','property_type_sections.property_type_id','=','property_types.id')
->join('property_type_section_fields','property_type_section_fields.property_type_section_id','=','property_type_sections.id')
->join('property_type_section_field_options','property_type_section_field_options.property_type_section_field_id','=','property_type_section_fields.id')
->where(['property_type_sections.deleted_at' => NULL,'property_types.deleted_at' => NULL])
->select('property_type_sections.name','property_type_sections.order_id as property_type_section_order_id','property_types.name as property_type_name','property_type_section_fields.name','property_type_section_fields.input_field_type_id','property_type_section_fields.validations','property_type_section_fields.order_id','property_type_section_field_options.display_value','property_type_section_field_options.order_id as property_type_section_field_options_order_id')
->get();
}
public function propertytypesection()
{
return $this->hasMany('App\PropertyTypeSection', 'property_type_id', 'id');
}
/*
protected static function boot() {
parent::boot();
static::deleting(function($propertytypes) {
$propertytypes->propertytypesection()->delete();
});
}
*/
}
<file_sep>/config/constants.php
<?php
/**
* Created by PhpStorm.
* User: Dell
* Date: 11/4/2016
* Time: 1:23 PM
*/
return [
'INPUT_TYPE_FIELD' => [
'1' => 'Input Text',
'2' => 'Input Radio',
'3' => 'Input Checkbox',
'4' => 'Input Date',
'5' => 'Input Datetime Local',
'6' => 'Input email',
'7' => 'Input Number',
'8' => 'Input Time',
'9' => 'Input Url',
'10' => 'Input Password',
'11' => 'Select Dropdown',
'12' => 'Input File',
'13' => 'Text Area',
],
'INPUT_TYPE_FIELD_IDENTIFIER' => [
'1' => 'basic_name',
'2' => 'basic_location',
'3' => 'basic_feature_image',
'4' => 'basic_price',
'5' => 'basic_description'
],
'IMAGE_FOLDER_NAME' => 'images',
'IMAGE_ASSET_FOLDER_NAME' => 'img',
'TIMEZONE_API_KEY' => '<KEY>',
/*when admin add new property default feild type ids*/
'ADMIN_DEFAULT_PROPERTY_FEILDS_TYPE_ID' =>[
'1' => '1',
'2' => '1',
'3' => '12',
'4' => '7',
'5' => '13',
],
'MAX_DAYS_NOTIES' => [
'90' => '3 months',
'180' => '6 months',
'270' => '9 months',
'365' => '1 year',
'0' => 'Dates unavailable by default',
],
'PROPERTY_REVIEW_REASON' => [
'1' => 'Very Bad',
'2' => 'Bad',
'3' => 'Good',
'4' => 'Very Good',
'5' => 'Excellent',
],
'CANCELLATION_POLICY_DURATION_IN_DAYS' => [
'1d' => '1',
'5d' => '5',
'2w' => '14',
'1m' => '30',
'owner' => '1'
],
'CANCELLATION_POLICY_DURATION_IN_HOURS' => [
'1d' => '24',
'5d' => '120',
'2w' => '336',
'1m' => '720',
'owner' => '24'
],
'CANCELLATION_POLICY_DURATION_IN_MINUTES' => [
'1d' => '1440',
'5d' => '7200',
'2w' => '20160',
'1m' => '43800',
'owner' => '1440'
],
'START_TIME' => '12:00:00',
'OFFSET_LIMIT_PROPERTY_SEARCH' => '4',
'SEARCH_DISTANCE' => '50',
'ASIA_TIMEZONE' => 'Asia/Calcutta',
];
<file_sep>/app/PropertyAvailaibility.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PropertyAvailaibility extends Model
{
protected $table = 'property_availaibility';
/*=====================================
Get Property Booked dates lists
Param 1 : Property Id
Param 2 : Start Date
Param 3 : End Date
======================================*/
public function getBookedDates( $propertyId ){
$current_date = getServerUtcTime();
return $this
->join('property_availaibility_dates','property_availaibility.id','=','property_availaibility_dates.property_availaibility_id')
->whereIn('property_availaibility.property_id', $propertyId)
->where(array('property_availaibility_dates.is_booked'=> 1))
->Where('property_availaibility_dates.date','>=', $current_date)
->select(
\DB::raw('group_concat(property_availaibility_dates.date) as date'),
'property_availaibility.property_id')
->groupBy('property_availaibility.property_id')
->pluck('date', 'property_id')
->toArray();
}
/*==========================================================================
Get Property Available Date Based On Property id and (Start and EndDate)
Param 1 : Property Id
Param 2 : Start Date
Param 3 : End Date
============================================================================*/
public function getPropertyAvailabilityBetweenDates( $propertyId, $startDate, $endDate ){
return $this
->join('property_availaibility_dates','property_availaibility.id','=','property_availaibility_dates.property_availaibility_id')
->where(array('property_availaibility.property_id' => $propertyId))
->where(array('property_availaibility_dates.is_booked'=> 0))
->whereDate('property_availaibility_dates.date', '>=',$startDate)
->whereDate('property_availaibility_dates.date', '<=', $endDate)
->pluck('property_availaibility_dates.id')
->toArray();
}
/*==========================================================================
Get Property Available Date Based On Property id and (Start and EndDate)
Param 1 : Property Id
Param 2 : Start Date
Param 3 : End Date
============================================================================*/
public function getIsRequestedDates( $propertyId, $startDate, $endDate ){
return $this
->join('property_availaibility_dates','property_availaibility.id','=','property_availaibility_dates.property_availaibility_id')
->where(array('property_availaibility.property_id' => $propertyId,'property_availaibility_dates.is_requested'=> 0))
->whereDate('property_availaibility_dates.date', '>=',$startDate)
->whereDate('property_availaibility_dates.date', '<=', $endDate)
->pluck('property_availaibility_dates.id')
->toArray();
}
/*================================================================================
Get Property Available Date Based On Property id and (Start and EndDate) for approval
Param 1 : Property Id
Param 2 : Start Date
Param 3 : End Date
============================================================================*/
public function getPropertyAvailabilityBetweenDatesFree( $propertyId, $startDate, $endDate ){
return $this
->join('property_availaibility_dates','property_availaibility.id','=','property_availaibility_dates.property_availaibility_id')
->where(array('property_availaibility.property_id' => $propertyId))
->where(array('property_availaibility_dates.is_booked'=> 0))
->where('property_availaibility_dates.date', '>=',$startDate)
->where('property_availaibility_dates.date', '<=', $endDate)
->pluck('property_availaibility_dates.id')
->toArray();
}
/*==========================================================================
Get Property Available Date Based On Property id and (Start and EndDate)
Param 1 : Property Id
Param 2 : Start Date
Param 3 : End Date
============================================================================*/
public function cancelGetPropertyAvailabilityBetweenDates1( $propertyId, $startDate, $endDate ){
return $this
->join('property_availaibility_dates','property_availaibility.id','=','property_availaibility_dates.property_availaibility_id')
->where(array('property_availaibility.property_id' => $propertyId))
->where(array('property_availaibility_dates.is_requested'=> 1))
->where('property_availaibility_dates.date', '>=',$startDate)
->where('property_availaibility_dates.date', '<=', $endDate)
->pluck('property_availaibility_dates.id')
->toArray();
}
public function cancelGetPropertyAvailabilityBetweenDates( $propertyId, $startDate, $endDate ){
return $this
->join('property_availaibility_dates','property_availaibility.id','=','property_availaibility_dates.property_availaibility_id')
->where(array('property_availaibility.property_id' => $propertyId))
->where(array('property_availaibility_dates.is_booked'=> 1))
->where('property_availaibility_dates.date', '>=',$startDate)
->where('property_availaibility_dates.date', '<=', $endDate)
->pluck('property_availaibility_dates.id')
->toArray();
}
/*====================================================
Get Property Available Dates Based On Property id
Param 1 : Property Id
=====================================================*/
public function getPropertyAvailabilityDates( $propertyId ){
$date = getServerUtcTime();
return $this
->join('property_availaibility_dates', 'property_availaibility.id','=','property_availaibility_dates.property_availaibility_id')
->where(array('property_availaibility.property_id' => $propertyId, 'property_availaibility_dates.is_requested' => 0))
->where('property_availaibility_dates.date','>=' ,$date)
->pluck('property_availaibility_dates.date')
->toArray();
}
/*====================================================
Get Property Available Dates Based On Property id
Param 1 : Property Id
=====================================================*/
public function getPropertySelectedDatesAndDays( $propertyId ){
return $this
->join('property_availaibility_dates', 'property_availaibility.id','=','property_availaibility_dates.property_availaibility_id')
->where(array('property_availaibility.property_id' => $propertyId))
->select('property_availaibility_dates.date','property_availaibility.avalaibility_option','is_booked','is_requested','property_availaibility.is_blocked')
->orderBy('property_availaibility_dates.date','ASC')
->get()
->toArray();
}
public function getPropertySelectedFilterWithDate( $propertyId,$date ){
return $this
->join('property_availaibility_dates', 'property_availaibility.id','=','property_availaibility_dates.property_availaibility_id')
->where(['property_availaibility.property_id' => $propertyId])
->whereDate('property_availaibility_dates.date','=',$date)
->select('property_availaibility_dates.is_booked','property_availaibility_dates.is_requested','property_availaibility_dates.date','property_availaibility.avalaibility_option','property_availaibility.is_blocked')
->first();
}
/*========================
Cancel booking Date
Param 1 : $propertyId
Param 2 : $startDate
Param 3 : $endDate
==========================*/
public function getPropertyBookingDatesWithDates( $propertyId, $startDate, $endDate ){
return $this
->join('property_availaibility_dates','property_availaibility.id','=','property_availaibility_dates.property_availaibility_id')
->where(array('property_availaibility.property_id'=>$propertyId))
->where(array('property_availaibility_dates.is_booked'=> 1))
->whereBetween('property_availaibility_dates.date', [$startDate,$endDate])
->pluck('property_availaibility_dates.id')
->toArray();
}
/*====================================================
Get Property Available Dates Based On Property id
Param 1 : $propertyId
Param 2 : $startDate
Param 3 : $endDate
=====================================================*/
/*public function checkIfBookedOnDate( $propertyId, $startDate, $endDate ){
return $this
->join('property_availaibility_dates','property_availaibility.id','=','property_availaibility_dates.property_availaibility_id')
->where(array('property_availaibility.property_id' => $propertyId))
->whereBetween('property_availaibility_dates.date', [$startDate, $endDate])
->Where(array('property_availaibility_dates.is_booked'=>0))
->pluck('date')
->toArray();
}*/
/*====================================================
Get Property Available Dates Based On Property id
Param 1 : $propertyId
Param 2 : $startDate
Param 3 : $endDate
=====================================================*/
public function checkIfBookedOnDate( $propertyId, $startDate, $endDate ){
return $this
->join('property_availaibility_dates','property_availaibility.id','=','property_availaibility_dates.property_availaibility_id')
->where(array('property_availaibility.property_id' => $propertyId))
->whereDate('property_availaibility_dates.date', '>=',$startDate)
->whereDate('property_availaibility_dates.date', '<=', $endDate)
->Where(array('property_availaibility_dates.is_booked'=>0))
->pluck('date')
->toArray();
}
}
<file_sep>/app/InputFieldType.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class InputFieldType extends Model
{
//
}
<file_sep>/database/migrations/2017_08_31_143120_create_property_type_section_fields_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreatePropertyTypeSectionFieldsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if (!Schema::hasTable('property_type_section_fields')) {
Schema::create('property_type_section_fields', function(Blueprint $table)
{
$table->integer('id', true);
$table->integer('property_type_section_id')->nullable();
$table->string('name', 100)->nullable();
$table->smallInteger('input_field_type_id')->nullable();
$table->string('field_identifier', 200)->nullable();
$table->text('validations', 65535)->nullable();
$table->smallInteger('allowed_instances')->nullable()->comment('0 for any number and >0 for putting limit');
$table->smallInteger('order_id')->nullable();
$table->boolean('is_country')->nullable();
$table->boolean('is_state')->nullable();
$table->timestamps();
$table->softDeletes();
});
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('property_type_section_fields');
}
}
<file_sep>/database/migrations/2017_12_07_101843_add_url_message_to_be_send.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddUrlMessageToBeSend extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('message_to_be_send', function (Blueprint $table) {
$table->string('approved_token')->after('email');
$table->string('url')->after('email');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('message_to_be_send', function (Blueprint $table) {
$table->dropColumn('approved_token');
$table->dropColumn('url');
});
}
}
<file_sep>/app/Http/Controllers/CronjobController.php
<?php
namespace App\Http\Controllers;
use App\Bookings;
use App\PropertyFieldValue;
use App\TemplateLog;
use Illuminate\Foundation\Auth\User;
use Illuminate\Http\Request;
use App\MessageToBeSend;
use DB;
use Auth;
use Session;
use Validator;
use Config;
use Mail;
class CronjobController extends Controller
{
/*================================================
Cronjob email fuction
==================================================*/
public function index(){
$mailList = MessageToBeSend::where( array( 'is_send' => 1,'status' => 0) )->limit(10)->get()->toArray();
foreach ($mailList as $key => $message) {
$email = $message['email'];
$messageBody = $message['body'];
$subject = $message['subject'];
Mail::send('email.email', array('body' => $messageBody), function($email) use ($message){ $email->to($message['email'])->subject($message['subject']); });
if(MessageToBeSend::where('id', $message['id'])->update(array('status' => 1))){
echo "Done";
}
}
}
public function maiToNotAprovedProperty(){
$utcCurrentTime = gmdate(date('Y-m-d H:i:s'));
//echo $utcCurrentTime;
//$timestamp = strtotime($utcCurrentTime) - 20*60;
//$timestamp2 = strtotime($utcCurrentTime) - 10*60;
$timestamp = strtotime($utcCurrentTime) - 300*120;
$timestamp2 = strtotime($utcCurrentTime) - 270*120;
$lastTime1 = date('Y-m-d H:i:s', $timestamp);
$lastTime2 = date('Y-m-d H:i:s', $timestamp2);
//echo '<br />'.$lastTime1;
//echo '<br />'.$lastTime2;die;
$messageData = [];
$notApprovedData = (new Bookings())
->join('booking_dates','booking_dates.booking_id','=','bookings.booking_id')
->where(['is_approved' => '0','is_send' => '0'])
->whereBetween('bookings.created_at', [$lastTime1,$lastTime2])
//->whereDate('bookings.created_at', '<', $utcCurrentTime)
//->whereDate('bookings.created_at', '<', $lastTime)
//->whereDate('booking_dates.date','>',date('Y-m-d'))
->groupBy('bookings.booking_id')
->get()->toArray();
foreach($notApprovedData as $data) {
$propertyName = (new PropertyFieldValue())->getPropertyDetail($data['property_id']);
$propertyFullName = '';
$routefunction = '<a href="' . route('pending-approval-booking-properties') . '">Click here</a>';
foreach ($propertyName as $property) {
if ($property['field_name'] == 'Name') {
$propertyFullName = $property['property_type_section_field_value'];
}
}
$routefunction = '<a href="'.route('pending-approval-booking-properties').'">Click here</a>';
$property_owner_details = User::where('id', $data['property_owner_id'])->first();
$userName = $property_owner_details['first_name'].' '.$property_owner_details['Last_name'];
$templateLog = (new TemplateLog())->where(['template_log_id' => '7'])->first();
$userTaskDes = array("#user_name#","#property_name#","#click_here#");
$userTaskRep = array($userName,$propertyFullName,$routefunction);
$messages = $templateLog->message;
$newTaskDes = str_replace($userTaskDes,$userTaskRep,$messages);
$messageBody = $newTaskDes;
$messageData[] = [
'type' => '1',
'subject' => 'Property Approval Reminder',
'body' => $messageBody,
'email' => $property_owner_details['email'],
'mobile_no' => $property_owner_details['mobile_number'],
'is_send' => "1",
'status' => '0',
'url' => "/success",
];
(new Bookings())->where(['booking_id' => $data['booking_id']])->update(['is_send' => '1']);
}
if(!empty($messageData)) {
(new MessageToBeSend())->insert($messageData);
echo 'done';
}
}
/* function ru after 16 hours of booking property */
public function maiToNotAprovedPropertySecond(){
$utcCurrentTime = gmdate(date('Y-m-d H:i:s'));
$timestamp = strtotime($utcCurrentTime) - 570*120;
$timestamp2 = strtotime($utcCurrentTime) - 600*120;
$lastTime1 = date('Y-m-d H:i:s', $timestamp);
$lastTime2 = date('Y-m-d H:i:s', $timestamp2);
//echo '<br />'.$utcCurrentTime;
//echo '<br />'.$lastTime1;
//echo '<br />'.$lastTime2;die;
$messageData = [];
$notApprovedData = (new Bookings())
->join('booking_dates','booking_dates.booking_id','=','bookings.booking_id')
->where(['is_approved' => '0','is_send' => '1'])
->whereBetween('bookings.created_at', [$lastTime1,$lastTime2])
//->whereDate('bookings.created_at', '<', $utcCurrentTime)
//->whereDate('bookings.created_at', '<', $lastTime)
//->whereDate('booking_dates.date','>',date('Y-m-d'))
->groupBy('bookings.booking_id')
->get()->toArray();
foreach($notApprovedData as $data) {
$propertyName = (new PropertyFieldValue())->getPropertyDetail($data['property_id']);
$propertyFullName = '';
$routefunction = '<a href="' . route('pending-approval-booking-properties') . '">Click here</a>';
foreach ($propertyName as $property) {
if ($property['field_name'] == 'Name') {
$propertyFullName = $property['property_type_section_field_value'];
}
}
$routefunction = '<a href="'.route('pending-approval-booking-properties').'">Click here</a>';
$property_owner_details = User::where('id', $data['property_owner_id'])->first();
$userName = $property_owner_details['first_name'].' '.$property_owner_details['Last_name'];
$templateLog = (new TemplateLog())->where(['template_log_id' => '7'])->first();
$userTaskDes = array("#user_name#","#property_name#","#click_here#");
$userTaskRep = array($userName,$propertyFullName,$routefunction);
$messages = $templateLog->message;
$newTaskDes = str_replace($userTaskDes,$userTaskRep,$messages);
$messageBody = $newTaskDes;
$messageData[] = [
'type' => '1',
'subject' => 'Property Approval Reminder',
'body' => $messageBody,
'email' => $property_owner_details['email'],
'mobile_no' => $property_owner_details['mobile_number'],
'is_send' => "1",
'status' => '0',
'url' => "/success",
];
(new Bookings())->where(['booking_id' => $data['booking_id']])->update(['is_send' => '2']);
}
if(!empty($messageData)) {
(new MessageToBeSend())->insert($messageData);
echo 'done';
}
}
/* function run after 48 hours to approve property */
public function approvedPropertyMail(){
$utcCurrentTime = gmdate(date('Y-m-d H:i:s'));
//$timestamp = strtotime($utcCurrentTime) - 20*60;
//$timestamp2 = strtotime($utcCurrentTime) - 10*60;
//$lastTime1 = date('Y-m-d H:i:s', $timestamp);
//$lastTime2 = date('Y-m-d H:i:s', $timestamp2);
$lastTime1 = date('Y-m-d H:i:s', strtotime($utcCurrentTime . " -48 hours"));
$lastTime2 = date('Y-m-d H:i:s', strtotime($utcCurrentTime . " -47 hours"));
//echo '<br />'.$utcCurrentTime;
//echo '<br />'.$lastTime1;
//echo '<br />'.$lastTime2;
$messageData = [];
$notApprovedData = (new Bookings())
->join('booking_dates','booking_dates.booking_id','=','bookings.booking_id')
->where(['is_approved' => '1','payment_status' => '0'])
->where('is_send','!=','3')
->whereBetween('bookings.updated_at', [$lastTime1,$lastTime2])
//->whereDate('bookings.created_at', '<', $utcCurrentTime)
//->whereDate('bookings.created_at', '<', $lastTime)
//->whereDate('booking_dates.date','>',date('Y-m-d'))
->groupBy('bookings.booking_id')
->get()->toArray();
//pr($notApprovedData);
foreach($notApprovedData as $data) {
$propertyName = (new PropertyFieldValue())->getPropertyDetail($data['property_id']);
$propertyFullName = '';
$routefunction = '<a href="' . route('approved-booking-properties',['id' => $data['booking_id']]) . '">Click here</a>';
foreach ($propertyName as $property) {
if ($property['field_name'] == 'Name') {
$propertyFullName = $property['property_type_section_field_value'];
}
}
//$routefunction = '<a href="'.route('pending-approval-booking-properties').'">Click here</a>';
$property_owner_details = User::where('id', $data['property_owner_id'])->first();
$buyerDetail = User::where('id', $data['user_id'])->first();
$userName = $property_owner_details['first_name'].' '.$property_owner_details['Last_name'];
$buyerName = $buyerDetail['first_name'].' '.$buyerDetail['Last_name'];
$templateLog = (new TemplateLog())->where(['template_log_id' => '8'])->first();
$userTaskDes = array("#user_name#","#buyer_name#","#property_name#","#click_here#");
$userTaskRep = array($userName,$buyerName,$propertyFullName,$routefunction);
$messages = $templateLog->message;
$newTaskDes = str_replace($userTaskDes,$userTaskRep,$messages);
$messageBody = $newTaskDes;
$messageData[] = [
'type' => '1',
'subject' => 'Property Status Reminder',
'body' => $messageBody,
'email' => $property_owner_details['email'],
'mobile_no' => $property_owner_details['mobile_number'],
'is_send' => "1",
'status' => '0',
'url' => "/success",
];
(new Bookings())->where(['booking_id' => $data['booking_id']])->update(['is_send' => '3']);
}
if(!empty($messageData)) {
(new MessageToBeSend())->insert($messageData);
echo 'done';
}
}
}
<file_sep>/database/migrations/2017_08_31_143120_create_users_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateUsersTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if (!Schema::hasTable('users')) {
Schema::create('users', function(Blueprint $table)
{
$table->integer('id', true);
$table->string('first_name', 45)->nullable();
$table->string('last_name', 45)->nullable();
$table->string('remember_token', 100)->nullable();
$table->string('email', 100)->nullable();
$table->string('password', 100)->nullable();
$table->boolean('role')->nullable()->comment('1 for admin, 2 for user');
$table->timestamps();
});
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
<file_sep>/app/Http/Requests/StorePropertyTypeSectionField.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use App\PropertyTypeSection;
class StorePropertyTypeSectionField extends FormRequest
{
// private $messages = [];
private $attribute = [];
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$requestUrl = \Request::all();
$id = $requestUrl['property_types_id'];
$propertyTypesSections = (new PropertyTypeSection())
->rightjoin('property_type_section_fields', 'property_type_section_fields.property_type_section_id','=', 'property_type_sections.id')
->where('property_type_sections.property_type_id' , $id)
->select('property_type_section_fields.id as property_type_section_fields_id','property_type_section_fields.name', 'validations')
->get()->toArray();
$validations = [];
foreach($propertyTypesSections as $index => $propertyTypesSection) {
$explodeValidations = explode(',', $propertyTypesSection['validations']);
$validations[$propertyTypesSection['property_type_section_fields_id']] = str_replace(',', '|', $propertyTypesSection['validations']);
foreach($explodeValidations as $explodeValidation) {
// $this->messages[$propertyTypesSection['property_type_section_fields_id'].'.'.$explodeValidation] = ':attribute '.$propertyTypesSection['name'];
$this->attribute[$propertyTypesSection['property_type_section_fields_id']] = $propertyTypesSection['name'];
}
}
//pr($propertyTypesSections);
//pr($validations);
//die;
return $validations;
}
public function attributes()
{
pr($this->attribute);
// die;
return $this->attribute;
}
}
<file_sep>/database/seeds/AdminSeeder.php
<?php
use Illuminate\Database\Seeder;
class AdminSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//DB::table('users')->truncate();
/*DB::table('users')->insert([
'first_name' => 'admin',
'last_name' => 'web',
'email' => '<EMAIL>',
'password' => bcrypt('<PASSWORD>'),
'is_verified' => 1,
'role' => 1,
]);*/
DB::table('users')->delete();
DB::table('users')->insert(array(
array('first_name'=>'admin','last_name'=>'web','email' => '<EMAIL>', 'mobile_number'=>'8888888888','password' => bcrypt('<PASSWORD>'),'is_verified' => 1,'role' => 1),
array('first_name'=>'Jorge','last_name'=>'Seller','email' => '<EMAIL>', 'mobile_number'=>'9999999999','password' => bcrypt('<PASSWORD>'),'is_verified' => 1,'role' => 2),
));
}
}
<file_sep>/app/Http/Controllers/Auth/LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Contracts\Auth\Guard;
use Auth;
use Session;
use Cookie;
use App\User;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* @var string
*/
//protected $redirectTo = '/propertytype';
protected $redirectTo ;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function authenticated(Request $request,$user)
{
$remember = $request->get('remember');
$auth = Auth::attempt(
[
'email' => strtolower($request->get('email')),
'password' => $request->get('password')
], $remember
);
if($auth){
if(isset($remember)){
$ckname = Auth::getRecallerName();
Cookie::queue($ckname, Cookie::get($ckname), 43200);
Cookie::queue('remembered','remembered', 43200);
Cookie::queue('email',$request->get('email'), 43200);
Cookie::queue('pass',$request->get('password'), 43200);
}else{
$ckname = Auth::getRecallerName();
Cookie::queue($ckname, '', 43200);
Cookie::queue('remembered','', 43200);
Cookie::queue('email','', 43200);
Cookie::queue('pass','', 43200);
}
$this->setUserSession($user);
if(Auth::user()->role == 1){
$this->redirectTo = '/propertytype';
}
if(Auth::user()->role == 2){
$this->redirectTo = route('home');
}
if((Auth::user()->role == 2) && ($request->session()->get('property_id'))){
$propertyId = $request->session()->get('property_id');
Session::forget('key');
$this->redirectTo = 'property-detail?property_id='.$propertyId;
}
} else {
return Redirect::to('/')
->withInput(Input::except('password'))
->with('flash_notice', 'Your username/password combination was incorrect.');
}
}
/*=============================
Check is email is Verified
================================*/
protected function credentials(Request $request) {
$credentials = $request->only($this->username(), 'password');
$credentials['is_verified'] = 1;
return $credentials;
}
/*==============================================
Change Error Message if Email is not Verified
===================================================*/
protected function sendFailedLoginResponse(Request $request) {
$errors = [$this->username() => trans('auth.failed')];
// Load user from database
$user = \App\User::where($this->username(), $request->{$this->username()})->first();
if ($user && \Hash::check($request->password, $user->password) && $user->is_verified != 1) {
$errors = [$this->username() => 'Please verify your email before login.'];
}
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
protected function setUserSession($user) {
Session::put('user_session', $user->email);
}
}
<file_sep>/app/Http/Controllers/PropertyTypeSectionFieldController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\PropertyType;
use App\PropertyTypeSection;
use App\InputFieldType;
use App\Validation;
use App\User;
use App\PropertyTypeSectionField;
use App\PropertyTypeSectionFieldOption;
use Mockery\CountValidator\Exception;
use Validator;
use Illuminate\Support\Facades\DB;
class PropertyTypeSectionFieldController extends Controller
{
public function singlefieldedit($field_id){
$InputFieldTypes = InputFieldType::all();
$Validations = Validation::all();
$section_field = PropertyTypeSectionField::with(['propertytypesectionfieldoption' => function ($query) {
}])->where('id', $field_id)->get();
$section_field = $section_field->toArray();
$section_field = $section_field[0];
return view('PropertyTypeSectionField.singlefieldedit', compact('InputFieldTypes', 'section_field', 'Validations'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id) {
$PropertyType = new PropertyType;
$PropertyTypeSection = new PropertyTypeSection;
//Get all the information associated with given ID
$PropertyType = PropertyType::find($id);
$PropertyTypeSections = PropertyTypeSection::where('property_type_id', $id)->orderBy('order_id', 'asc')->get();
$InputFieldTypes = InputFieldType::all();
$Validations = Validation::all();
//And return to edit.blade.php view file.
return view('Propertytype.edit', compact('PropertyType', 'PropertyTypeSections', 'InputFieldTypes', 'Validations'));
}
}
<file_sep>/app/Http/Controllers/HomeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$this->middleware('auth');
return view('Propertytype.home');
}
public function create() {
$this->middleware('auth');
echo 'sdf';
}
public function sendEmail(){
\Mail::send('email.verified_link', array('content' => 'TEST EMAIL CONTENT'), function($email) {
$email->to('<EMAIL>')->subject('Test Email');
});
if(\Mail::failures()){
echo 'Email Not Send';
}else{
echo 'Email Send';
}
}
}
<file_sep>/app/ProertiesPolicyUpdation.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use DB;
class ProertiesPolicyUpdation extends Model
{
protected $table = 'properties_policy_updation';
protected $fillable = [
'id', 'property_id', 'policy_id'
];
}
<file_sep>/app/Http/Controllers/PropertyController.php
<?php
namespace App\Http\Controllers;
use App\Property;
use App\TemplateLog;
use Illuminate\Http\Request;
use App\PropertyType;
use App\PropertyTypeSection;
use App\PropertyTypeSectionFieldOption;
use App\PropertyTypeSectionField;
use App\PropertyFieldValue;
use App\Bookings;
use Carbon\Carbon;
use App\BookingDates;
use App\Http\Requests\StorePropertyTypeSectionField;
use App\Http\Requests\BookingPropertyRequest;
use App\PropertyAvailaibility;
use App\PropertyAvailaibilityDate;
use App\PropertyReviews;
use App\MessageToBeSend;
use App\CancellationPolicyType;
use App\User;
use DB;
use Auth;
use Session;
use Validator;
use Config;
use Request as AjaxRequest;
class PropertyController extends Controller
{
public function index(Request $request){
$Inputs = $request->all();
$display = isset($Inputs['display']) ? $Inputs['display'] : 'grid';
$order_by = isset($Inputs['filter_order_by']) ? $Inputs['filter_order_by'] : 1;
$offset = isset($Inputs['offset']) ? $Inputs['offset'] :0;
$offsetLimit=6;
$propertyTypes = (new PropertyType())
->where(['deleted_at' => NULL])
->get(['name','id'])->toArray();
$propertyTypesId = $request->input('property_type_id');
$query = Property::join('properties_field_values', 'properties_field_values.property_id', '=', 'properties.id')
->join('property_type_section_fields','property_type_section_fields.id','=', 'properties_field_values.property_type_section_field_id' )
->join('property_availaibility','property_availaibility.property_id','=', 'properties.id' )
->select('properties.id as propertyIds' ,'properties_field_values.property_type_section_field_value as price')
->where(array('property_type_section_fields.field_identifier' => 'basic_price', 'property_availaibility.is_blocked' => 1 ))
->whereExists(function ($query){
$query->select(DB::raw(1))
->from('property_availaibility')
->join('property_availaibility_dates', 'property_availaibility_dates.property_availaibility_id', '=', 'property_availaibility.id')
->whereRaw('property_availaibility.property_id = properties.id');
});
switch($order_by){
case 2:
$q = "CAST(price AS DECIMAL(10,2)) ASC";
$allProperties = $query->orderByRaw($q)->skip($offset)->take($offsetLimit)->get()->toArray();
break;
case 3:
$allProperties = $query->orderBy('properties.id', "DESC")->skip($offset)->take($offsetLimit)->get()->toArray();
break;
case 4:
$allProperties = $query->orderBy('properties.id', "ASC")->skip($offset)->take($offsetLimit)->get()->toArray();
break;
default:
$q = "CAST(price AS DECIMAL(10,2)) DESC";
$allProperties = $query->orderByRaw($q)->skip($offset)->take($offsetLimit)->get()->toArray();
}
$propertyIDS = array();
if(isset($allProperties)){
foreach($allProperties as $value){
$propertyIDS[] = $value["propertyIds"];
}
}
if(count($propertyIDS)){
$properties_data = (new Property())->getPropertyRelatedData($propertyIDS);
}
if(isset($properties_data)){
$propertyArr = prepareDataForProperties($properties_data);
} else {
$propertyArr = 0;
}
if(AjaxRequest::ajax()) {
$view = view( 'Propertytype.lazy_loading_home_page', compact( 'propertyTypes', 'propertyTypesId', 'propertyArr', 'display', 'allProperties', 'propertyTypesId', 'order_by' ))->render();
if(!empty($propertyArr)){
$result =[
'success' => 100,
'data' => $view,
];
} else{
$result =[
'success' => 50
];
}
return response()->json($result);
} else {
return view('Propertytype.property_index', compact('propertyTypes', 'propertyTypesId', 'propertyArr', 'display', 'allProperties', 'propertyTypesId', 'order_by'));
}
}
public function propertyIndex(Request $request){
$filters = $request->input('property_filters');
$Inputs = $request->all();
/*$currentLocationLatitude = isset($Inputs['currentLocationLatitude']) ? $Inputs['currentLocationLatitude']:0 ;
$currentLocationlongitude = isset($Inputs['currentLocationlongitude']) ? $Inputs['currentLocationlongitude'] : 0;
Session()->put('lat', $currentLocationLatitude);
Session()->put('lng', $currentLocationlongitude);*/
//$limit = isset($Inputs['limit']) ? (int)$Inputs['limit'] : 2;
$searchDistance = Config::get('constants.SEARCH_DISTANCE');
$setData = isset($Inputs['setData']) ? (int)$Inputs['setData'] : 0;
if($setData==1){
$startDate = isset($Inputs['start_date']) ? date("Y-m-d", strtotime($Inputs['start_date'])) : '' ;
$distance = isset($Inputs['distance']) ? (int)$Inputs['distance'] : 0;
}else{
$startDate = isset($Inputs['start_date']) ? date("Y-m-d", strtotime($Inputs['start_date'])) : date("Y-m-d") ;
$distance = isset($Inputs['distance']) ? (int)$Inputs['distance'] : $searchDistance;
}
$offset = isset($Inputs['offset']) ? (int)$Inputs['offset'] : 0;
$latitude = isset($Inputs['lat']) ? $Inputs['lat'] :0;
$longitude = isset($Inputs['long']) ? $Inputs['long'] :0;
/*$getLatSearchBar = isset($Inputs['getLatSearchBar']) ? $Inputs['getLatSearchBar'] :0;
$getLongSearchBar = isset($Inputs['getLongSearchBar']) ? $Inputs['getLongSearchBar'] :0;
Session()->put('lat', $getLatSearchBar);
Session()->put('lng', $getLongSearchBar);*/
$order_by = isset($Inputs['filter_order_by']) ? $Inputs['filter_order_by'] : 1;
$display = isset($Inputs['display']) ? $Inputs['display'] : 'grid';
$endDate = isset($Inputs['end_date']) ? date("Y-m-d", strtotime($Inputs['end_date'])) : null;
$min_price = isset($Inputs['min_price']) ? $Inputs['min_price'] : 0;
$max_price = isset($Inputs['max_price']) ? $Inputs['max_price'] : 0;
$propertyTypes = (new PropertyType())
->where(['deleted_at' => NULL])
->get(['name','id'])->toArray();
$propertyTypesId = $request->input('property_type_id');
$location = isset($Inputs['location']) ? $Inputs['location'] : '';
$query = Property::join('properties_field_values', 'properties_field_values.property_id', '=', 'properties.id')
->join('property_type_section_fields','property_type_section_fields.id','=', 'properties_field_values.property_type_section_field_id' )
->join('property_availaibility','property_availaibility.property_id','=', 'properties.id' )
->select(\DB::raw("@id :=( 6371 * acos( cos( radians(" . $latitude . ") ) * cos( radians(lat) ) *
cos( radians(lng) - radians(" . $longitude . ") ) + sin( radians(" . $latitude . ") ) *
sin( radians(lat) ) ) ) AS distance"), 'properties.id as propertyIds', 'properties.created_at' ,'properties_field_values.property_type_section_field_value as price' )
->where(array('property_type_section_fields.field_identifier' => 'basic_price', 'property_availaibility.is_blocked' => 1))
->groupBy('properties.id')
->when($distance, function($q) use ($distance){
if(!empty($distance)) {
return $q->havingRaw('distance<=' . $distance);
}
})
->whereExists(function ($query) use ($startDate,$endDate) {
$query->select(DB::raw(1))
->from('property_availaibility')
->join('property_availaibility_dates', 'property_availaibility_dates.property_availaibility_id', '=', 'property_availaibility.id')
->where(function($query2) use ($startDate,$endDate) {
if( (isset($startDate)) && (isset($endDate))){
/*$query2->whereBetween('property_availaibility_dates.date', [$startDate, $endDate])
->Where('property_availaibility_dates.is_booked',0);*/
$query2->whereDate('property_availaibility_dates.date', '>=',$startDate)
->whereDate('property_availaibility_dates.date', '<=', $endDate)
->Where('property_availaibility_dates.is_booked',0);
}elseif(isset($startDate)){
$query2->Where('property_availaibility_dates.date','>=', $startDate)
->Where('property_availaibility_dates.is_booked',0);
}elseif(isset($endDate)){
$current_date = date("Y-m-d");
$query2->whereBetween('property_availaibility_dates.date', [$current_date, $endDate])
->Where('property_availaibility_dates.is_booked',0);
}
})
->whereRaw('property_availaibility.property_id = properties.id');
})
->where(array('properties.property_type_id' => $propertyTypesId));
$query = $query->whereExists(function ($query) use ( $min_price, $max_price) {
$query->select(DB::raw(1))
->from('properties_field_values')
->join('property_type_section_fields', 'property_type_section_fields.id', '=', 'properties_field_values.property_type_section_field_id')
->where(function($query) use ($min_price,$max_price) {
if( (isset($min_price)) && (isset($max_price)) && ($max_price>0) ) {
$query->where('field_identifier', '=', 'basic_price')->whereBetween('properties_field_values.property_type_section_field_value', [(int)$min_price, (int)$max_price]);
}
})
->whereRaw('properties_field_values.property_id = properties.id');
});
$query = $query->whereExists(function ($query) use ($filters) {
$query->select(DB::raw(1))
->from('properties_field_values')
->join('property_type_section_fields', 'property_type_section_fields.id', '=', 'properties_field_values.property_type_section_field_id')
->where(function($query) use ($filters) {
if(isset($filters) && count($filters)){
$query->whereIn('properties_field_values.property_type_section_field_value', $filters);
}
})
->whereRaw('properties_field_values.property_id = properties.id');
});
$offsetLimit = Config::get('constants.OFFSET_LIMIT_PROPERTY_SEARCH');
switch($order_by){
case 2:
$q = "CAST(price AS DECIMAL(10,2)) ASC";
$allProperties=$query->orderByRaw($q)->skip($offset)->take($offsetLimit)->get()->toArray();
break;
case 3:
$allProperties = $query->orderBy('properties.created_at', "DESC")->skip($offset)->take($offsetLimit)->get()->toArray(); // Newest
break;
case 4:
$allProperties = $query->orderBy('properties.created_at', "ASC")->skip($offset)->take($offsetLimit)->get()->toArray(); // Oldest
break;
case 5:
$allProperties = $query->orderBy('distance', "ASC")->skip($offset)->take($offsetLimit)->get()->toArray(); // Sort By Distance Ascending
break;
case 6:
$allProperties = $query->orderBy('distance', "DESC")->skip($offset)->take($offsetLimit)->get()->toArray(); // Sort By Distance Descending
break;
default:
$q = "CAST(price AS DECIMAL(10,2)) DESC"; // Price High to low
$allProperties = $query->orderByRaw($q)->skip($offset)->take($offsetLimit)->get()->toArray();
}
$propertyIDS = array();
if(isset($allProperties)){
foreach($allProperties as $value){
$propertyIDS[] = $value["propertyIds"];
}
}
if(count($propertyIDS)){
$properties_data = (new Property())->getPropertyRelatedData($propertyIDS);
}
if(isset($properties_data)){
$propertyArr = prepareDataForProperties($properties_data); // Defined in Helper
} else {
$propertyArr = 0;
}
$property_filters = (new PropertyTypeSection())->getPropertyFilters( $propertyTypesId, $min_price, $max_price );
$filter_array = array();
foreach($property_filters as $key => $value){
$filter_array[$value['name']][$value['id']] = $value['display_value'];
}
$count = count($propertyArr);
return view( 'Propertytype.property_filter_results', compact( 'propertyTypes', 'propertyTypesId', 'propertyArr', 'display', 'allProperties', 'property_filters', 'location', 'propertyTypesId', 'startDate', 'endDate', 'min_price', 'max_price', 'filters', 'order_by', 'latitude', 'longitude', 'distance', 'offset','count', 'setData','filter_array' ));
}
public function propertyIndexAjax(Request $request){
$filters = $request->input('property_filters');
$Inputs = $request->all();
//$limit = isset($Inputs['limit']) ? (int)$Inputs['limit'] : 2;
/* $currentLocationLatitude = isset($Inputs['currentLocationLatitude']) ? $Inputs['currentLocationLatitude']:'' ;
$currentLocationlongitude = isset($Inputs['currentLocationlongitude']) ? $Inputs['currentLocationlongitude'] : '';*/
$searchDistance = Config::get('constants.SEARCH_DISTANCE');
$setData = isset($Inputs['setData']) ? (int)$Inputs['setData'] : 0;
if($setData==1){
$startDate = isset($Inputs['start_date']) ? date("Y-m-d", strtotime($Inputs['start_date'])) : '' ;
$distance = isset($Inputs['distance']) ? (int)$Inputs['distance'] : 0;
}else{
$startDate = isset($Inputs['start_date']) ? date("Y-m-d", strtotime($Inputs['start_date'])) : date("Y-m-d") ;
$distance = isset($Inputs['distance']) ? (int)$Inputs['distance'] : $searchDistance;
}
$offset = isset($Inputs['offset']) ? (int)$Inputs['offset'] : 0;
$latitude = isset($Inputs['lat']) ? $Inputs['lat'] :0;
$longitude = isset($Inputs['long']) ? $Inputs['long'] : 0;
$order_by = isset($Inputs['filter_order_by']) ? $Inputs['filter_order_by'] : 1;
$display = isset($Inputs['display']) ? $Inputs['display'] : 'grid';
$endDate = isset($Inputs['end_date']) ? date("Y-m-d", strtotime($Inputs['end_date'])) : null;
$min_price = isset($Inputs['min_price']) ? $Inputs['min_price'] : 0;
$max_price = isset($Inputs['max_price']) ? $Inputs['max_price'] : 0;
$propertyTypes = (new PropertyType())
->where(['deleted_at' => NULL])
->get(['name','id'])->toArray();
$propertyTypesId = $request->input('property_type_id');
$location=$Inputs['location'];
$query = Property::join('properties_field_values', 'properties_field_values.property_id', '=', 'properties.id')
->join('property_type_section_fields','property_type_section_fields.id','=', 'properties_field_values.property_type_section_field_id' )
->join('property_availaibility','property_availaibility.property_id','=', 'properties.id' )
->select(\DB::raw("@id :=( 6371 * acos( cos( radians(" . $latitude . ") ) * cos( radians(lat) ) *
cos( radians(lng) - radians(" . $longitude . ") ) + sin( radians(" . $latitude . ") ) *
sin( radians(lat) ) ) ) AS distance"), 'properties.id as propertyIds' ,'properties_field_values.property_type_section_field_value as price' )
->where(array('property_type_section_fields.field_identifier' => 'basic_price', 'property_availaibility.is_blocked' => 1 ))
->groupBy('properties.id')
->when($distance, function($q) use ($distance){
if(!empty($distance)) {
return $q->havingRaw('distance<=' . $distance);
}
})
->whereExists(function ($query) use ($startDate,$endDate) {
$query->select(DB::raw(1))
->from('property_availaibility')
->join('property_availaibility_dates', 'property_availaibility_dates.property_availaibility_id', '=', 'property_availaibility.id')
->where(function($query2) use ($startDate,$endDate) {
if( (isset($startDate)) && (isset($endDate))){
$query2->whereDate('property_availaibility_dates.date', '>=',$startDate)
->whereDate('property_availaibility_dates.date', '<=', $endDate)
->Where('property_availaibility_dates.is_booked',0);
}elseif(isset($startDate)){
$query2->Where('property_availaibility_dates.date','>=', $startDate)
->Where('property_availaibility_dates.is_booked',0);
}elseif(isset($endDate)){
$current_date = date("Y-m-d");
$query2->whereBetween('property_availaibility_dates.date', [$current_date, $endDate])
->Where('property_availaibility_dates.is_booked',0);
}
})
->whereRaw('property_availaibility.property_id = properties.id');
})
->where(array('properties.property_type_id' => $propertyTypesId));
$query = $query->whereExists(function ($query) use ( $min_price, $max_price) {
$query->select(DB::raw(1))
->from('properties_field_values')
->join('property_type_section_fields', 'property_type_section_fields.id', '=', 'properties_field_values.property_type_section_field_id')
->where(function($query) use ($min_price,$max_price) {
if( (isset($min_price)) && (isset($max_price)) && ($max_price>0) ) {
$query->where('field_identifier', '=', 'basic_price')->whereBetween('properties_field_values.property_type_section_field_value', [(int)$min_price, (int)$max_price]);
}
})
->whereRaw('properties_field_values.property_id = properties.id');
});
$query = $query->whereExists(function ($query) use ($filters) {
$query->select(DB::raw(1))
->from('properties_field_values')
->join('property_type_section_fields', 'property_type_section_fields.id', '=', 'properties_field_values.property_type_section_field_id')
->where(function($query) use ($filters) {
if(isset($filters) && count($filters)){
$query->whereIn('properties_field_values.property_type_section_field_value', $filters);
}
})
->whereRaw('properties_field_values.property_id = properties.id');
});
$offsetLimit = Config::get('constants.OFFSET_LIMIT_PROPERTY_SEARCH');
// echo $offsetLimit;
switch($order_by){
case 2:
$q = "CAST(price AS DECIMAL(10,2)) ASC";
//$allProperties = $query->orderByRaw($q)->paginate(4);
//$allProperties = $query->orderByRaw($q)->offset($offset)->limit($limit)->get()->toArray();
$allProperties=$query->orderByRaw($q)->skip($offset)->take($offsetLimit)->get()->toArray();
break;
case 3:
$allProperties = $query->orderBy('properties.id', "DESC")->skip($offset)->take($offsetLimit)->get()->toArray();
break;
case 4:
$allProperties = $query->orderBy('properties.id', "ASC")->skip($offset)->take($offsetLimit)->get()->toArray();
break;
case 5:
$allProperties = $query->orderBy('distance', "ASC")->skip($offset)->take($offsetLimit)->get()->toArray(); // Sort By Distance Ascending
break;
case 6:
$allProperties = $query->orderBy('distance', "DESC")->skip($offset)->take($offsetLimit)->get()->toArray(); // Sort By Distance Descending
break;
default:
$q = "CAST(price AS DECIMAL(10,2)) DESC";
$allProperties = $query->orderByRaw($q)->skip($offset)->take($offsetLimit)->get()->toArray();
}
$propertyIDS = array();
if(isset($allProperties)){
foreach($allProperties as $value){
$propertyIDS[] = $value["propertyIds"];
}
}//pr($propertyIDS);
if(count($propertyIDS)){
$properties_data = (new Property())->getPropertyRelatedData($propertyIDS);
}
if(isset($properties_data)){
$propertyArr = prepareDataForProperties($properties_data); // Defined in Helper
} else {
$propertyArr = 0;
}//pr($propertyArr,1);
$property_filters = (new PropertyTypeSection())->getPropertyFilters( $propertyTypesId, $min_price, $max_price );
$view = view( 'Propertytype.property_filter_result_data', compact( 'propertyTypes', 'propertyTypesId', 'propertyArr', 'display', 'allProperties', 'property_filters', 'location', 'propertyTypesId', 'startDate', 'endDate', 'min_price', 'max_price', 'filters', 'order_by', 'latitude', 'longitude', 'distance', 'limit', 'offset' ))->render();
if(!empty($propertyArr)){
$result =[
'success' => 100,
'data' => $view,
];
} else{
$result =[
'success' => 50
];
}
return response()->json($result);
}
/*======================
Get Property Detail
========================*/
public function propertyDetail(Request $request){
$inputs = $request->all();
$propertyId = $inputs['property_id'];
$startDate ='';
$endDate ='';
$approvedBooking ='';
$bookingId ='';
if(isset($inputs['bookingId'])){
$bookingId = $inputs['bookingId'];
$bookingDate = (new Bookings())->getBookingDatesByBookingID( $bookingId );
$startDate = $bookingDate[0]['date'];
$endDate = $bookingDate[count($bookingDate) - 1]['date'];
$bookingData = Bookings::where('booking_id', $bookingId)->first();
$approvedBooking= $bookingData->is_approved;
}
$propertyDetails = (new PropertyFieldValue())->getPropertyDetail( $propertyId );
$properties = Property::where('id', $propertyId)->first();
$checked_requied=$properties['is_approved_checked'];
foreach($propertyDetails as $propertyDetail){
if($propertyDetail['is_option']==1){
$ids[] = $propertyDetail['property_type_section_field_value'];
}
}
if((isset($ids)) && (count($ids))){
$display_values = (new PropertyTypeSectionFieldOption())->getDisplayValues( $ids );
} else {
$display_values[]=0;
}
$localDates = (new PropertyAvailaibility())->getPropertyAvailabilityDates( $propertyId );
$available_dates= convertUtcToLocal($localDates, $properties->timezone_name); // Convert dates to local dates
$propertyReviews = (new PropertyReviews())->getReviewOfBuyer( $propertyId );
$totalReviewOfBuyer = (new PropertyReviews())->getTotalReviewOfBuyer( $propertyId );
$section_array = prepareDataForPropertyDetail( $propertyDetails );
return view('Propertytype.property_detail',compact('bookingId','approvedBooking','startDate','endDate','checked_requied','section_array','available_dates', 'propertyId','display_values', 'propertyReviews', 'totalReviewOfBuyer'));
}
/*=================
Book Property
===================*/
public function bookProperty(BookingPropertyRequest $request){
$inputs = $request->all();
if(isset($inputs['approvedBooking'])){
$bookingId = $inputs['bookingId'];
$approvedBooking = $inputs['approvedBooking'];
$availabilityIds = (new PropertyAvailaibility())->getPropertyAvailabilityBetweenDates( $inputs['property_id'], $inputs['start_date'], $inputs['end_date'] );
$bookingDate = (new Bookings())->getBookingDatesByBookingID( $bookingId );
if(count($availabilityIds) == count($bookingDate)){
$booked = (new PropertyAvailaibilityDate())->dateBook( $availabilityIds );
if($booked){
if( Bookings::where('booking_id', $bookingId)->update(array('payment_status' => 1))){
$this->sendConfrimedBookingEmail($inputs['property_id'],$inputs['start_date'], $inputs['end_date'],$inputs['ownerID']);
return response()->json(['success'=>true,'message'=>'Your Booking is done successfully'] );
} else {
return response()->json(['success'=>false,'message'=>'These dates are not available'] );
}
}
}else {
return response()->json(['success'=>false,'message'=>'These dates are not available'] );
}
} else {
$time = Config::get('constants.START_TIME');
$approval_required = $inputs['approval_required'];
$available = (new PropertyAvailaibility())->checkIfBookedOnDate($inputs['property_id'],$inputs['start_date'], $inputs['end_date']);
$propertydata = Property::where('id', $inputs['property_id'])->first();
$cancelPolicyId= $propertydata['policy_types_id'];
$bookDates = $inputs['bookFor'];
$booking_dates = convertLocalToUTC($bookDates, $time, $propertydata->timezone_name); // Convert local to UTC dates
$result = array_diff($booking_dates,$available);
if(count($result)){
return response()->json(['success'=>false,'message'=>'These dates are not available']);
}
if(Auth::user()->id == $inputs['ownerID'] ){
return response()->json(['success'=>false,'message'=>'Can not book your own property']);
}
$property_status= $this->getPropertyStatus($inputs['property_id']);
$propertyTimezone= $property_status['timezone_name'];
$dateResult = getUtcTime($propertyTimezone);
$currentDateTime=$dateResult['currentTime'];
$utcDateTime=$dateResult['utcTime'];
$statusvalue = $property_status->is_approved_checked;
$data['property_id'] = $inputs['property_id'];
$data['user_id'] = Auth::user()->id;
$data['property_owner_id'] = $inputs['ownerID'];
$data['total_amount'] = $inputs['total_amount'];
$data['policy_id'] = $cancelPolicyId;
$data['utc_time'] = $utcDateTime;
$data['payment_status'] = 0;
if($statusvalue==1){
$data['is_approved'] = 0;
$data['payment_status'] = 0;
$data['through_approval'] = 1;
} else {
$data['is_approved'] = 1;
$data['payment_status'] = 1;
$data['through_approval'] = 0;
}
$bookObj = new Bookings($data);
if( $bookObj->save() ){
$propertyName = (new PropertyFieldValue())->getPropertyDetail($inputs['property_id']);
$propertyFullName = '';
$routefunction = '<a href="'.route('pending-approval-booking-properties').'">Click here</a>';
foreach($propertyName as $property){
if($property['field_name'] == 'Name'){
$propertyFullName = $property['property_type_section_field_value'];
}
}
$property_owner_details = User::where('id', $inputs['ownerID'])->first();
$buyerDetail = User::where('id', $data['user_id'])->first();
$book['booking_id']=$bookObj->id;
$userName = $property_owner_details['first_name'].' '.$property_owner_details['Last_name'];
$buyer = $buyerDetail['first_name'].' '.$buyerDetail['last_name'];
$templateLog = (new TemplateLog())->where(['template_log_id' => '3'])->first();
$userTaskDes = array("#user_name#","#buyer_name#","#property_name#","#from_date#",'#end_date#',"#click_here#");
$userTaskRep = array($userName,$buyer,$propertyFullName,$inputs['start_date'],$inputs['end_date'],$routefunction);
$messages = $templateLog->message;
$newTaskDes = str_replace($userTaskDes,$userTaskRep,$messages);
$messageBody = $newTaskDes;
if($statusvalue==1){
$message['bookingId'] = $bookObj->id;
$message['approved_token'] = md5(time());
$message['email'] = $property_owner_details['email'];
$message['subject'] = "Property Approval";
$message['mobile_no'] = $property_owner_details['mobile_number'];
$message['is_send'] = "1";
$message['body'] = $messageBody;
$message['url'] = "/success";
$message['type'] = 1;
$sendObj = new MessageToBeSend($message);
$sendObj->save();
}
if($statusvalue == 0){
$this->sendConfrimedBookingEmail($inputs['property_id'],$inputs['start_date'], $inputs['end_date'],$inputs['ownerID']);
}
foreach($booking_dates as $values){
$book['date'] = $values;
$bookDatesObj = new BookingDates($book);
$bookDatesObj->save();
}
//$availabilityIds = (new PropertyAvailaibility())->getPropertyAvailabilityBetweenDates( $inputs['property_id'], $inputs['start_date'], $inputs['end_date'] );
$availabilityIds = (new PropertyAvailaibility())->getIsRequestedDates( $inputs['property_id'], $inputs['start_date'], $inputs['end_date'] );
(new PropertyAvailaibilityDate())->setIsRequested( $availabilityIds ); // set IsRequested = 1
if($approval_required==0){ // 0 => Automatically booked no approval of seller is required.
(new PropertyAvailaibilityDate())->dateBook( $availabilityIds ); // Set is_booked key to 1
}
return response()->json(['is_approved'=>$statusvalue,'success'=>true,'message'=>'Your Booking is done successfully'] );
} else {
return response()->json(['success'=>false,'message'=>'Something went wrong'] );
}
}
}
function sendConfrimedBookingEmail($propertyId,$startDate,$endDate,$ownerId){
$propertyName = (new PropertyFieldValue())->getPropertyDetail($propertyId);
$propertyFullName = '';
$routefunction = '<a href="'.route('pending-approval-booking-properties').'">Click here</a>';
foreach($propertyName as $property){
if($property['field_name'] == 'Name'){
$propertyFullName = $property['property_type_section_field_value'];
}
}
$property_owner_details = User::where('id', $ownerId)->first();
$buyerDetail = User::where('id', Auth::user()->id)->first();
$userName = $property_owner_details['first_name'].' '.$property_owner_details['Last_name'];
$buyer = $buyerDetail['first_name'].' '.$buyerDetail['last_name'];
$templateLog = (new TemplateLog())->where(['template_log_id' => '5'])->first();
$userTaskDes = array("#user_name#","#buyer_name#","#property_name#","#from_date#",'#end_date#');
$userTaskRep = array($userName,$buyer,$propertyFullName,$startDate,$endDate);
$messages = $templateLog->message;
$newTaskDes = str_replace($userTaskDes,$userTaskRep,$messages);
$messageBody = $newTaskDes;
$messageData = [
'type' => '1',
'subject' => 'Property Booked',
'body' => $messageBody,
'email' => $property_owner_details['email'],
'mobile_no' => $property_owner_details['mobile_number'],
'is_send' => "1",
'status' => '0',
'url' => "/success",
];
(new MessageToBeSend())->insert($messageData);
$templateLog = (new TemplateLog())->where(['template_log_id' => '6'])->first();
$userTaskDes = array("#user_name#","#property_name#","#from_date#",'#end_date#');
$userTaskRep = array($buyer,$propertyFullName,$startDate,$endDate);
$messages = $templateLog->message;
$newTaskDes = str_replace($userTaskDes,$userTaskRep,$messages);
$messageBody = $newTaskDes;
$messageData = [
'type' => '1',
'subject' => 'Booking Confirmation',
'body' => $messageBody,
'email' => $buyerDetail['email'],
'mobile_no' => $buyerDetail['mobile_number'],
'is_send' => "1",
'status' => '0',
'url' => "/success",
];
(new MessageToBeSend())->insert($messageData);
}
/*======================================================
Function for getting the Approval Status of Property
========================================================*/
public function getPropertyStatus($property_id){
return $propertyResult = (new Property())->getApprovedStatus($property_id);
}
/*==================================
Function for Approve the Booking
=====================================*/
public function approvedBooking($approved_token){
$MessageToBeSend = MessageToBeSend::where( array( 'approved_token' => $approved_token ) )->first();
if(Bookings::where('booking_id', $MessageToBeSend->bookingId)->update(array('is_approved' => 1)) ){
return redirect('/thanks')->with('message', 'Ï.');
} else {
return redirect('/thanks')->with('message', 'Something went wrong.');
}
}
/*==================================
Pending for comment
=====================================*/
public function thanks(){
return view('thanks');
}
/*===============================================
Function for Getting the Properties of seller
==================================================*/
public function sellerProperties(Request $request){
$inputs = $request->all();
$propertyId = $inputs['propertyId'];
$sellerId = $inputs['sellerId'];
$button = $inputs['button'];
$query = (new Property())->getPropertyWithPropertyIdAndSellerId($sellerId,$propertyId,$button);
if(count($query) == 0) {
$query = (new Property())->getFirstPropertyWithPropertyIdAndSellerId($sellerId,$propertyId,$button);
}
$allPropertiesData = $query->toArray();
$propertyIDS = array();
if(isset($allPropertiesData)){
$propertyIDS[] = $allPropertiesData["propertyIds"];
}
if(count($propertyIDS)){
$properties_data = (new Property())->getSellerPropertyRelatedData($propertyIDS);
}
//pr($properties_data,1);
if(isset($properties_data)){
$properties = prepareDataForSellerProperties($properties_data); // Defined in Helper
}
//pr($properties,1);
$array_key = key($properties);
$sellerPropertyData = view('Propertytype.seller-properties-at-guest')->with('properties',$properties[$array_key])->render();
if(!empty($properties)){
$ary = [
'success' => '100',
'data' => $sellerPropertyData
];
}else{
$ary = [
'success' => 50
];
}
return response()->json($ary);
//return response(json_encode($ary));
}
}
<file_sep>/app/MessageToBeSend.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use DB;
class MessageToBeSend extends Model
{
protected $table = 'message_to_be_send';
protected $fillable = ['approved_token','type','subject','body','email','url','mobile_no','is_send'];
}
<file_sep>/app/PropertyAvailaibilityDate.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PropertyAvailaibilityDate extends Model
{
//
public $timestamps = false;
protected $fillable = [ 'is_booked' ];
/*========================
Book Property Date
Param 1 : Property Id
==========================*/
public function dateBook( $ids ){
return $this
->whereIn( 'id', $ids )
->where( array( 'is_booked' => 0 ) )
->update( array( 'is_booked' => 1 ) );
}
/*======================================================
Set Is Requested Field = 1 When request For Booking
Param 1 : Primary keys of property_availaibility_dates
=======================================================*/
public function setIsRequested( $ids ){
return $this
->whereIn( 'id', $ids )
->where( array( 'is_requested' => 0 ) )
->update( array( 'is_requested' => 1 ) );
}
/*========================
Cancel booking Date
Param 1 : property_availaibility_dates Id
==========================*/
public function cancelDates( $ids ){
return $this
->whereIn( 'id', $ids )
->update( array( 'is_booked' => 0,'is_requested' => 0 ) );
}
}
<file_sep>/app/Property.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use DB;
class Property extends Model
{
protected $table = 'properties';
protected $fillable = [
'timezone_name','property_type_id', 'seller_id', 'lng', 'lat' , 'is_approved_checked', 'policy_types_id'
];
//public function test( $propertyTypesId, $startdate, $enddate, $location, $min_price, $max_price, $filters ){
/*=====================================================================================================
Search Property based on property id, Location, Start Date ,End Date, Max Price, Min Price, Filters
Param 1 : Array($searchData)
Join : properties_field_values, property_type_section_fields,
======================================================================================================*/
public function searchProperties( $searchData ){
return $this
->join('properties_field_values', 'properties_field_values.property_id', '=', 'properties.id')
->join('property_type_section_fields','property_type_section_fields.id','=', 'properties_field_values.property_type_section_field_id' )
->select('properties.id as propertyIds' ,'properties_field_values.property_type_section_field_value as price')
->where(array('property_type_section_fields.field_identifier' => 'basic_price'))
->whereExists(function ($query) use ($searchData) {
$query->select(DB::raw(1))
->from('property_availaibility')
->join('property_availaibility_dates', 'property_availaibility_dates.property_availaibility_id', '=', 'property_availaibility.id')
->where(function($query2) use ( $searchData ) {
if( (isset($searchData['startDate'])) && (isset( $searchData['endDate'] ))){
$query2->whereBetween('property_availaibility_dates.date', [$searchData['startDate'], $searchData['endDate'] ])
->Where('property_availaibility_dates.is_booked',0);
}elseif(isset($searchData['startDate'])){
$query2->Where('property_availaibility_dates.date','>=', $searchData['startDate'])
->Where('property_availaibility_dates.is_booked',0);
}elseif(isset($searchData['endDate'])){
$current_date = getServerUtcTime();
$query2->whereBetween('property_availaibility_dates.date', [$current_date, $searchData['endDate'] ])
->Where('property_availaibility_dates.is_booked',0);
}
})
->whereRaw('property_availaibility.property_id = properties.id');
})
->where(array('properties.property_type_id' => $searchData['propertyTypesId']))
->whereExists(function ($query) use ($searchData) {
$query->select(DB::raw(1))
->from('properties_field_values')
->join('property_type_section_fields', 'property_type_section_fields.id', '=', 'properties_field_values.property_type_section_field_id')
->where(function($query) use ($searchData) {
if( (isset($searchData['location']) && (!empty($searchData['location'])) )) {
//$array = explode(',', $searchData['location']);
/*echo "<pre>";
print_r($array);
die('here');*/
$query->where('field_identifier', '=', 'basic_location')->where('properties_field_values.property_type_section_field_value', 'LIKE', '%'.$searchData['location'].'%');
}
})
->where(function($query) use ($searchData) {
if( (isset($searchData['minPrice'])) && (isset($searchData['maxPrice'])) && ($searchData['maxPrice']>0) ) {
$query->where('field_identifier', '=', 'basic_price')->whereBetween('properties_field_values.property_type_section_field_value', [$searchData['minPrice'], $searchData['maxPrice']]);
}
})
->where(function($query) use ($searchData) {
if( isset($searchData['filters']) && count($searchData['filters'])) {
$query->whereIn('properties_field_values.id', $searchData['filters']);
}
})
->whereRaw('properties_field_values.property_id = properties.id');
});
}
/*===================================================
Get Property of Particular User based on User id
Param 1 : SellerId
=======================================================*/
public function getProperties($seller_id) {
return $this->select('properties.id as propertyIds', 'properties.created_at')
->where(array('properties.seller_id' => $seller_id));
}
/*===================================================
Get Property of Particular User based on User id
Param 1 : SellerId
=======================================================*/
public function getPropertyWithPropertyIdAndSellerId($seller_id,$propertyId,$button) {
return $this->select('properties.id as propertyIds', 'properties.created_at')
->when($button, function($q) use ($seller_id,$propertyId,$button){
if($button=='next') {
$q->where(array('properties.seller_id' => $seller_id))
->where('properties.id', '>', $propertyId);
}
if($button=='previous') {
return $q->where(array('properties.seller_id' => $seller_id))
->where('properties.id', '<', $propertyId);
}
})->first();
}
/*====================================================================================================
Get Property of Particular Property based on User id, This function is executed if no item found
Param 1 : SellerId
========================================================================================================*/
public function getFirstPropertyWithPropertyIdAndSellerId($seller_id,$propertyId,$button) {
return $this->select('properties.id as propertyIds', 'properties.created_at')
->when($button, function($q) use ($seller_id,$propertyId,$button){
if($button=='next') {
$q->where(array('properties.seller_id' => $seller_id))
->where('properties.id', '<', $propertyId);
}
if($button=='previous') {
return $q->where(array('properties.seller_id' => $seller_id))
->where('properties.id', '>', $propertyId);
}
})->first();
}
/*=============================================================================================
Get Property Data E.Q. Name, Location, Price, Property Description Based On Property ids
Param 1 : PropertiesIds (Array)
Join : properties_field_values, property_type_section_fields,
==============================================================================================*/
public function getSellerPropertyRelatedData( $PropertiesIds ){
return $this
->rightjoin('properties_field_values', 'properties_field_values.property_id','=', 'properties.id')
->rightjoin('property_type_section_fields', 'property_type_section_fields.id','=', 'properties_field_values.property_type_section_field_id')
//->join('bookings', 'bookings.property_id','=', 'properties.id')
->join('users', 'properties.seller_id', '=', 'users.id')
->where(function($q) use($PropertiesIds){
$q->whereIn('properties_field_values.property_id' , $PropertiesIds);
})
->select('properties.property_type_id','properties.property_type_id','property_type_section_fields.name','properties_field_values.property_type_section_field_value','property_type_section_fields.field_identifier','property_type_section_fields.id as property_type_section_field_id','properties.id','properties_field_values.id as property_filed_value_id','properties_field_values.created_at as created_at', 'users.first_name', 'users.last_name')
// ->select('properties.property_type_id','property_type_section_fields.name','properties_field_values.property_type_section_field_value','property_type_section_fields.field_identifier','property_type_section_fields.id as property_type_section_field_id','properties.id','properties_field_values.id as property_filed_value_id','properties_field_values.created_at as created_at', 'users.first_name', 'users.last_name', 'bookings.booking_id' )
->get()
->toArray();
}
/*public function testgetSellerPropertyRelatedData( $PropertiesIds ){
return $this
->rightjoin('properties_field_values', 'properties_field_values.property_id','=', 'properties.id')
->rightjoin('property_type_section_fields', 'property_type_section_fields.id','=', 'properties_field_values.property_type_section_field_id')
//->join('bookings', 'bookings.property_id','=', 'properties.id')
->join('users', 'properties.seller_id', '=', 'users.id')
->where(function($q) use($PropertiesIds){
$q->where('properties_field_values.property_id' , $PropertiesIds);
})
->select('properties.property_type_id','properties.property_type_id','property_type_section_fields.name','properties_field_values.property_type_section_field_value','property_type_section_fields.field_identifier','property_type_section_fields.id as property_type_section_field_id','properties.id','properties_field_values.id as property_filed_value_id','properties_field_values.created_at as created_at', 'users.first_name', 'users.last_name')
// ->select('properties.property_type_id','property_type_section_fields.name','properties_field_values.property_type_section_field_value','property_type_section_fields.field_identifier','property_type_section_fields.id as property_type_section_field_id','properties.id','properties_field_values.id as property_filed_value_id','properties_field_values.created_at as created_at', 'users.first_name', 'users.last_name', 'bookings.booking_id' )
->get()
->toArray();
}*/
/*=============================================================================================
Get Property Data E.Q. Name, Location, Price, Property Description Based On Property ids
Param 1 : PropertiesIds (Array)
Join : properties_field_values, property_type_section_fields,
==============================================================================================*/
public function getPropertyRelatedData( $PropertiesIds ){
$placeholders = implode(',',array_fill(0, count($PropertiesIds), '?'));
return $this
->rightjoin('properties_field_values', 'properties_field_values.property_id','=', 'properties.id')
->rightjoin('property_type_section_fields', 'property_type_section_fields.id','=', 'properties_field_values.property_type_section_field_id')
->join('users', 'properties.seller_id', '=', 'users.id')
->whereIn('properties_field_values.property_id' , $PropertiesIds)->orderByRaw("field(properties_field_values.property_id,{$placeholders})", $PropertiesIds)
->select('properties.seller_id','properties.property_type_id','property_type_section_fields.name','properties_field_values.property_type_section_field_value','property_type_section_fields.field_identifier','property_type_section_fields.id as property_type_section_field_id','properties.id','properties_field_values.id as property_filed_value_id', 'properties.created_at as created_at', 'users.first_name', 'users.last_name' )
->get()
->toArray();
}
/*===========================================================================================================
Get Property Data E.Q. Name, Location, Price, Property Description, Booking Dates Based On Property ids
Param 1 : PropertiesIds (Array), UserId
Join : properties_field_values, property_type_section_fields, bookings, booking_dates
=============================================================================================================*/
public function getPastBookingPropertyData( $bookingsIds, $userId ){
$current_date = getServerUtcTime();
return $this
->rightjoin('properties_field_values', 'properties_field_values.property_id','=', 'properties.id')
->rightjoin('property_type_section_fields', 'property_type_section_fields.id','=', 'properties_field_values.property_type_section_field_id')
->join('bookings', 'bookings.property_id','=', 'properties.id')
->join('users', 'bookings.property_owner_id','=', 'users.id')
->join('booking_dates', 'bookings.booking_id','=', 'booking_dates.booking_id')
->where(array('bookings.user_id' => $userId ))
->Where('booking_dates.date','<', $current_date)
->where(function($q) use($bookingsIds){
$q->whereIn('bookings.booking_id' , $bookingsIds);
$q->where('property_type_section_fields.field_identifier','!=', null);
})
->select('bookings.payment_status','bookings.property_owner_id','bookings.is_approved','users.email','users.mobile_number','users.id as buyerId','users.first_name','users.last_name','property_type_section_fields.name','properties_field_values.property_type_section_field_value','property_type_section_fields.field_identifier','property_type_section_fields.id as property_type_section_field_id','properties.id','properties_field_values.id as property_filed_value_id','properties_field_values.created_at as created_at', 'booking_dates.date as upcoming_date', 'booking_dates.booking_date_id', 'bookings.booking_id', 'bookings.total_amount' )
->get()
->toArray();
}
/*===========================================================================================================
Get Property Data E.Q. Name, Location, Price, Property Description, Booking Dates Based On Property ids
Param 1 : PropertiesIds (Array), UserId
Join : properties_field_values, property_type_section_fields, bookings, booking_dates
=============================================================================================================*/
public function getBookedPastBookingPropertyData( $bookingsIds, $userId ){
$current_date = getServerUtcTime();
return $this
->rightjoin('properties_field_values', 'properties_field_values.property_id','=', 'properties.id')
->rightjoin('property_type_section_fields', 'property_type_section_fields.id','=', 'properties_field_values.property_type_section_field_id')
->join('bookings', 'bookings.property_id','=', 'properties.id')
->join('booking_dates', 'bookings.booking_id','=', 'booking_dates.booking_id')
->join('users', 'bookings.user_id','=', 'users.id')
->where(array('bookings.property_owner_id' => $userId ))
->Where('booking_dates.date','<', $current_date)
->where(function($q) use($bookingsIds){
$q->whereIn('bookings.booking_id' , $bookingsIds);
$q->where('property_type_section_fields.field_identifier','!=', null);
})
->select('bookings.payment_status','bookings.property_owner_id','bookings.is_approved','users.email','users.mobile_number','users.id as buyerId','users.first_name','users.last_name','property_type_section_fields.name','properties_field_values.property_type_section_field_value','property_type_section_fields.field_identifier','property_type_section_fields.id as property_type_section_field_id','properties.id','properties_field_values.id as property_filed_value_id','properties_field_values.created_at as created_at', 'booking_dates.date as upcoming_date', 'booking_dates.booking_date_id', 'bookings.booking_id', 'bookings.total_amount' )
->get()
->toArray();
}
/*==========================================================================================================
Get Property Data E.Q. Name, Location, Price, Property Description, Booking Dates Based On Property ids
Param 1 : PropertiesIds (Array) , userId
Join : properties_field_values, property_type_section_fields, bookings, booking_dates
===========================================================================================================*/
public function getUpcomingBookingPropertyData( $bookingsIds, $userId ){
$current_date = getServerUtcTime();
return $this
->rightjoin('properties_field_values', 'properties_field_values.property_id','=', 'properties.id')
->rightjoin('property_type_section_fields', 'property_type_section_fields.id','=', 'properties_field_values.property_type_section_field_id')
->join('bookings', 'bookings.property_id','=', 'properties.id')
->join('booking_dates', 'bookings.booking_id','=', 'booking_dates.booking_id')
->join('users', 'bookings.property_owner_id','=', 'users.id')
->where(array('bookings.user_id' => $userId,'bookings.is_approved' => 1,'bookings.payment_status' => 1 ))
->Where('booking_dates.date','>=', $current_date)
->where(function($q) use($bookingsIds){
$q->whereIn('bookings.booking_id' , $bookingsIds);
$q->where('property_type_section_fields.field_identifier','!=', null);
})
->select('bookings.payment_status','bookings.property_owner_id','users.email','users.mobile_number','users.id as buyerId','users.first_name','users.last_name','property_type_section_fields.name','properties_field_values.property_type_section_field_value','property_type_section_fields.field_identifier','property_type_section_fields.id as property_type_section_field_id','properties.id','properties_field_values.id as property_filed_value_id','properties_field_values.created_at as created_at', 'booking_dates.date as upcoming_date', 'booking_dates.booking_date_id', 'bookings.booking_id', 'bookings.total_amount' ,'bookings.is_approved')
->get()
->toArray();
}
/*==========================================================================================================
Get Property Data E.Q. Name, Location, Price, Property Description, Booking Dates Based On Property ids
Param 1 : PropertiesIds (Array) , userId
Join : properties_field_values, property_type_section_fields, bookings, booking_dates
===========================================================================================================*/
public function getApproveBookingPropertyData( $bookingsIds, $userId ){
$current_date = getServerUtcTime();
return $this
->rightjoin('properties_field_values', 'properties_field_values.property_id','=', 'properties.id')
->rightjoin('property_type_section_fields', 'property_type_section_fields.id','=', 'properties_field_values.property_type_section_field_id')
->join('bookings', 'bookings.property_id','=', 'properties.id')
->join('booking_dates', 'bookings.booking_id','=', 'booking_dates.booking_id')
->join('users', 'bookings.property_owner_id','=', 'users.id')
->where(array('bookings.user_id' => $userId ,'bookings.is_approved' => 1,'bookings.through_approval' => 1,'bookings.payment_status' => 0))
->Where('booking_dates.date','>=', $current_date)
->where(function($q) use($bookingsIds){
$q->whereIn('bookings.booking_id' , $bookingsIds);
$q->where('property_type_section_fields.field_identifier','!=', null);
})
->select('bookings.payment_status','bookings.property_owner_id','users.email','users.mobile_number', 'users.id as buyerId','users.first_name','users.last_name', 'property_type_section_fields.name','properties_field_values.property_type_section_field_value','property_type_section_fields.field_identifier','property_type_section_fields.id as property_type_section_field_id','properties.id','properties_field_values.id as property_filed_value_id','properties_field_values.created_at as created_at', 'booking_dates.date as upcoming_date', 'booking_dates.booking_date_id', 'bookings.booking_id', 'bookings.total_amount' ,'bookings.is_approved')
->get()
->toArray();
}
/*==========================================================================================================
Get Property Data E.Q. Name, Location, Price, Property Description, Booking Dates Based On Property ids
Param 1 : PropertiesIds (Array) , userId
Join : properties_field_values, property_type_section_fields, bookings, booking_dates
===========================================================================================================*/
public function getBookedUpcomingBookingPropertyData( $bookingsIds, $userId ){
$current_date = getServerUtcTime();
return $this
->rightjoin('properties_field_values', 'properties_field_values.property_id','=', 'properties.id')
->rightjoin('property_type_section_fields', 'property_type_section_fields.id','=', 'properties_field_values.property_type_section_field_id')
->join('bookings', 'bookings.property_id','=', 'properties.id')
->join('booking_dates', 'bookings.booking_id','=', 'booking_dates.booking_id')
->join('users', 'bookings.user_id','=', 'users.id')
->where(array('bookings.property_owner_id' => $userId ,'bookings.is_approved' => 1,'bookings.payment_status' => 1 ))
->Where('booking_dates.date','>=', $current_date)
->where(function($q) use($bookingsIds){
$q->whereIn('bookings.booking_id' , $bookingsIds);
$q->where('property_type_section_fields.field_identifier','!=', null);
})
->select('bookings.payment_status','bookings.property_owner_id','users.email','users.mobile_number','users.id as buyerId','users.first_name','users.last_name','property_type_section_fields.name','properties_field_values.property_type_section_field_value','property_type_section_fields.field_identifier','property_type_section_fields.id as property_type_section_field_id','properties.id','properties_field_values.id as property_filed_value_id','properties_field_values.created_at as created_at', 'booking_dates.date as upcoming_date', 'booking_dates.booking_date_id', 'bookings.booking_id','bookings.is_approved', 'bookings.total_amount' )
->get()
->toArray();
}
/*==========================================================================================================
Get Property Data E.Q. Name, Location, Price, Property Description, Booking Dates Based On Property ids
Param 1 : PropertiesIds (Array) , userId
Join : properties_field_values, property_type_section_fields, bookings, booking_dates
===========================================================================================================*/
public function getBookedApproveBookingPropertyData( $bookingsIds, $userId ){
$current_date = getServerUtcTime();
return $this
->rightjoin('properties_field_values', 'properties_field_values.property_id','=', 'properties.id')
->rightjoin('property_type_section_fields', 'property_type_section_fields.id','=', 'properties_field_values.property_type_section_field_id')
->join('bookings', 'bookings.property_id','=', 'properties.id')
->join('users', 'bookings.user_id','=', 'users.id')
->join('booking_dates', 'bookings.booking_id','=', 'booking_dates.booking_id')
->where(array('bookings.property_owner_id' => $userId ,'bookings.is_approved' => 1,'bookings.through_approval' => 1,'bookings.payment_status' => 0))
->Where('booking_dates.date','>=', $current_date)
->where(function($q) use($bookingsIds){
$q->whereIn('bookings.booking_id' , $bookingsIds);
$q->where('property_type_section_fields.field_identifier','!=', null);
})
->select('bookings.payment_status','bookings.property_owner_id','users.email','users.mobile_number','users.id as buyerId','users.first_name','users.last_name','property_type_section_fields.name','properties_field_values.property_type_section_field_value','property_type_section_fields.field_identifier','property_type_section_fields.id as property_type_section_field_id','properties.id','properties_field_values.id as property_filed_value_id','properties_field_values.created_at as created_at', 'booking_dates.date as upcoming_date', 'booking_dates.booking_date_id', 'bookings.booking_id','bookings.is_approved', 'bookings.total_amount' )
->get()
->toArray();
}
public function getBookedPendingBookingPropertyData( $bookingsIds, $propertyOwnerId ){
$current_date = getServerUtcTime();
return $this
->rightjoin('properties_field_values', 'properties_field_values.property_id','=', 'properties.id')
->rightjoin('property_type_section_fields', 'property_type_section_fields.id','=', 'properties_field_values.property_type_section_field_id')
->join('bookings', 'bookings.property_id','=', 'properties.id')
->join('booking_dates', 'bookings.booking_id','=', 'booking_dates.booking_id')
->join('users', 'bookings.user_id','=', 'users.id')
->where(array('bookings.property_owner_id' => $propertyOwnerId ,'bookings.is_approved' => 0,'bookings.through_approval' => 1))
//->Where('booking_dates.date','>=', $current_date)
->where(function($q) use($bookingsIds){
$q->whereIn('bookings.booking_id' , $bookingsIds);
$q->where('property_type_section_fields.field_identifier','!=', null);
})
->select('bookings.payment_status','bookings.property_owner_id','users.email','users.mobile_number','users.id as buyerId','users.first_name','users.last_name','property_type_section_fields.name','properties_field_values.property_type_section_field_value','property_type_section_fields.field_identifier','property_type_section_fields.id as property_type_section_field_id','properties.id','properties_field_values.id as property_filed_value_id','properties_field_values.created_at as created_at', 'booking_dates.date as upcoming_date', 'booking_dates.booking_date_id', 'bookings.booking_id','bookings.is_approved', 'bookings.total_amount' )
->get()
->toArray();
}
public function getPendingBookingPropertyData( $bookingsIds, $userId ){
$current_date = getServerUtcTime();
return $this
->rightjoin('properties_field_values', 'properties_field_values.property_id','=', 'properties.id')
->rightjoin('property_type_section_fields', 'property_type_section_fields.id','=', 'properties_field_values.property_type_section_field_id')
->join('bookings', 'bookings.property_id','=', 'properties.id')
->join('booking_dates', 'bookings.booking_id','=', 'booking_dates.booking_id')
->join('users', 'bookings.property_owner_id','=', 'users.id')
->where(array('bookings.user_id' => $userId ,'bookings.is_approved' => 0,'bookings.through_approval' => 1))
//->Where('booking_dates.date','>=', $current_date)
->where(function($q) use($bookingsIds){
$q->whereIn('bookings.booking_id' , $bookingsIds);
$q->where('property_type_section_fields.field_identifier','!=', null);
})
->select('bookings.payment_status','bookings.property_owner_id','users.email','users.mobile_number','users.id as buyerId','users.first_name','users.last_name', 'property_type_section_fields.name','properties_field_values.property_type_section_field_value','property_type_section_fields.field_identifier','property_type_section_fields.id as property_type_section_field_id','properties.id','properties_field_values.id as property_filed_value_id','properties_field_values.created_at as created_at', 'booking_dates.date as upcoming_date', 'booking_dates.booking_date_id', 'bookings.booking_id','bookings.is_approved', 'bookings.total_amount' )
->get()
->toArray();
}
public function getBookedRejectedBookingPropertyData( $bookingsIds, $userId ){
//$current_date = getServerUtcTime();
return $this
->rightjoin('properties_field_values', 'properties_field_values.property_id','=', 'properties.id')
->rightjoin('property_type_section_fields', 'property_type_section_fields.id','=', 'properties_field_values.property_type_section_field_id')
->join('bookings', 'bookings.property_id','=', 'properties.id')
->join('booking_dates', 'bookings.booking_id','=', 'booking_dates.booking_id')
->join('users', 'bookings.user_id','=', 'users.id')
->where(array('bookings.property_owner_id' => $userId ,'bookings.is_approved' => 2,'bookings.through_approval' => 1))
//->Where('booking_dates.date','>=', $current_date)
->where(function($q) use($bookingsIds){
$q->whereIn('bookings.booking_id' , $bookingsIds);
$q->where('property_type_section_fields.field_identifier','!=', null);
})
->select('bookings.payment_status','bookings.property_owner_id','users.email','users.mobile_number','users.id as buyerId','users.first_name','users.last_name','property_type_section_fields.name','properties_field_values.property_type_section_field_value','property_type_section_fields.field_identifier','property_type_section_fields.id as property_type_section_field_id','properties.id','properties_field_values.id as property_filed_value_id','properties_field_values.created_at as created_at', 'booking_dates.date as upcoming_date', 'booking_dates.booking_date_id', 'bookings.booking_id','bookings.is_approved', 'bookings.total_amount' )
->get()
->toArray();
}
public function getRejectedBookingPropertyData( $bookingsIds, $userId ){
//$current_date = getServerUtcTime();
return $this
->rightjoin('properties_field_values', 'properties_field_values.property_id','=', 'properties.id')
->rightjoin('property_type_section_fields', 'property_type_section_fields.id','=', 'properties_field_values.property_type_section_field_id')
->join('bookings', 'bookings.property_id','=', 'properties.id')
->join('booking_dates', 'bookings.booking_id','=', 'booking_dates.booking_id')
->join('users', 'bookings.property_owner_id','=', 'users.id')
->where(array('bookings.user_id' => $userId ,'bookings.is_approved' => 2,'bookings.through_approval' => 1))
//->Where('booking_dates.date','>=', $current_date)
->where(function($q) use($bookingsIds){
$q->whereIn('bookings.booking_id' , $bookingsIds);
$q->where('property_type_section_fields.field_identifier','!=', null);
})
->select('bookings.payment_status','bookings.property_owner_id','users.email','users.mobile_number', 'users.id as buyerId','users.first_name','users.last_name', 'property_type_section_fields.name','properties_field_values.property_type_section_field_value','property_type_section_fields.field_identifier','property_type_section_fields.id as property_type_section_field_id','properties.id','properties_field_values.id as property_filed_value_id','properties_field_values.created_at as created_at', 'booking_dates.date as upcoming_date', 'booking_dates.booking_date_id', 'bookings.booking_id','bookings.is_approved', 'bookings.total_amount' )
->get()
->toArray();
}
public function getOwnProperty( $propertyId, $userId ){
return $this
->where(array('properties.id'=> $propertyId, 'properties.seller_id' => $userId ))
->first();
}
/* public function getByDistance($lat, $lng, $distance){
$results = DB::select(DB::raw('SELECT id,lat,lng, ( 6371 * acos( cos( radians(' . $lat . ') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(' . $lng . ') ) + sin( radians(' . $lat .') ) * sin( radians(lat) ) ) ) AS distance FROM properties HAVING distance <= ' . $distance . ' ORDER BY distance') );
//->select(\DB::raw("((ACOS( SIN( " . $latitude . " PI( ) /180 ) SIN( latitude * PI( ) /180 ) + COS( " . $latitude . " PI( ) /180 ) COS( latitude PI( ) /180 ) COS( ( " . $longitude . " - longitude ) * PI( ) /180 )) *180 / PI( )) 60 1.1515 * 1.609344) AS distance"),'pharmacy_detail_id', 'pocket_clinic_users.my_channel');
return $results;
}*/
/*public function getByDistance($lat, $lng, $distance){
return $this
->select(\DB::raw("( 6371 * acos( cos( radians(' . $lat . ') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(' . $lng . ') ) + sin( radians(' . $lat .') ) * sin( radians(lat) ) ) ) AS distance"),'properties.id', 'lat','lng' )
//->having('distance', '<=', $distance)
->get()
->toArray();
}*/
public function getByDistance($lat, $lng, $distance){
return $this
->select(\DB::raw("( 6371 * acos( cos( radians(" . $lat . ") ) * cos( radians(lat) ) *
cos( radians(lng) - radians(" . $lng . ") ) + sin( radians(" . $lat . ") ) *
sin( radians(lat) ) ) ) AS distance"))
->when($distance, function($query) use ($distance){
return $query->having('distance', '<=', $distance);
})
->get()
->toArray();
}
/******************** Get property approve status *******************/
public function getApprovedStatus( $propertyId ){
return $this
->where(array('id' => $propertyId))
->select('*')
->first();
}
public function getSellerId($propertyId){
return $this
->where(array('id' => $propertyId))
->value('seller_id');
}
}
<file_sep>/app/Helpers/helper.php
<?php
use App\Property;
use App\Bookings;
function pr($data, $exit = false){
echo "<pre>";
print_r($data);
if ($exit) {
die;
}
}
function createThumb($name, $filename, $new_w, $new_h){
$found = 0;
$system = explode('.', $name);
$echeck = strtolower(end($system));
if (preg_match('/pdf|txt/', $echeck)) {
$found = 0;
}
if (preg_match('/jpg|jpeg/', $echeck)) {
$src_img = imagecreatefromjpeg($name);
$found = 1;
}
if (preg_match('/png/', $echeck)) {
$src_img = imagecreatefrompng($name);
$found = 1;
}
if (preg_match('/gif/', $echeck)) {
$src_img = imagecreatefromgif($name);
$found = 1;
}
if ($found) {
$old_x = imagesx($src_img);
$old_y = imagesy($src_img);
$ar = $old_x / $old_y;
if ($old_x > 2000) {
if ($new_w == $new_h) {
$thumb_w = $new_w;
$thumb_h = $new_h;
} else {
$thumb_w = $new_w;
$thumb_h = (int)(($old_y / $old_x) * $new_w);
}
} else {
$thumb_w = $old_x;
$thumb_h = $old_y;
}
$dst_img = imagecreatetruecolor($thumb_w, $thumb_h);
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y);
if (preg_match("/png/", $echeck)) {
imagepng($dst_img, $filename);
} else if (preg_match('/jpg|jpeg/', $echeck)) {
imagejpeg($dst_img, $filename, 100);
} else if (preg_match("/gif/", $echeck)) {
imagegif($dst_img, $filename);
}
imagedestroy($dst_img);
imagedestroy($src_img);
}
}
function isSeller(){
return \Auth::user() && \Auth::user()->role == 2 ? true : false;
}
/*=======================================================
Prepare Date When Displaying the details For Property
Param 1 : $propertyDetails (Array)
Used In : SellerController and PropertyController
=========================================================*/
// function prepareDataForPropertyDetail( $propertyDetails ){
// $section_array = array();
// foreach($propertyDetails as $propertyDetail){
// $section_array[$propertyDetail['id']]['section_name']=$propertyDetail['section'];
// $section_array[$propertyDetail['id']]['fields'][]= [
// 'owner_id' => $propertyDetail['seller_id'],
// 'field_name' => $propertyDetail['field_name'],
// 'field_value' => $propertyDetail['property_type_section_field_value'],
// 'field_identifier' => $propertyDetail['field_identifier'],
// 'is_option' => $propertyDetail['is_option'],
// 'input_field_type_id' => $propertyDetail['input_field_type_id'],
// 'is_approved_checked' => $propertyDetail['is_approved_checked']
// ];
// }
// return $section_array;
// }
function prepareDataForPropertyDetail( $propertyDetails ){
$section_array = array();
foreach($propertyDetails as $propertyDetail){
if(!empty($propertyDetail['property_type_section_field_value'])){
$section_array[$propertyDetail['id']]['section_name']=$propertyDetail['section'];
$section_array[$propertyDetail['id']]['fields'][]= [
'owner_id' => $propertyDetail['seller_id'],
'field_name' => $propertyDetail['field_name'],
'field_value' => $propertyDetail['property_type_section_field_value'],
'field_identifier' => $propertyDetail['field_identifier'],
'is_option' => $propertyDetail['is_option'],
'input_field_type_id' => $propertyDetail['input_field_type_id'],
'is_approved_checked' => $propertyDetail['is_approved_checked']
];
}
}
return $section_array;
}
/*==================================================
Prepare Date When Searching the Property By Id
Param 1 : $properties_data (Array)
Used In : SellerController and PropertyController
=====================================================*/
function prepareDataForProperties( $properties_data ){
$propertyArr = [];
foreach($properties_data as $key => $property){
$propertyArr[$property['id']]['property_type_id'] = $property['property_type_id'];
$propertyArr[$property['id']]['property_id'] = $property['id'];
if($property['field_identifier'] == \Config::get('constants.INPUT_TYPE_FIELD_IDENTIFIER.1')){
$propertyArr[$property['id']]['basic_name'] = $property['property_type_section_field_value'];
}
if($property['field_identifier'] == \Config::get('constants.INPUT_TYPE_FIELD_IDENTIFIER.2')){
$propertyArr[$property['id']]['basic_location'] = $property['property_type_section_field_value'];
}
if($property['field_identifier'] == \Config::get('constants.INPUT_TYPE_FIELD_IDENTIFIER.3')){
$propertyArr[$property['id']]['basic_feature_image'] = $property['property_type_section_field_value'];
}
if($property['field_identifier'] == \Config::get('constants.INPUT_TYPE_FIELD_IDENTIFIER.4')){
$propertyArr[$property['id']]['basic_price'] = $property['property_type_section_field_value'];
}
if($property['field_identifier'] == \Config::get('constants.INPUT_TYPE_FIELD_IDENTIFIER.5')){
$propertyArr[$property['id']]['basic_description'] = $property['property_type_section_field_value'];
}
if($property['created_at']){
$propertyArr[$property['id']]['created_at'] = $property['created_at'];
}
if($property['first_name']){
$propertyArr[$property['id']]['first_name'] = $property['first_name'];
}
if($property['last_name']){
$propertyArr[$property['id']]['last_name'] = $property['last_name'];
}
if($property['seller_id']){
$propertyArr[$property['id']]['seller_id'] = $property['seller_id'];
}
}
return $propertyArr;
}
/*==================================================
Prepare Date When Searching the Property By Id
Param 1 : $properties_data (Array)
Used In : SellerController and PropertyController
=====================================================*/
function prepareDataForSellerProperties( $properties_data ){
$propertyArr = [];
foreach($properties_data as $key => $property){
$propertyArr[$property['id']]['property_type_id'] = $property['property_type_id'];
$propertyArr[$property['id']]['property_id'] = $property['id'];
if($property['field_identifier'] == \Config::get('constants.INPUT_TYPE_FIELD_IDENTIFIER.1')){
$propertyArr[$property['id']]['basic_name'] = $property['property_type_section_field_value'];
}
if($property['field_identifier'] == \Config::get('constants.INPUT_TYPE_FIELD_IDENTIFIER.2')){
$propertyArr[$property['id']]['basic_location'] = $property['property_type_section_field_value'];
}
if($property['field_identifier'] == \Config::get('constants.INPUT_TYPE_FIELD_IDENTIFIER.3')){
$propertyArr[$property['id']]['basic_feature_image'] = $property['property_type_section_field_value'];
}
if($property['field_identifier'] == \Config::get('constants.INPUT_TYPE_FIELD_IDENTIFIER.4')){
$propertyArr[$property['id']]['basic_price'] = $property['property_type_section_field_value'];
}
if($property['field_identifier'] == \Config::get('constants.INPUT_TYPE_FIELD_IDENTIFIER.5')){
$propertyArr[$property['id']]['basic_description'] = $property['property_type_section_field_value'];
}
if($property['created_at']){
$propertyArr[$property['id']]['created_at'] = $property['created_at'];
}
if($property['first_name']){
$propertyArr[$property['id']]['first_name'] = $property['first_name'];
}
if($property['last_name']){
$propertyArr[$property['id']]['last_name'] = $property['last_name'];
}
/*if($property['booking_id']){
$propertyArr[$property['id']]['booking_id'] = $property['booking_id'];
}*/
}
return $propertyArr;
}
/*====================================================
Prepare Date When Searching the Property By Id
Param 1 : $properties_data (Array)
Used In : SellerController and PropertyController
=======================================================*/
function prepareDataForUpComingPastProperties( $properties_data ){
$propertyArr = [];
foreach($properties_data as $key => $property){
$propertyArr[$property['booking_id']]['property_id'] = $property['id'];
if($property['field_identifier'] == \Config::get('constants.INPUT_TYPE_FIELD_IDENTIFIER.1')){
$propertyArr[$property['booking_id']]['basic_name'] = $property['property_type_section_field_value'];
}
if($property['field_identifier'] == \Config::get('constants.INPUT_TYPE_FIELD_IDENTIFIER.2')){
$propertyArr[$property['booking_id']]['basic_location'] = $property['property_type_section_field_value'];
}
if($property['field_identifier'] == \Config::get('constants.INPUT_TYPE_FIELD_IDENTIFIER.3')){
$propertyArr[$property['booking_id']]['basic_feature_image'] = $property['property_type_section_field_value'];
}
if($property['field_identifier'] == \Config::get('constants.INPUT_TYPE_FIELD_IDENTIFIER.4')){
$propertyArr[$property['booking_id']]['basic_price'] = $property['property_type_section_field_value'];
}
if($property['field_identifier'] == \Config::get('constants.INPUT_TYPE_FIELD_IDENTIFIER.5')){
$propertyArr[$property['booking_id']]['basic_description'] = $property['property_type_section_field_value'];
}
if($property['created_at']){
$propertyArr[$property['booking_id']]['created_at'] = $property['created_at'];
}
if($property['upcoming_date']){
$propertyArr[$property['booking_id']]['upcoming_date'][$property['booking_date_id']] = $property['upcoming_date'];
}
if($property['booking_id']){
$propertyArr[$property['booking_id']]['booking_id'] = $property['booking_id'];
}
if($property['total_amount']){
$propertyArr[$property['booking_id']]['total_amount'] = $property['total_amount'];
}
if($property['email']){
$propertyArr[$property['booking_id']]['email'] = $property['email'];
}
if($property['mobile_number']){
$propertyArr[$property['booking_id']]['mobile_number'] = $property['mobile_number'];
}
if($property['first_name']){
$propertyArr[$property['booking_id']]['first_name'] = $property['first_name'];
}
if($property['last_name']){
$propertyArr[$property['booking_id']]['last_name'] = $property['last_name'];
}
if($property['buyerId']){
$propertyArr[$property['booking_id']]['buyerId'] = $property['buyerId'];
}
if($property['is_approved']){
$propertyArr[$property['booking_id']]['is_approved'] = $property['is_approved'];
}
if($property['property_owner_id']){
$propertyArr[$property['booking_id']]['property_owner_id'] = $property['property_owner_id'];
}
if($property['payment_status']){
$propertyArr[$property['booking_id']]['payment_status'] = $property['payment_status'];
}
}
return $propertyArr;
}
/*========================================
check value match with associative array
Param 1 : Array
Param 2 : key
Param 3 : value
=========================================*/
function is_in_array($array, $key, $key_value){
$within_array = 'no';
foreach( $array as $k=>$v ){
if( is_array($v) ){
$within_array = is_in_array($v, $key, $key_value);
if( $within_array == 'yes' ){
break;
}
} else {
if( $v == $key_value && $k == $key ){
$within_array = 'yes';
break;
}
}
}
return $within_array;
}
/*========================================
Convert date format to as 08 Nov 2017
Param 1 : Date
=========================================*/
function dateFormat($date){
return date('d M Y', strtotime($date));
}
function getUtcTime($timezone){
$carbon = new Carbon();
$carbon->setTimezone($timezone);
$currentTime= $carbon; //output is : DateTime | TimeZone
$utcTime= $carbon->now(); // output is : DateTime | UTC
return $datesArray = array('currentTime' =>$currentTime , 'utcTime' =>$utcTime);
}
/*======================
GET SERVER UTC TIME
========================*/
function getServerUtcTime(){
$carbon = new Carbon();
return $utcTime= $carbon->now();
}
/*============================================================
GET DATE DIFF BETWEEN TWO DATES IN MINUTE HOURS AND DAYS
=============================================================*/
function dateDiff($start, $end) {
$start_ts = strtotime($start);
$end_ts = strtotime($end);
$diff = $end_ts - $start_ts;
$hourDiff = round((strtotime($end) - strtotime($start))/3600, 1);
$daysDiff = round($diff / 86400);
$interval = abs($diff);
$minutes = round($interval / 60);
return $datesDiff = array('minutesDiff' =>$minutes,'hourDiff' =>$hourDiff , 'daysDiff' =>$daysDiff);
}
/*================================
Convert local time to UTC Time
==================================*/
function convertIntoUTC($localTime, $dateTimeType, $timeZone) {
$dateFormat = 'Y-m-d';
$timeFormat = 'H:i:s';
$dateTimeTypeFormat = $dateFormat . ' ' . $timeFormat;
$date = new \DateTime($localTime.' '.$dateTimeType, new DateTimeZone($timeZone));
$date->setTimezone(new DateTimeZone('UTC'));
return $date->format($dateTimeTypeFormat);
}
/*================================
Convert UTC time to Local Time
Param : Array of dates
==================================*/
function convertUtcToLocal($available_dates , $timeZone) {
$localDates =array();
foreach($available_dates as $utc){
$dt = new DateTime($utc);
$tz = new DateTimeZone($timeZone); // or whatever zone you're after
$dt->setTimezone($tz);
$localDates[]=$dt->format('Y-m-d H:i:s');
}
return $localDates;
}
/*================================
Convert local time to UTC Time
Param : Array of dates
==================================*/
function convertLocalToUTC($bookDates, $time, $timeZone) {
$utcDates = array();
foreach($bookDates as $Dates){
$dateFormat = 'Y-m-d';
$timeFormat = 'H:i:s';
$dateTimeTypeFormat = $dateFormat . ' ' . $timeFormat;
$date = new \DateTime($Dates.' '.$time, new DateTimeZone($timeZone));
$date->setTimezone(new DateTimeZone('UTC'));
$utcDates[] = $date->format($dateTimeTypeFormat);
}
return $utcDates;
}
function getSingleLable ($section_array){
$arrayTemp = array();
foreach($section_array as $sec=>$section_arr){
foreach ($section_arr['fields'] as $key => $val) {
if($val['is_option']==1){
$arrayTemp[$val['field_name']]['label_name'] = $val['field_name'];
$arrayTemp[$val['field_name']]['is_option'] = $val['is_option'];
$arrayTemp[$val['field_name']]['values'][] = $val['field_value'];
$arrayTemp[$val['field_name']]['sectionId'] = $sec;
$arrayTemp[$val['field_name']]['typeId'] = $val['input_field_type_id'];
}
}
}
return $arrayTemp;
}
function listCounting ($seller_id,$type){
if($type=='myProperty'){
$query = (new Property())->getProperties($seller_id);
$allPropertiesData = $query->orderBy('properties.id', "ASC")->get()->toArray();
$propertyIDS = array();
if(isset($allPropertiesData)){
foreach($allPropertiesData as $value){
$propertyIDS[] = $value["propertyIds"];
}
}
if(count($propertyIDS)){
$properties_data = (new Property())->getSellerPropertyRelatedData($propertyIDS);
}
if(isset($properties_data)){
$propertyArr = prepareDataForSellerProperties($properties_data); // Defined in Helper
return count($propertyArr);
}
}
elseif($type=='bookedUpcomingProperties'){
$propertyOwnerId=$seller_id;
$bookingsIds=getBookingIds($propertyOwnerId,'bookedUpcomingProperties');
$properties_data = (new Property())->getBookedUpcomingBookingPropertyData( $bookingsIds, $propertyOwnerId );
if(isset($properties_data)){
$propertyArr = prepareDataForUpComingPastProperties($properties_data); // Defined in Helper
return count($propertyArr);
}
}
elseif($type=='bookedPendingBookingProperties'){
$propertyOwnerId=$seller_id;
$bookingsIds=getBookingIds($propertyOwnerId,'bookedPendingBookingProperties');
$properties_data = (new Property())->getBookedPendingBookingPropertyData( $bookingsIds, $propertyOwnerId );
if(isset($properties_data)){
$propertyArr = prepareDataForUpComingPastProperties($properties_data); // Defined in Helper
return count($propertyArr);
}
}
elseif($type=='bookedApproveProperties'){
$propertyOwnerId=$seller_id;
$bookingsIds=getBookingIds($propertyOwnerId,'bookedApproveProperties');
$properties_data = (new Property())->getBookedApproveBookingPropertyData( $bookingsIds, $propertyOwnerId );
if(isset($properties_data)){
$propertyArr = prepareDataForUpComingPastProperties($properties_data); // Defined in Helper
return count($propertyArr);
}
}
elseif($type=='bookedRejectedBookingProperties'){
$propertyOwnerId=$seller_id;
$bookingsIds=getBookingIds($propertyOwnerId,'bookedRejectedBookingProperties');
$properties_data = (new Property())->getBookedRejectedBookingPropertyData( $bookingsIds, $propertyOwnerId );
if(isset($properties_data)){
$propertyArr = prepareDataForUpComingPastProperties($properties_data); // Defined in Helper
return count($propertyArr);
}
}
elseif($type=='bookedPastBookingProperties'){
$propertyOwnerId=$seller_id;
$bookingsIds=getBookingIds($propertyOwnerId,'bookedPastBookingProperties');
$properties_data = (new Property())->getBookedPastBookingPropertyData( $bookingsIds, $propertyOwnerId );
if(isset($properties_data)){
$propertyArr = prepareDataForUpComingPastProperties($properties_data); // Defined in Helper
return count($propertyArr);
}
}
elseif($type=='upcomingProperties'){
$propertyOwnerId=$seller_id;
$bookingsIds=getBookingIds($propertyOwnerId,'upcomingProperties');
$properties_data = (new Property())->getUpcomingBookingPropertyData( $bookingsIds, $propertyOwnerId );
if(isset($properties_data)){
$propertyArr = prepareDataForUpComingPastProperties($properties_data); // Defined in Helper
return count($propertyArr);
}
}
elseif($type=='pendingProperties'){
$propertyOwnerId=$seller_id;
$bookingsIds=getBookingIds($propertyOwnerId,'pendingProperties');
$properties_data = (new Property())->getPendingBookingPropertyData( $bookingsIds, $propertyOwnerId );
if(isset($properties_data)){
$propertyArr = prepareDataForUpComingPastProperties($properties_data); // Defined in Helper
return count($propertyArr);
}
}
elseif($type=='approveProperties'){
$propertyOwnerId=$seller_id;
$bookingsIds=getBookingIds($propertyOwnerId,'approveProperties');
$properties_data = (new Property())->getApproveBookingPropertyData( $bookingsIds, $propertyOwnerId );
if(isset($properties_data)){
$propertyArr = prepareDataForUpComingPastProperties($properties_data); // Defined in Helper
return count($propertyArr);
}
}
elseif($type=='rejectedBookingProperties'){
$propertyOwnerId=$seller_id;
$bookingsIds=getBookingIds($propertyOwnerId,'rejectedBookingProperties');
$properties_data = (new Property())->getRejectedBookingPropertyData( $bookingsIds, $propertyOwnerId );
if(isset($properties_data)){
$propertyArr = prepareDataForUpComingPastProperties($properties_data); // Defined in Helper
return count($propertyArr);
}
}
elseif($type=='pastBookingProperties'){
$propertyOwnerId=$seller_id;
$bookingsIds=getBookingIds($propertyOwnerId,'pastBookingProperties');
$properties_data = (new Property())->getPastBookingPropertyData( $bookingsIds, $propertyOwnerId );
if(isset($properties_data)){
$propertyArr = prepareDataForUpComingPastProperties($properties_data); // Defined in Helper
return count($propertyArr);
}
}
}
function getBookingIds($propertyOwnerId,$type){
$commentType = 2;
if($type=='bookedUpcomingProperties'){
$query = (new Bookings())->getBookedUpcomingProperties( $propertyOwnerId );
}
elseif($type=='bookedPendingBookingProperties'){
$query = (new Bookings())->getBookedPendingProperties( $propertyOwnerId );
}
elseif($type=='bookedApproveProperties'){
$query = (new Bookings())->getBookedApproveProperties( $propertyOwnerId );
}
elseif($type=='bookedRejectedBookingProperties'){
$query = (new Bookings())->getBookedRejectedProperties( $propertyOwnerId );
}
elseif($type=='bookedPastBookingProperties'){
$query = (new Bookings())->getBookedPastBookingProperties( $propertyOwnerId );
}
elseif($type=='upcomingProperties'){
$query = (new Bookings())->getUpcomingProperties( $propertyOwnerId );
}
elseif($type=='pendingProperties'){
$query = (new Bookings())->getPendingProperties( $propertyOwnerId );
}
elseif($type=='approveProperties'){
$query = (new Bookings())->getApproveProperties( $propertyOwnerId );
}
elseif($type=='rejectedBookingProperties'){
$query = (new Bookings())->getRejectedProperties( $propertyOwnerId );
}
elseif($type=='pastBookingProperties'){
$query = (new Bookings())->getPastBookingProperties( $propertyOwnerId );
}
$allPropertiesData = $query->orderBy('bookings.property_id', "DESC")->get()->toArray();
$PropertiesIds = array();
$bookingsIds = array();
if(isset($allPropertiesData)){
foreach($allPropertiesData as $value){
$PropertiesIds[] = $value["property_id"];
$bookingsIds[] = $value["booking_id"];
}
}
return $bookingsIds;
}
<file_sep>/app/Http/Controllers/Seller/SellerProperty.php
<?php
namespace App\Http\Controllers\Seller;
use App\Http\Requests\Seller\PropertiesFieldValues;
use App\PropertyType;
use App\TemplateLog;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Foundation\Testing\HttpException;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Property;
use App\PropertyTypeSectionFieldOption;
use App\PropertyFieldValue;
use App\PropertyTypeSection;
use App\PropertyTypeSectionField;
use App\PropertyAvailaibility;
use App\PropertyAvailaibilityDate;
use App\BookingDates;
use App\Bookings;
use App\PropertyReviews;
use App\MessageToBeSend;
use App\CancellationPolicyType;
use App\ProertiesPolicyUpdation;
use App\User;
use Carbon\Carbon;
use DB;
use Auth;
use Request as AjaxRequest;
use Illuminate\Validation\ValidationException;
use Mockery\CountValidator\Exception;
use Session;
use Illuminate\Support\MessageBag;
use \Validator;
//use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Foundation\Http\FormRequest;
use Config;
class SellerProperty extends Controller
{
/*==========================
Load After Seller Login
=============================*/
private $attribute = [];
private $messages = [];
private $rule = [];
private $validator1= '';
public function index(Request $request){
$seller_id=Auth::user()->id;
$query = (new Property())->getProperties($seller_id);
$allPropertiesData = $query->orderBy('properties.id', "ASC")->paginate(4);
$propertyIDS = array();
if(isset($allPropertiesData)){
foreach($allPropertiesData as $value){
$propertyIDS[] = $value["propertyIds"];
}
}
if(count($propertyIDS)){
$properties_data = (new Property())->getSellerPropertyRelatedData($propertyIDS);
}
if(isset($properties_data)){
$propertyArr = prepareDataForSellerProperties($properties_data); // Defined in Helper
}
$active = 'myProperty';
return view('seller.my_properties',compact('propertyArr', 'allPropertiesData', 'active' ));
}
/*================================
Load View For Property Submit
==================================*/
public function propertyInformation(Request $request){
$propertyTypesId = $request->input('property_type_id');
$propertyTypes = (new PropertyType())
->where(['deleted_at' => NULL])
->get(['name','id'])->toArray();
$policyTypes = (new CancellationPolicyType())
->get(['policy_name','id'])->toArray();
$propertyTypesSection = (new PropertyTypeSection())
->leftjoin('property_type_section_fields', 'property_type_section_fields.property_type_section_id','=', 'property_type_sections.id')
->where('property_type_sections.property_type_id' , $request->input('property_type_id'))
->select(\DB::raw('group_concat(property_type_section_fields.id) as property_type_section_fields_id'), 'property_type_sections.name', 'property_type_sections.id')
->groupBy('property_type_sections.id')
->orderBy('property_type_sections.order_id',"ASC")
->get()->toArray();
$propertyTypesSectionFieldId = explode(',', implode(',', array_filter(array_column($propertyTypesSection, 'property_type_section_fields_id'))));
$inputsFields = (new PropertyTypeSectionField())
->with(['propertyTypeSectionFieldValue' => function ($query) {
$query->select('display_value', 'property_type_section_field_id','id');
}])
->join('input_field_types', 'input_field_types.id','=', 'property_type_section_fields.input_field_type_id')
->whereIn('property_type_section_fields.id' , $propertyTypesSectionFieldId)
->select('property_type_section_fields.name','property_type_section_fields.validations','property_type_section_fields.field_identifier','property_type_section_fields.property_type_section_id','property_type_section_fields.id','input_field_types.field_name')
->orderBy('property_type_section_fields.order_id',"ASC")
->get()->toArray();
$propertyTypeSectionData = [];
foreach($propertyTypesSection as $ind => $propertyTypeFieldName){
foreach($inputsFields as $index => $inputsField) {
if ($inputsField['property_type_section_id'] == $propertyTypeFieldName['id']) {
$propertyTypeSectionData[$inputsField['property_type_section_id']]['section_name'] = $propertyTypeFieldName['name'];
$propertyTypeSectionData[$inputsField['property_type_section_id']]['section_id'] = $inputsField['property_type_section_id'];
$propertyTypeSectionData[$inputsField['property_type_section_id']]['fields'][$inputsField['id']]['type'] = $inputsField['field_name'];
$propertyTypeSectionData[$inputsField['property_type_section_id']]['fields'][$inputsField['id']]['id'] = $inputsField['id'];
$propertyTypeSectionData[$inputsField['property_type_section_id']]['fields'][$inputsField['id']]['name'] = $inputsField['name'];
$propertyTypeSectionData[$inputsField['property_type_section_id']]['fields'][$inputsField['id']]['validations'] = $inputsField['validations'];
$propertyTypeSectionData[$inputsField['property_type_section_id']]['fields'][$inputsField['id']]['field_identifier'] = $inputsField['field_identifier'];
$propertyTypeSectionData[$inputsField['property_type_section_id']]['fields'][$inputsField['id']]['options'] = $inputsField['property_type_section_field_value'];
}
}
}
//return view('Propertytype.property_information',compact('propertyTypes','propertyTypeSectionData','propertyTypesId'));
return view('seller/property.property_information',compact('policyTypes','propertyTypes','propertyTypeSectionData','propertyTypesId'));
}
function change_key( $array, $old_key, $new_key ) {
if( ! array_key_exists( $old_key, $array ) )
return $array;
$keys = array_keys( $array );
$keys[ array_search( $old_key, $keys ) ] = $new_key;
return array_combine( $keys, $array );
}
/*==============================
Store Property Field Values
================================*/
public function storePropertyTypeData(PropertiesFieldValues $request){
DB::beginTransaction();
try{
$inputsValues = $request->all();
$savePropertyFieldValue = [];
$propertyTypesId = $inputsValues['property_types_id'];
$inputs = [];
$i=0;
foreach($inputsValues as $key => $newInput){
if($i >= 2) {
$newKey = substr($key, 0, strpos($key, "_"));
if(!empty($newKey) && is_numeric($newKey)) {
$inputs[$newKey] = $newInput;
}
}$i++;
}
$data['property_type_id'] = $propertyTypesId;
$data['seller_id'] = Auth::user()->id;
$data['lat'] = isset($inputsValues['lat'])?$inputsValues['lat']:0;
$data['lng'] = isset($inputsValues['long'])?$inputsValues['long']:0;
$latitude = $data['lat'];
$longitude = $data['lng'];
$key= \Config::get('TIMEZONE_API_KEY');
$time = time();
$url = "https://maps.googleapis.com/maps/api/timezone/json?location=$latitude,$longitude×tamp=$time&key=$key";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(curl_exec($ch) === false)
{
pr(curl_error($ch));
exit;
}
$responseJson = curl_exec($ch);
curl_close($ch);
$response = json_decode($responseJson);
$timezone_name='';
$asiaTimezone = Config::get('constants.ASIA_TIMEZONE');// constants.ASIA_TIMEZONE;
if($response->timeZoneId==$asiaTimezone){
$timezone_name = str_replace("Calcutta","Kolkata",$response->timeZoneId);
}else{
$timezone_name = $response->timeZoneId;
}
$data['timezone_name'] = $timezone_name;
$data['is_approved_checked'] = isset($inputsValues['is_approved_checked']) ? $inputsValues['is_approved_checked'] : 0;
$data['policy_types_id'] = $inputsValues['policyType'];
$propertyTypeObj = new Property($data);
try {
if ($propertyTypeObj->save()) {
$propertyId = $propertyTypeObj->id;
$fileName = (new PropertyTypeSection())
->join('property_type_section_fields', 'property_type_section_fields.property_type_section_id', '=', 'property_type_sections.id')
->where(['property_type_sections.property_type_id' => $propertyTypesId, 'property_type_section_fields.input_field_type_id' => \Config::get('constants.ADMIN_DEFAULT_PROPERTY_FEILDS_TYPE_ID.3')])
->select('property_type_section_fields.id')
->get()->toArray();
$imageAry = $request->file();
$image = [];
$newImageAry = [];
if (!empty($imageAry)) {
foreach ($imageAry as $key => $imgArray) {
$imageAryKey = $key;
$newImageKey = substr($imageAryKey, 0, strpos($imageAryKey, "_"));
$newImageAry[$newImageKey] = $imgArray;
}
}
if (!empty($newImageAry) && !empty($fileName)) {
foreach ($fileName as $fileId) {
$newImageAryKey = array_keys($newImageAry);
if (in_array($fileId['id'], $newImageAryKey)) {
$images[$fileId['id']] = $newImageAry[$fileId['id']];
}
}
}
$input['image_name'] = [];
$imageFileName = [];
if (!empty($images)) {
foreach ($images as $key => $imagees) {
if(is_array($imagees)){
foreach ($imagees as $imgKey=>$image) {
$input['image_name'] = time() . str_shuffle('addProperty67890').rand(0, 9) . '.' . $image->getClientOriginalExtension();
$destinationPath = public_path(\Config::get('constants.IMAGE_FOLDER_NAME'));
$image->move($destinationPath, $input['image_name']);
$filePath = $destinationPath . '/' . 'thumb_' . $input['image_name'];
$newPath = public_path(\Config::get('constants.IMAGE_FOLDER_NAME') . '/' . $input['image_name']);
createThumb($newPath, $filePath, 150, 200);
$imageFileName[$imgKey]['id'] = $imgKey;
$imageFileName[$imgKey]['image'] = $input['image_name'];
if(isset($inputsValues['main_image'])){
if($inputsValues['main_image']==$imgKey){
$imageFileName[$imgKey]['chk'] = 1 ;
} else{
$imageFileName[$imgKey]['chk'] = 0 ;
}
} else{
$imageFileName[$imgKey]['chk'] = 1;
}
}
$inputs[$key] = json_encode($imageFileName);
}else{
$input['image_name'] = time() . str_shuffle('addExtraFeature12345').rand(0, 9) . '.' . $imagees->getClientOriginalExtension();
$destinationPath = public_path(\Config::get('constants.IMAGE_FOLDER_NAME'));
$imagees->move($destinationPath, $input['image_name']);
$filePath = $destinationPath . '/' . 'thumb_' . $input['image_name'];
$newPath = public_path(\Config::get('constants.IMAGE_FOLDER_NAME') . '/' . $input['image_name']);
createThumb($newPath, $filePath, 150, 200);
$inputs[$key] = $input['image_name'];
}
}
}
foreach ($inputs as $ind => $inputVal) {
if (is_numeric($ind)) {
if (is_array($inputVal)) {
foreach ($inputVal as $key => $value) {
$savePropertyFieldValue[] = [
'property_id' => $propertyId,
'property_type_section_field_id' => $ind,
'property_type_section_field_value' => $value,
'is_option' => '1',
'created_at' => date('Y-m-d h:i:s'),
];
}
} else {
$savePropertyFieldValue[] = [
'property_id' => $propertyId,
'property_type_section_field_id' => $ind,
'property_type_section_field_value' => $inputVal,
'is_option' => '0',
'created_at' => date('Y-m-d h:i:s'),
];
}
}
}
// pr($savePropertyFieldValue,1);
\DB::table('properties_field_values')->insert(
$savePropertyFieldValue
);
DB::commit();
return redirect()->route('show.property.availaibility', ['propertyTypesId' => $propertyId]);
}
}catch (Exception $e){
DB::rollback();
//pr($e->getMessage(),1);
return redirect('/property/information')->with('warning', $e->getMessage());
}
}catch(\Exception $e){
DB::rollback();
//pr($e->getMessage(),1);
return redirect('/property/information')->with('warning', $e->getMessage());
}
}
/*========================================
Load View For Display Booking Calendar
===========================================*/
public function showPropertyAvailability(Request $request, $propertyTypesId){
try {
$isBlocked = '';
$propertyAvailablityDates = (new PropertyAvailaibility())->getPropertySelectedDatesAndDays($propertyTypesId);
//pr($propertyAvailablityDates,1);
$data = [];
$startDate = reset($propertyAvailablityDates);
$endDate = end($propertyAvailablityDates);
$startDate = $startDate['date'];
$endDate = $endDate['date'];
$bookedDates = [];
if (!empty($propertyAvailablityDates)) {
$isBlocked = array_column($propertyAvailablityDates,'is_blocked');
$isBlocked = $isBlocked[0];
foreach ($propertyAvailablityDates as $dates) {
$data[] = [
'success' => '100',
'title' => 'booked',
'start' => date('Y-m-d',strtotime($dates['date'])),
'start_date' => date('Y-m-d',strtotime($startDate)),
'last_date' => date('Y-m-d',strtotime($endDate)),
//'booked' => $dates['is_booked'],
'booked' => $dates['is_requested'],
'isBlocked' => $dates['is_blocked'],
];
if ($dates['is_booked'] == '1') {
$bookedDates[] = [
'start_date' => $dates['date'],
//'booked' => $dates['is_booked'],
'booked' => $dates['is_requested'],
];
}
}
} else {
$data = ['success' => '0'];
}
//pr($data,1);
$data = json_encode($data);
$bookedDates = json_encode($bookedDates);
$propertyData = (new PropertyFieldValue())->getPropertyDetail( $propertyTypesId );
$propertyData = prepareDataForPropertyDetail($propertyData);
//pr($propertyData,1);
return view('seller.property.property_availaibility', compact('propertyTypesId', 'propertyAvailablityDates', 'data', 'startDate', 'endDate', 'bookedDates','isBlocked','propertyData'));
} catch (Exception $e){
}
}
public function blockunblockdates(Request $request, $id,$isBlocked){
$ary = [
'is_blocked' => $isBlocked,
'updated_at' => date('Y-m-d H:i:s')
];
(new PropertyAvailaibility())->where(['property_id' => $id])->update($ary);
if($isBlocked == 1){
Session::flash('message', 'all date are unblock successfully');
}else{
Session::flash('message', 'all date are blocked successfully');
}
return redirect()->route('seller-properties');
}
public function getCalenderEvents(Request $request,$id){
/*$inputs = $request->all();
$id = $inputs['id'];*/
try {
$propertyAvailablityDates = (new PropertyAvailaibility())->getPropertySelectedDatesAndDays($id);
$startDate = reset($propertyAvailablityDates);
$endDate = end($propertyAvailablityDates);
if (!empty($propertyAvailablityDates)) {
foreach ($propertyAvailablityDates as $dates) {
$data[] = [
'success' => '100',
'title' => 'booked',
'start' => date('Y-m-d',strtotime($dates['date'])),
'start_date' => date('Y-m-d',strtotime($startDate['date'])),
'last_date' => date('Y-m-d',strtotime($endDate['date'])),
'isBlocked' => $dates['is_blocked']
];
}
} else {
$data = [
'success' => '0',
];
}
return json_encode($data);
}catch (Exception $e){
}
}
public function getCalenderEventsDates(Request $request,$id,$dates){
try {
$inputs = $request->all();
$propertyAvailablityDates = (new PropertyAvailaibility())->getPropertySelectedFilterWithDate($id, $dates);
if (count($propertyAvailablityDates) > 0) {
$propertyAvailablityDates = $propertyAvailablityDates->toArray();
} else {
$propertyAvailablityDates = '';
}
if (!empty($propertyAvailablityDates)) {
$data = $propertyAvailablityDates['date'];
$data = [
'success' => '100',
'date' => date('Y-m-d',strtotime($propertyAvailablityDates['date'])),
'is_booked' => $propertyAvailablityDates['is_requested'],
'isBlocked' => $propertyAvailablityDates['is_blocked']
];
return $data;
} else {
/**** data not found ****/
return [
'success' => '0',
];
}
}catch (Exception $e){
}
}
/*================================================
Store Dates into property_availaibility_dates
===================================================*/
public function storePropertyAvailabilityData(Request $request) {
//echo $request->property_id;
try {
$time = Config::get('constants.START_TIME');// constants.UTC_START_TIME;
$PropertyAvailaibility_already_exists = PropertyAvailaibility::where('property_id', '=', $request->property_id)->first();
$timeZone = Property::where(array('id' => $request->property_id))->value('timezone_name');
//pr($PropertyAvailaibility_already_exists,1);
$bookedDates = [];
$bookedDatesArray = [];
$dateArray = [];
// $currentTime = date('Y-m-d H:i:s');
// echo $timeZone;
// exit;
//echo convertToLocalTimeZone($currentTime, 'Asia/Kolkata');
// exit;
if (count($PropertyAvailaibility_already_exists) > 0) {
$bookedDates = PropertyAvailaibilityDate::where(['property_availaibility_id' => $PropertyAvailaibility_already_exists->id, 'is_requested' => 1])->get();
foreach ($bookedDates->toArray() as $bookdates) {
$bookedDatesArray[] = $bookdates['date'];
}
$requestDateArray = $request->dates;
$lastBookedDate = end($bookedDatesArray);
$lastRequestedDate = end($requestDateArray);
if ($lastBookedDate <= $lastRequestedDate) {
(new PropertyAvailaibilityDate())->where(['property_availaibility_id' => $PropertyAvailaibility_already_exists->id, 'is_requested' => '0'])->delete();
if (!empty($bookedDates) && count($bookedDates) > 0) {
$newDatesArray = array_diff($request->dates, $bookedDatesArray);
if (!empty($newDatesArray)) {
foreach ($newDatesArray as $dates) {
$array[] = [
'property_availaibility_id' => $PropertyAvailaibility_already_exists->id,
'date' => convertIntoUTC($dates, $time, $timeZone),
'is_booked' => '0',
'is_requested' => '0',
];
}
}
} else {
foreach ($request->dates as $value) {
$array[] = [
'property_availaibility_id' => $PropertyAvailaibility_already_exists->id,
'date' => convertIntoUTC($value, $time, $timeZone),
'is_booked' => '0',
'is_requested' => '0',
];
}
}
if(!empty($array)) {
(new PropertyAvailaibilityDate())->insert($array);
}
$update = [
'property_id' => $request->property_id,
'avalaibility_option' => $request->avalaibility_option,
'updated_at' => date('Y-m-d'),
];
(new PropertyAvailaibility())->where(['property_id' => $request->property_id])->update($update);
Session::flash('message', 'Property updated successfully');
return response()->json(['success'=>true] );
}else{
Session::flash('warning', 'Sorry some property have already book');
return response()->json(['warning'=>true] );
}
} else {
$PropertyAvailaibility = new PropertyAvailaibility;
$propertyArray = [
'property_id' => $request->property_id,
'avalaibility_option' => $request->avalaibility_option,
'is_blocked' => '1',
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
];
$insertId = $PropertyAvailaibility->insertGetId($propertyArray);
foreach ($request->dates as $value) {
$array[] = [
'property_availaibility_id' => $insertId,
'date' => convertIntoUTC($value,$time,$timeZone),
'is_booked' => '0',
];
}
(new PropertyAvailaibilityDate())->insert($array);
Session::flash('message', 'Property added successfully');
return response()->json(['success'=>true] );
}
} catch (Exception $e){
Session::flash('message', $e->getMessage());
return response()->json(['success'=>false]);
}
}
/*===========================================
Function For Getting My property Details
==============================================*/
public function propertyDetail(Request $request){
$input = $request->all();
$commentType = $input['commentType'];
$bookingId = $input['bookingId'];
$userId = Auth::user()->id;
$propertyId = $input['property_id'];
$propertyDetails = (new PropertyFieldValue())->getPropertyDetail( $propertyId );
foreach($propertyDetails as $propertyDetail){
if($propertyDetail['is_option']==1){
$ids[] = $propertyDetail['property_type_section_field_value'];
}
}
if((isset($ids)) && (count($ids))){
$display_values = (new PropertyTypeSectionFieldOption())->getDisplayValues( $ids );
} else {
$display_values[]=0;
}
$section_array = prepareDataForPropertyDetail( $propertyDetails ); //Defined In Helper
if($commentType==1){
$bookingDates = Bookings::join('booking_dates', 'bookings.booking_id', '=', 'booking_dates.booking_id')
->where(array('bookings.user_id'=> Auth::user()->id, 'bookings.property_id' => $propertyId, 'bookings.booking_id' => $bookingId ))
->select('booking_dates.date','booking_dates.booking_date_id')
->get()
->toArray();
$endDateOfBooking = end($bookingDates);
//$propertyReviews = (new PropertyReviews())->getReviewOfSeller( $propertyId );
$propertyReviews = (new PropertyReviews())->getReviewOfBuyer( $propertyId );
$idReviewOfBuyer = (new PropertyReviews())->getBookingId( $propertyId , $userId, $bookingId );
if($idReviewOfBuyer){
$displayAddReview = 0;
} else{
$displayAddReview = 1;
}
}
if( $commentType==2 || $commentType==3 ){
/* echo 'propertyId--->>'.$propertyId.'<br>';
echo 'Auth::user()->id--->>'.Auth::user()->id;
echo 'bookingId--->>'.$bookingId;*/
$bookingDates = Bookings::join('booking_dates', 'bookings.booking_id', '=', 'booking_dates.booking_id')
->where(array('bookings.property_owner_id'=> Auth::user()->id, 'bookings.property_id' => $propertyId, 'bookings.booking_id' => $bookingId ))
->select('booking_dates.date','booking_dates.booking_date_id')
->get()
->toArray();
$endDateOfBooking = end($bookingDates);
$propertyReviews = (new PropertyReviews())->getReviewOfBuyer( $propertyId );
$idReviewOfSeller = (new PropertyReviews())->getIdReviewOfSeller( $propertyId , $userId, $bookingId );
if($idReviewOfSeller){
$displayAddReview = 0;
} else{
$displayAddReview = 1;
}
//echo $displayAddReview;
}
$totalReviewOfBuyer = (new PropertyReviews())->getTotalReviewOfBuyer( $propertyId );
return view('seller.property_details',compact( 'section_array', 'display_values', 'propertyId', 'commentType', 'endDateOfBooking', 'propertyReviews', 'displayAddReview', 'bookingId', 'totalReviewOfBuyer' ));
}
/*=========================================================================
Function For Getting Upcoming Properties That Are Booked By Other Seller owner
============================================================================*/
public function bookedUpcomingProperties(){
$propertyOwnerId=Auth::user()->id;
$commentType = 2;
$query = (new Bookings())->getBookedUpcomingProperties( $propertyOwnerId );
$allPropertiesData = $query->orderBy('bookings.property_id', "DESC")->paginate(4);
$PropertiesIds = array();
$bookingsIds = array();
if(isset($allPropertiesData)){
foreach($allPropertiesData as $value){
$PropertiesIds[] = $value["property_id"];
$bookingsIds[] = $value["booking_id"];
}
}
$properties_data = (new Property())->getBookedUpcomingBookingPropertyData( $bookingsIds, $propertyOwnerId );
if(isset($properties_data)){
$propertyArr = prepareDataForUpComingPastProperties($properties_data); // Defined in Helper
}
$active = 'bookedUpcomingProperties';
//pr($propertyArr,1);
return view('seller.property.upcoming_properties',compact( 'propertyArr', 'allPropertiesData', 'active', 'commentType' ) );
}
/*=========================================================================
Function For Getting Pending Properties That Are Booked By Other Seller
============================================================================*/
public function bookedPendingBookingProperties(){
$propertyOwnerId=Auth::user()->id;
$commentType = 2;
$query = (new Bookings())->getBookedPendingProperties( $propertyOwnerId );
$allPropertiesData = $query->orderBy('bookings.property_id', "DESC")->paginate(4);
$PropertiesIds = array();
$bookingsIds = array();
if(isset($allPropertiesData)){
foreach($allPropertiesData as $value){
$PropertiesIds[] = $value["property_id"];
$bookingsIds[] = $value["booking_id"];
}
}
$properties_data = (new Property())->getBookedPendingBookingPropertyData( $bookingsIds, $propertyOwnerId );
if(isset($properties_data)){
$propertyArr = prepareDataForUpComingPastProperties($properties_data); // Defined in Helper
}
$active = 'bookedPendingBookingProperties';
return view('seller.property.pending_booking',compact( 'propertyArr', 'allPropertiesData', 'active', 'commentType' ) );
}
/*=========================================================================
Function For Getting Rejected Properties That Are Booked By Other Seller
============================================================================*/
public function bookedRejectedBookingProperties(){
$propertyOwnerId=Auth::user()->id;
$commentType = 2;
$query = (new Bookings())->getBookedRejectedProperties( $propertyOwnerId );
$allPropertiesData = $query->orderBy('bookings.property_id', "DESC")->paginate(4);
$PropertiesIds = array();
$bookingsIds = array();
if(isset($allPropertiesData)){
foreach($allPropertiesData as $value){
$PropertiesIds[] = $value["property_id"];
$bookingsIds[] = $value["booking_id"];
}
}
$properties_data = (new Property())->getBookedRejectedBookingPropertyData( $bookingsIds, $propertyOwnerId );
if(isset($properties_data)){
$propertyArr = prepareDataForUpComingPastProperties($properties_data); // Defined in Helper
}
$active = 'bookedRejectedBookingProperties';
return view('seller.property.rejected_booking',compact( 'propertyArr', 'allPropertiesData', 'active', 'commentType' ) );
}
/*===============================================================================
Function For Getting Rejected Properties That Are Booked By Other Seller Guest
==================================================================================*/
public function rejectedBookingProperties(){
$userId=Auth::user()->id;
$commentType = 2;
$query = (new Bookings())->getRejectedProperties( $userId );
$allPropertiesData = $query->orderBy('bookings.property_id', "DESC")->paginate(4);
$PropertiesIds = array();
$bookingsIds = array();
if(isset($allPropertiesData)){
foreach($allPropertiesData as $value){
$PropertiesIds[] = $value["property_id"];
$bookingsIds[] = $value["booking_id"];
}
}
$properties_data = (new Property())->getRejectedBookingPropertyData( $bookingsIds, $userId );
if(isset($properties_data)){
$propertyArr = prepareDataForUpComingPastProperties($properties_data); // Defined in Helper
}
$active = 'rejectedBookingProperties';
return view('seller.property.rejected_booking',compact( 'propertyArr', 'allPropertiesData', 'active', 'commentType' ) );
}
/*================================================
Function For Getting Upcoming Properties guest
==================================================*/
public function upcomingProperties(){
$userId=Auth::user()->id;
$commentType = 1;
$query = (new Bookings())->getUpcomingProperties( $userId );
$allPropertiesData = $query->orderBy('bookings.property_id', "DESC")->paginate(4);
$PropertiesIds = array();
$bookingsIds = array();
if(isset($allPropertiesData)){
foreach($allPropertiesData as $value){
$PropertiesIds[] = $value["property_id"];
$bookingsIds[] = $value["booking_id"];
}
}
$properties_data = (new Property())->getUpcomingBookingPropertyData( $bookingsIds, $userId );
if(isset($properties_data)){
$propertyArr = prepareDataForUpComingPastProperties($properties_data); // Defined in Helper
}
$active = 'upcomingProperties';
return view('seller.property.upcoming_properties',compact( 'propertyArr', 'allPropertiesData', 'active', 'commentType' ) );
}
/*================================================================================
Function For Getting Approve Properties That Are Booked By Other Seller owner
=================================================================================*/
public function bookedApproveProperties($bookingId = null){
// $bookingId = '38';
$allPropertiesData = [];
$propertyOwnerId=Auth::user()->id;
$commentType = 2;
$query = (new Bookings())->getBookedApproveProperties( $propertyOwnerId,$bookingId);
$allPropertiesData = $query->orderBy('bookings.property_id', "DESC");
$allPropertiesData = (!empty($bookingId) || $bookingId == null) ? $allPropertiesData->paginate(1) : $allPropertiesData->paginate(4);
//pr($allPropertiesData->toArray(),1);
$PropertiesIds = array();
$bookingsIds = array();
if(isset($allPropertiesData)){
foreach($allPropertiesData as $value){
$PropertiesIds[] = $value["property_id"];
$bookingsIds[] = $value["booking_id"];
}
}
$properties_data = (new Property())->getBookedApproveBookingPropertyData( $bookingsIds, $propertyOwnerId );
//pr($properties_data,1);
if(isset($properties_data)){
$propertyArr = prepareDataForUpComingPastProperties($properties_data); // Defined in Helper
}
//pr($propertyArr,1);
$active = 'bookedApproveProperties';
return view('seller.property.approved-booking-properties',compact('propertyOwnerId', 'propertyArr', 'allPropertiesData', 'active', 'commentType' ) );
}
/*===============================================================================
Function For Getting Approve Properties That Are Booked By Other Seller guest
=================================================================================*/
public function approveProperties(){
$useId=Auth::user()->id;
$propertyOwnerId=Auth::user()->id;
$commentType = 1;
$query = (new Bookings())->getApproveProperties( $useId );
$allPropertiesData = $query->orderBy('bookings.property_id', "DESC")->paginate(4);
$propertiesIds = array();
$bookingsIds = array();
if(isset($allPropertiesData)){
foreach($allPropertiesData as $value){
$propertiesIds[] = $value["property_id"];
$bookingsIds[] = $value["booking_id"];
}
}
$bookedDates =(new PropertyAvailaibility())->getBookedDates( $propertiesIds );
$properties_data = (new Property())->getApproveBookingPropertyData( $bookingsIds, $useId );
if(isset($properties_data)){
$propertyArr = prepareDataForUpComingPastProperties($properties_data); // Defined in Helper
}
$active = 'approveProperties';
return view('seller.property.approved-booking-properties',compact('bookedDates','propertyOwnerId','propertyArr', 'allPropertiesData', 'active', 'commentType' ) );
}
/*==============================================
Function For Getting Pending Properties guest
===============================================*/
public function pendingProperties(){
$useId=Auth::user()->id;
$commentType = 1;
$query = (new Bookings())->getPendingProperties( $useId );
$allPropertiesData = $query->orderBy('bookings.property_id', "DESC")->paginate(4);
$PropertiesIds = array();
$bookingsIds = array();
if(isset($allPropertiesData)){
foreach($allPropertiesData as $value){
$PropertiesIds[] = $value["property_id"];
$bookingsIds[] = $value["booking_id"];
}
}
$properties_data = (new Property())->getPendingBookingPropertyData( $bookingsIds, $useId );
if(isset($properties_data)){
$propertyArr = prepareDataForUpComingPastProperties($properties_data); // Defined in Helper
}
$active = 'pendingProperties';
return view('seller.property.user_pending_properties',compact( 'propertyArr', 'allPropertiesData', 'active', 'commentType' ) );
}
/*==============================================
Function For Getting Past Booking Properties Owner
================================================*/
public function bookedPastBookingProperties(){
$propertyOwnerId=Auth::user()->id;
$commentType = 2;
$query = (new Bookings())->getBookedPastBookingProperties( $propertyOwnerId );
$allPropertiesData = $query->orderBy('bookings.property_id', "DESC")->paginate(4);
$bookingsIds = array();
$PropertiesIds = array();
if(isset($allPropertiesData)){
foreach($allPropertiesData as $value){
$PropertiesIds[] = $value["property_id"];
$bookingsIds[] = $value["booking_id"];
}
}
$properties_data = (new Property())->getBookedPastBookingPropertyData( $bookingsIds, $propertyOwnerId );
if(isset($properties_data)){
$propertyArr = prepareDataForUpComingPastProperties($properties_data); // Defined in Helper
}
$active = 'bookedPastBookingProperties';
return view('seller.property.past_booking_properties', compact( 'propertyArr', 'allPropertiesData', 'active', 'commentType' ));
}
/*=====================================================
Function For Getting Past Booking Properties guest
========================================================*/
public function pastBookingProperties(){
$useId=Auth::user()->id;
$commentType = 1;
$query = (new Bookings())->getPastBookingProperties( $useId );
$allPropertiesData = $query->orderBy('bookings.property_id', "DESC")->paginate(4);
$PropertiesIds = array();
$bookingsIds = array();
if(isset($allPropertiesData)){
foreach($allPropertiesData as $value){
$PropertiesIds[] = $value["property_id"];
$bookingsIds[] = $value["booking_id"];
}
}
$properties_data = (new Property())->getPastBookingPropertyData( $bookingsIds, $useId );
if(isset($properties_data)){
$propertyArr = prepareDataForUpComingPastProperties($properties_data); // Defined in Helper
}
$active = 'pastBookingProperties';
return view('seller.property.past_booking_properties', compact( 'propertyArr', 'allPropertiesData', 'active', 'commentType' ));
}
/*==============================================
Function For cancel booking
================================================*/
public function cancelBooking(Request $request){
try{
$propertyOwnerId=Auth::user()->id;
$inputs = $request->all();
$availability_dates_ids = ( new PropertyAvailaibility() )->getPropertyBookingDatesWithDates( $inputs['propertyId'], $inputs['startDate'], $inputs['endDate'] );
$bookingId = $inputs['bookingID'];
$bookingData = (new Bookings())->getPolicyRecord( $bookingId );
$bookingDates = (new Bookings())->getBookingDatesByBookingID( $bookingId );
$property_id = $bookingData['property_id'];
$property_status = (new Property())->getApprovedStatus($inputs['propertyId']);
$propertyTimezone= $property_status['timezone_name'];
$dateResult = getUtcTime($propertyTimezone);
$currentDateTime=$dateResult['currentTime']; // current time according to time zone
$utcDateTime=$dateResult['utcTime']; // UTC time according to time zone
$property_owner_id = $bookingData['property_owner_id'];
$cancelDuration = $bookingData['duration'];
$bookingStartdate = $bookingDates[0]['date'];
$policyDuratonHours = \Config::get('constants.CANCELLATION_POLICY_DURATION_IN_MINUTES');
$bookingPolicyDuration='';
if($propertyOwnerId==$property_owner_id){
$bookingPolicyDuration = $policyDuratonHours['owner'];
} else{
$bookingPolicyDuration = $policyDuratonHours[$cancelDuration];
}
$bookingDuration=dateDiff($utcDateTime,$bookingStartdate);
$bookingMinutesDiff= $bookingDuration['minutesDiff'];
if($bookingPolicyDuration < $bookingMinutesDiff) {
$cancelPolicyId= $bookingData['policy_id'];
if(Bookings::where( 'booking_id', $inputs['bookingID'] )->update( array( 'is_approved'=> 3))){
$availabilityIds = (new PropertyAvailaibility())->cancelGetPropertyAvailabilityBetweenDates1( $inputs['propertyId'], $inputs['startDate'], $inputs['endDate'] );
(new PropertyAvailaibilityDate())->cancelDates( $availabilityIds );
return response()->json(['success'=>true]);
}
} else {
return response()->json(['success'=>false,'limitEexceed'=>'yes']);
}
}
catch(\Exception $e){ pr($e->getMessage(),1);
return $e->getMessage();
}
}
/*==============================================
Function For Approve and reject booking
================================================*/
public function approveBooking(Request $request){
try{
$current_date = getServerUtcTime();
$inputs = $request->all();
$bookingId=$inputs['bookingID'];
$checkedAvailability = (new PropertyAvailaibility())->getPropertyAvailabilityBetweenDatesFree( $inputs['propertyId'], $inputs['startDate'], $inputs['endDate'] );
$bookingDate = (new Bookings())->getBookingDatesByBookingID( $bookingId );
$ary = [
'is_approved' => $inputs['status'],
'updated_at' => date('Y-m-d H:i:s')
];
if($inputs['status']==1){
if($inputs['startDate'] >= $current_date){
if(count($checkedAvailability) == count($bookingDate)){
if($this->messageToBeSend($ary,$inputs['bookingID'],$inputs['email'],$inputs['mobileno'],$inputs['status'],$inputs['propertyId'])){
return response()->json(['success'=>true,'is_approved' => $inputs['status']]);
}
} else {
return response()->json(['success'=>false,'availaibility' => 0]);
}
} else {
return response()->json(['success'=>false,'expaired' => 1]);
}
} else if($inputs['status']==2){
if($this->messageToBeSend($ary,$inputs['bookingID'],$inputs['email'],$inputs['mobileno'],$inputs['status'],$inputs['propertyId'],$inputs['startDate'],$inputs['endDate'])){
$availabilityIds = (new PropertyAvailaibility())->cancelGetPropertyAvailabilityBetweenDates1( $inputs['propertyId'], $inputs['startDate'], $inputs['endDate'] );
(new PropertyAvailaibilityDate())->cancelDates( $availabilityIds );
return response()->json(['success'=>true,'is_approved' => $inputs['status']]);
}else{
return response()->json(['success'=>false,'is_approved' => $inputs['status']]);
}
} else {
return response()->json(['success'=>false,'is_approved' => $inputs['status']]);
}
} catch(\Exception $e){
return $e->getMessage();
//return redirect('/seller/upcoming-properties')->with('warning', $e->getMessage());
}
}
/*===========================================================
Function For Displaying The Profile of Buyer From seller
============================================================*/
public function buyerDetail(Request $request){
$inputs = $request->all();
$buyerID = $inputs['buyerId'];
$offSet = isset($inputs['offset']) ? $inputs['offset'] : 0;
$userInformation = User::with(array('userReviews' => function ($q) use ($buyerID, $offSet) {
$q->join('users', 'property_reviews.rating_from_user', '=', 'users.id');
$q->where(array('comment_type' => 2))
->select(['property_reviews.*', 'users.id as user_id', 'users.first_name', 'users.last_name', 'users.image'])
->take(4)
->skip($offSet);
}))
->where(array('users.id' => $buyerID))->first()->toArray();
if (AjaxRequest::ajax()) {
return response()->json($userInformation);
} else {
return view('seller/user_profile',compact('userInformation'));
}
}
/*================================================================
Function For Displaying The Profile of seller after login
============================================================*/
public function sellerDetail(Request $request){
$inputs = $request->all();
$sellerID = $inputs['sellerId'];
$offSet = isset($inputs['offset']) ? $inputs['offset'] : 0;
$sellerUserInformation = $this->reviewsAsSeller($sellerID, $offSet);
$buyerUserInformation = $this->reviewsAsBuyer($sellerID, $offSet);
$arr = $this->getProperties($sellerID);
$propertyArr = $arr['0'];
$allPropertiesData = $arr['1'];
$active = 'myProperty';
return view('seller/seller_profile',compact('sellerUserInformation','buyerUserInformation','propertyArr', 'allPropertiesData', 'active'));
}
/*================================================================
Function For Displaying The Profile of seller before login
==================================================================*/
public function sellerprofile(Request $request){
$inputs = $request->all();
$sellerID = $inputs['sellerId'];
$offSet = isset($inputs['offset']) ? $inputs['offset'] : 0;
$sellerUserInformation = $this->reviewsAsSeller($sellerID, $offSet);
$buyerUserInformation = $this->reviewsAsBuyer($sellerID, $offSet);
$arr = $this->getProperties($sellerID);
$propertyArr = $arr['0'];
$allPropertiesData = $arr['1'];
$active = 'myProperty';
return view('seller/before_login_seller_profile',compact('sellerUserInformation','buyerUserInformation','propertyArr', 'allPropertiesData', 'active'));
}
/*=====================================
Function For Get reviews As Buyer
=======================================*/
function reviewsAsBuyer($sellerID, $offSet){
return $buyerUserInformation = User::with(array('userReviews' => function ($q) use ($sellerID, $offSet) {
$q->join('users', 'property_reviews.rating_from_user', '=', 'users.id');
$q->where(array('comment_type' => 2))
->select(['property_reviews.*', 'users.id as user_id', 'users.first_name', 'users.last_name', 'users.image'])
->take(4)
->skip($offSet);
}))
->where(array('users.id' => $sellerID))->first()->toArray();
}
/*=====================================
Function For Get reviews As Seller
=======================================*/
function reviewsAsSeller($sellerID, $offSet){
return $sellerUserInformation = User::with(array('userReviews' => function ($q) use ($sellerID, $offSet) {
$q->join('users', 'property_reviews.rating_to_user', '=', 'users.id');
$q->where(array('comment_type' => 1))
->select(['property_reviews.*', 'users.id as user_id', 'users.first_name', 'users.last_name', 'users.image'])
->take(4)
->skip($offSet);
}))
->where(array('users.id' => $sellerID))->first()->toArray();
}
/*=====================================
Function For Get Seller Properties
=======================================*/
function getProperties($sellerID){
$query = (new Property())->getProperties($sellerID);
$allPropertiesData = $query->orderBy('properties.id', "ASC")->paginate(4);
$propertyIDS = array();
if(isset($allPropertiesData)){
foreach($allPropertiesData as $value){
$propertyIDS[] = $value["propertyIds"];
}
}
if(count($propertyIDS)){
$properties_data = (new Property())->getSellerPropertyRelatedData($propertyIDS);
}
if(isset($properties_data)){
$propertyArr = prepareDataForSellerProperties($properties_data); // Defined in Helper
}
return array($propertyArr, $allPropertiesData);
}
/*========================================================================
Function For Sending Message During Approving ,Rejection, Cancellation
=========================================================================*/
function messageToBeSend($ary,$bookingId,$email,$mobile_no,$status,$propertyId,$startDate=null,$endDate=null){
$propertyName = (new PropertyFieldValue())->getPropertyDetail($propertyId);
$propertyFullName = '';
//$routefunction = route('property.detail').'?property_id='.$propertyId.'&commentType=1&bookingId='.$bookingId;
$routefunction = route('approved-properties');
foreach($propertyName as $property){
if($property['field_name'] == 'Name'){
$propertyFullName = $property['property_type_section_field_value'];
}
}
if($status==1){
$subjects = "Property Approved";
$booking = "Your request for the booking of '".$propertyFullName."' has been approved by the Owner, please click on the following link.
<a href='".$routefunction."'>Click Here </a> to pay.";
}else{
$subjects = "Property Rejected";
$booking = "Your request for the booking of '".$propertyFullName."' has been rejected by the Owner from ".date('Y-m-d',strtotime($startDate))." to ".date('Y-m-d',strtotime($endDate))." ";
}
$user = (new User())->where(['mobile_number' => $mobile_no])->first();
$userName = $user->first_name.' '.$user->last_name;
$templateLog = (new TemplateLog())->where(['template_log_id' => '4 '])->first();
$userTaskDes = array("#user_name#",'#messages#');
$userTaskRep = array($userName,$booking);
$messages = $templateLog->message;
$newTaskDes = str_replace($userTaskDes,$userTaskRep,$messages);
$messageBody = $newTaskDes;
if((new Bookings())->where(['booking_id' => $bookingId])->update($ary)){
$message['bookingId'] = $bookingId;
$message['approved_token'] = md5(time());
$message['email'] = $email;
$message['subject'] = $subjects;
$message['mobile_no'] = $mobile_no;
$message['is_send'] = "1";
$message['body'] = $messageBody;
$message['url'] = "/success";
$message['type'] = 1;
$sendObj = new MessageToBeSend($message);
if($sendObj->save()){
return true;
}else{
return false;
}
}
}
/*=====================================================================
Function For Getting the Review Of Seller that are Giving To Buyer
========================================================================*/
public function reviewFromSeller(Request $request){
$inputs = $request->all();
$offSet = isset($inputs['offset']) ? $inputs['offset'] : 0;
$userId=Auth::user()->id;
$sellerReviews = (new PropertyReviews())->getReviewOfSellerToBuyer($userId,$offSet);
if(AjaxRequest::ajax()) {
return response()->json($sellerReviews);
} else {
$active = 'reviewFromSeller';
return view('seller/seller_reviews_to_buyer',compact('sellerReviews','active'));
}
}
/*================================================
Function For Loading View For Updating Values
==================================================*/
public function propertyEdit(Request $request,$id=null){
$propertyId = is_numeric($id) ? $id : '';
$properties = Property::where('id', $propertyId)->first();
$policyTypes = (new CancellationPolicyType())
->get(['policy_name','id'])->toArray();
$checkedRequied=$properties['is_approved_checked'];
$policyTypesID=$properties['policy_types_id'];
$propertyTypesId = $request->input('property_type_id');
$propertyTypes = (new PropertyType())
->where(['deleted_at' => NULL])
->get(['name','id'])->toArray();
$propertyTypesSection = (new PropertyTypeSection())
->leftjoin('property_type_section_fields', 'property_type_section_fields.property_type_section_id','=', 'property_type_sections.id')
->where('property_type_sections.property_type_id' , $propertyTypesId)
->select(\DB::raw('group_concat(property_type_section_fields.id) as property_type_section_fields_id'), 'property_type_sections.name', 'property_type_sections.id')
->groupBy('property_type_sections.id')
->orderBy('property_type_sections.order_id',"ASC")
->get()->toArray();
$propertyTypesSectionFieldId = explode(',', implode(',', array_filter(array_column($propertyTypesSection, 'property_type_section_fields_id'))));
$inputsFields = (new PropertyTypeSectionField())
->with(['propertyTypeSectionFieldValue' => function ($query) {
$query->select('display_value', 'property_type_section_field_id','id');
}])
->join('input_field_types', 'input_field_types.id','=', 'property_type_section_fields.input_field_type_id')
->whereIn('property_type_section_fields.id' , $propertyTypesSectionFieldId)
->select('property_type_section_fields.name','property_type_section_fields.validations','property_type_section_fields.field_identifier','property_type_section_fields.property_type_section_id','property_type_section_fields.id','input_field_types.field_name')
->orderBy('property_type_section_fields.order_id',"ASC")
->get()->toArray();
$propertyTypeSectionData = [];
foreach($propertyTypesSection as $ind => $propertyTypeFieldName){
foreach($inputsFields as $index => $inputsField) {
if ($inputsField['property_type_section_id'] == $propertyTypeFieldName['id']) {
$propertyTypeSectionData[$inputsField['property_type_section_id']]['section_name'] = $propertyTypeFieldName['name'];
$propertyTypeSectionData[$inputsField['property_type_section_id']]['section_id'] = $inputsField['property_type_section_id'];
$propertyTypeSectionData[$inputsField['property_type_section_id']]['fields'][$inputsField['id']]['type'] = $inputsField['field_name'];
$propertyTypeSectionData[$inputsField['property_type_section_id']]['fields'][$inputsField['id']]['id'] = $inputsField['id'];
$propertyTypeSectionData[$inputsField['property_type_section_id']]['fields'][$inputsField['id']]['name'] = $inputsField['name'];
$propertyTypeSectionData[$inputsField['property_type_section_id']]['fields'][$inputsField['id']]['validations'] = $inputsField['validations'];
$propertyTypeSectionData[$inputsField['property_type_section_id']]['fields'][$inputsField['id']]['field_identifier'] = $inputsField['field_identifier'];
$propertyTypeSectionData[$inputsField['property_type_section_id']]['fields'][$inputsField['id']]['options'] = $inputsField['property_type_section_field_value'];
}
}
}
$properties = (new Property())
->rightjoin('properties_field_values', 'properties_field_values.property_id','=', 'properties.id')
->rightjoin('property_type_section_fields', 'property_type_section_fields.id','=', 'properties_field_values.property_type_section_field_id')
->join('input_field_types', 'input_field_types.id','=', 'property_type_section_fields.input_field_type_id')
->where(function($query) use ($propertyTypesId) {
if ($propertyTypesId != '') {
$query->where('properties.property_type_id', $propertyTypesId);
}
})
->select('properties.lat', 'properties.lng','property_type_section_fields.name','property_type_section_fields.validations','input_field_types.field_name','properties_field_values.property_type_section_field_value','property_type_section_fields.field_identifier','property_type_section_fields.id as property_type_section_field_id','properties.id','properties_field_values.id as property_filed_value_id')
->groupBy('properties_field_values.id')
->get()->toArray();
$propertyEditArr = [];
foreach($properties as $key => $property) {
if ($property['id'] == $id) {
$propertyEditArr[$property['property_type_section_field_id']]['property_id'] = $property['property_type_section_field_id'];
$propertyEditArr[$property['property_type_section_field_id']]['property_type_section_field_value'][] = $property['property_type_section_field_value'];
$propertyEditArr[$property['property_type_section_field_id']]['lat'] = $property['lat'];
$propertyEditArr[$property['property_type_section_field_id']]['lng'] = $property['lng'];
}
}
return view('seller/property.edit_property_information',compact('policyTypes','policyTypesID','checkedRequied','propertyTypes','propertyTypeSectionData','propertyTypesId','propertyEditArr','propertyId'));
}
/*==============================
Function For Updating Values $multipleImages
================================*/
public function propertyUpdate(PropertiesFieldValues $request) {
$inputsValues = $request->all();
$propertyId = $inputsValues['property_id'];
$property = Property::where( array( 'id' => $propertyId ) )->first();
$data['lat']=trim($inputsValues['lat']);
$data['lng']=trim($inputsValues['long']);
$data['policy_types_id'] = trim($inputsValues['policyTypeID']);
$latitude = $data['lat'];
$longitude = $data['lng'];
$key= \Config::get('TIMEZONE_API_KEY');
$time = time();
$url = "https://maps.googleapis.com/maps/api/timezone/json?location=$latitude,$longitude×tamp=$time&key=$key";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(curl_exec($ch) === false) {
pr(curl_error($ch));
exit;
}
$responseJson = curl_exec($ch);
curl_close($ch);
$response = json_decode($responseJson);
$timezone_name='';
$asiaTimezone = Config::get('constants.ASIA_TIMEZONE');// constants.ASIA_TIMEZONE;
if($response->timeZoneId==$asiaTimezone){
$timezone_name = str_replace("Calcutta","Kolkata",$response->timeZoneId);
}else{
$timezone_name = $response->timeZoneId;
}
$data['timezone_name'] = $timezone_name;
$data['is_approved_checked'] = isset($inputsValues['is_approved_checked']) ? $inputsValues['is_approved_checked'] : 0;
if($property->policy_types_id!=$inputsValues['policyTypeID']){
$this->policyUpdationRecord($inputsValues['policyTypeID'],$propertyId);
}
$property->update( $data );
$propertyTypeId = $inputsValues['property_types_id'];
$inputs = [];
$i=0;
foreach($inputsValues as $key => $newInput){
if($i >= 2) {
$newKey = substr($key, 0, strpos($key, "_"));
if(!empty($newKey) && is_numeric($newKey)) {
$inputs[$newKey] = $newInput;
}
}$i++;
}
$properties = (new Property())
->rightjoin('properties_field_values', 'properties_field_values.property_id', '=', 'properties.id')
->rightjoin('property_type_section_fields', 'property_type_section_fields.id', '=', 'properties_field_values.property_type_section_field_id')
->join('input_field_types', 'input_field_types.id', '=', 'property_type_section_fields.input_field_type_id')
->where('properties_field_values.property_id', $propertyId)
->select('property_type_section_fields.name', 'property_type_section_fields.validations', 'input_field_types.field_name', 'properties_field_values.property_type_section_field_value', 'property_type_section_fields.field_identifier', 'property_type_section_fields.id as property_type_section_field_id', 'properties.id', 'properties_field_values.id as property_filed_value_id')
->groupBy('properties_field_values.id')
->get()->toArray();
$updatePropertyFieldValue = [];
$insertPropertyFieldValue = [];
$insertMultipleFieldValue = [];
$insertAbleIds = [];
$fileName = (new PropertyTypeSection())
->join('property_type_section_fields', 'property_type_section_fields.property_type_section_id','=', 'property_type_sections.id')
->where(['property_type_sections.property_type_id' => $propertyTypeId,'property_type_section_fields.input_field_type_id' => \Config::get('constants.ADMIN_DEFAULT_PROPERTY_FEILDS_TYPE_ID.3')])
->select('property_type_section_fields.id')
->get()->toArray();
$imageName = (new Property())
->join('properties_field_values', 'properties_field_values.property_id','=', 'properties.id')
->join('property_type_section_fields', 'property_type_section_fields.id','=', 'properties_field_values.property_type_section_field_id')
->where(['properties_field_values.property_id' => $propertyId,'property_type_section_fields.input_field_type_id' => \Config::get('constants.ADMIN_DEFAULT_PROPERTY_FEILDS_TYPE_ID.3')])
->where('properties_field_values.property_id',$propertyId)
->select('properties_field_values.property_type_section_field_value')
->get()->toArray();
$imageAry = $request->file();
$newImageAry = [];
//pr($imageName);
if(!empty($imageAry)){
foreach($imageAry as $key => $imgArray) {
$imageAryKey = $key;
$newImageKey = substr($imageAryKey, 0, strpos($imageAryKey, "_"));
$newImageAry[$newImageKey] = $imgArray;
}
}
$images = [];
$imageNameDone = [];
$i = 0;
if(!empty($newImageAry) && !empty($fileName)){
foreach($fileName as $fileId){
$newImageAryKey = array_keys($newImageAry);
if(in_array($fileId['id'],$newImageAryKey)) {
$images[$fileId['id']] = $newImageAry[$fileId['id']];
}
if(!empty($imageName[$i])){
$imageNameDone[$fileId['id']] = $imageName[$i];
}
$i++;
}
}
$input['image_name'] = '';
$k= 0;
// When only Change default image
/*if(!count($images) && (isset($inputsValues['main_image'])) ){
$uploadedImages = json_decode($imageName[0]['property_type_section_field_value'], true);
foreach($uploadedImages as $key => $value) {
if($uploadedImages[$key]['id']==$inputsValues['main_image']){
$uploadedImages[$key]['chk'] = 1;
}else{
$uploadedImages[$key]['chk'] = 0;
}
}
$index = $fileName[0]['id'];
$inputs[$index] = json_encode($uploadedImages);
}*/
foreach($images as $key => $image) {
if (!empty($image) && !empty($imageName) && !empty($imageName[$key])) {
if (file_exists(public_path(\Config::get('constants.IMAGE_FOLDER_NAME') . '/' . $imageName[$key]['property_type_section_field_value']))) {
unlink(public_path(\Config::get('constants.IMAGE_FOLDER_NAME') . '/' . $imageName[$key]['property_type_section_field_value']));
unlink(public_path(\Config::get('constants.IMAGE_FOLDER_NAME') . '/' . 'thumb_' . $imageName[$key]['property_type_section_field_value']));
$input['image_name'] = time() . rand(0, 9) . '.' . $image->getClientOriginalExtension();
$destinationPath = public_path(\Config::get('constants.IMAGE_FOLDER_NAME'));
$image->move($destinationPath, $input['image_name']);
$filePath = $destinationPath . '/' . 'thumb_' . $input['image_name'];
$newPath = public_path(\Config::get('constants.IMAGE_FOLDER_NAME') . '/' . $input['image_name']);
createThumb($newPath, $filePath, 150, 200);
} else {
$input['image_name'] = time() . rand(0, 9) . '.' . $image->getClientOriginalExtension();
$destinationPath = public_path(\Config::get('constants.IMAGE_FOLDER_NAME'));
$image->move($destinationPath, $input['image_name']);
$filePath = $destinationPath . '/' . 'thumb_' . $input['image_name'];
$newPath = public_path(\Config::get('constants.IMAGE_FOLDER_NAME') . '/' . $input['image_name']);
createThumb($newPath, $filePath, 150, 200);
}
$imagesKeys = array_keys($images);
$inputs[$imagesKeys[$k]] = $input['image_name'];
} else if (!empty($image)) {
if(is_array($image)){
$uploadedImages = json_decode($imageName[0]['property_type_section_field_value'], true);
foreach ($image as $imgKey=>$img) {
$input['image_name'] = time() . str_shuffle('editProperty12345').rand(0, 9) . '.' . $img->getClientOriginalExtension();
$destinationPath = public_path(\Config::get('constants.IMAGE_FOLDER_NAME'));
$img->move($destinationPath, $input['image_name']);
$filePath = $destinationPath . '/' . 'thumb_' . $input['image_name'];
$newPath = public_path(\Config::get('constants.IMAGE_FOLDER_NAME') . '/' . $input['image_name']);
createThumb($newPath, $filePath, 150, 200);
$imageFileName[$imgKey]['id'] = $imgKey;
$imageFileName[$imgKey]['image'] = $input['image_name'];
if(isset($inputsValues['main_image'])){
if($inputsValues['main_image']==$imgKey){
$imageFileName[$imgKey]['chk'] = 1 ;
if(!empty($uploadedImages)) {
foreach ($uploadedImages as $key => $value) {
//$uploadedImages[$key]['chk'] = 0;
if ($uploadedImages[$key]['id'] == $imgKey) { // Replace default image
$flag = 1;
if (file_exists(public_path(\Config::get('constants.IMAGE_FOLDER_NAME') . '/' . $uploadedImages[$key]['image']))) {
unlink(public_path(\Config::get('constants.IMAGE_FOLDER_NAME') . '/' . $uploadedImages[$key]['image']));
unlink(public_path(\Config::get('constants.IMAGE_FOLDER_NAME') . '/' . 'thumb_' . $uploadedImages[$key]['image']));
}
}
}
}
if(!empty($uploadedImages)) {
if (isset($flag) && ($flag) == 1) {
$imageFileName = array_replace($uploadedImages, $imageFileName);
} else {
$imageFileName = array_merge($uploadedImages, $imageFileName);
}
}
} else{
// All Images replacement expect default
foreach($uploadedImages as $key => $uploadedIma){
if($uploadedImages[$key]['id']==$imgKey){
if (file_exists(public_path(\Config::get('constants.IMAGE_FOLDER_NAME') . '/' . $uploadedImages[$key]['image']))) {
unlink(public_path(\Config::get('constants.IMAGE_FOLDER_NAME') . '/' . $uploadedImages[$key]['image']));
unlink(public_path(\Config::get('constants.IMAGE_FOLDER_NAME') . '/' . 'thumb_' . $uploadedImages[$key]['image']));
}
}
}
$imageFileName[$imgKey]['chk'] = 0 ;
$imageFileName = array_replace($uploadedImages,$imageFileName);
}
//$imageFileName = array_merge($uploadedImages,$imageFileName);
} else{
$imageFileName[$imgKey]['chk'] = 1;
}
}
$inputs[$fileName[$k]['id']] = json_encode($imageFileName);
}else{
$input['image_name'] = time() . str_shuffle('editExtraFeature67890'). rand(0, 9) . '.' . $image->getClientOriginalExtension();
$destinationPath = public_path(\Config::get('constants.IMAGE_FOLDER_NAME'));
$image->move($destinationPath, $input['image_name']);
$filePath = $destinationPath . '/' . 'thumb_' . $input['image_name'];
$newPath = public_path(\Config::get('constants.IMAGE_FOLDER_NAME') . '/' . $input['image_name']);
createThumb($newPath, $filePath, 150, 200);
$inputs[$key] = $input['image_name'];
}
} else {
unset($fileName[$key]['id']);
}
$k++;
}
// pr($inputs,1);
foreach ($inputs as $postInputFieldKey => $inputVal) {
if(is_array($inputVal)){
(new PropertyFieldValue())->where(['property_type_section_field_id' => $postInputFieldKey,'property_id' => $propertyId])->delete();
$insertAbleIds[] = $postInputFieldKey;
}
$isAvailable = false;
foreach ($properties as $GetProkey => $property) {
if ($property['property_type_section_field_id'] == $postInputFieldKey) {
$isAvailable = true;
break;
}
}
if ($isAvailable) {
if (is_numeric($postInputFieldKey)) {
if (is_array($inputVal)) {
foreach ($inputVal as $key => $value) {
$updatePropertyFieldValue[] = [
'property_id' => $propertyId,
'property_type_section_field_id' => $postInputFieldKey,
'property_type_section_field_value' => $value,
'is_option' => '1',
'created_at' => date('Y-m-d h:i:s'),
];
}
}else {
$updatePropertyFieldValue[] = [
'property_id' => $propertyId,
'property_type_section_field_id' => $postInputFieldKey,
'property_type_section_field_value' => "'$inputVal'",
'is_option' => '0',
'created_at' => date('Y-m-d h:i:s'),
];
}
}
} else {
if (is_numeric($postInputFieldKey)) {
$insertAbleIds[] = $postInputFieldKey;
}
}
}
if(!empty($insertAbleIds)){
$insertAbleIds = array_unique($insertAbleIds);
}
//$insertAbleIds[$fileName->id] = $input['image_name'];
if(!empty($insertAbleIds)) {
foreach ($insertAbleIds as $ind => $insertAbleId) {
if (is_array($inputs[$insertAbleId])) {
foreach ($inputs[$insertAbleId] as $key => $value) {
$insertPropertyFieldValue[] = [
'property_id' => $propertyId,
'property_type_section_field_id' => $insertAbleId,
'property_type_section_field_value' => $value,
'is_option' => '1',
'created_at' => date('Y-m-d h:i:s'),
];
}
} else {
$insertPropertyFieldValue[] = [
'property_id' => $propertyId,
'property_type_section_field_id' => $insertAbleId,
'property_type_section_field_value' => $inputs[$insertAbleId],
'is_option' => '0',
'created_at' => date('Y-m-d h:i:s'),
];
}
}
}
//pr($updatePropertyFieldValue,1);
//$propertyFieldValueIds = PropertyFieldValue::where(array('property_id' =>$propertyId))->pluck('property_type_section_field_id')->toArray();
//pr($propertyFieldValueIds,1);
$property_type_section_field_id = array_column($updatePropertyFieldValue, 'property_type_section_field_id');
//pr($property_type_section_field_id);
if (isset($property_type_section_field_id) && $property_type_section_field_id != '') {
$property_field_value_id = implode(",", $property_type_section_field_id);
//pr($property_field_value_id,1);
$property_type_section_field_value = "";
foreach ($updatePropertyFieldValue as $ind => $updatePropertyValue) { //pr($updatePropertyValue);
$propertyValues = !empty($updatePropertyValue['property_type_section_field_value']) ? $updatePropertyValue['property_type_section_field_value'] : " '' ";
$property_type_section_field_value .= "WHEN property_type_section_field_id = " . $updatePropertyValue['property_type_section_field_id'] . " THEN " . $propertyValues . " ";
$ids[] = $updatePropertyValue['property_type_section_field_id'];
}
if (!empty($ids)){
$ids = implode(",", $ids);
}
$id = $propertyId;
//pr($property_type_section_field_value);
$sqlQuery = "UPDATE `properties_field_values` SET `property_type_section_field_value`= CASE " . $property_type_section_field_value . " END
WHERE properties_field_values.property_type_section_field_id in ($ids) AND property_id=$id";
//pr($sqlQuery,1);
\DB::update($sqlQuery);
if(!empty($insertMultipleFieldValue)){
(new PropertyFieldValue())
->where(['property_id' => $insertMultipleFieldValue['property_id'],'property_type_section_field_id' => $insertMultipleFieldValue['property_type_section_field_id']])
->forceDelete();
foreach($insertMultipleFieldValue['property_type_section_field_value'] as $propertyTypeSections){
$insertPropertyFieldValue[] = [
'property_id' => $insertMultipleFieldValue['property_id'],
'property_type_section_field_id' => $insertMultipleFieldValue['property_type_section_field_id'],
'property_type_section_field_value' => $propertyTypeSections,
'is_option' => '1',
'created_at' => date('Y-m-d h:i:s'),
];
}
}
}//pr($insertPropertyFieldValue,1);
\DB::table('properties_field_values')->insert(
$insertPropertyFieldValue
);
//return redirect()->route('seller-properties');
return redirect()->route('show.property.availaibility', ['propertyTypesId' => $propertyId]);
}
/*==============================
Function For Updating Policy
================================*/
public function policyUpdationRecord($policyId , $propertyID){
$property = ProertiesPolicyUpdation::where( array( 'property_id' => $propertyID ,'policy_id' => $policyId) )->get();
$data['policy_id'] = $policyId;
$data['property_id'] = $propertyID;
$data['created_at']=date('Y-m-d H:i:s');
$data['updated_at']=date('Y-m-d H:i:s');
$propertyPolicyObj = new ProertiesPolicyUpdation($data);
$propertyPolicyObj->save();
}
/*================================
Function For Removing Images
==================================*/
public function updateImage(Request $request){
$inputsValues = $request->all();
$removeImgId = isset($inputsValues['removeImgId'])?$inputsValues['removeImgId']:'';
$propertyId = $inputsValues['property_id'];
$properties = (new PropertyFieldValue())
->rightjoin('property_type_section_fields', 'property_type_section_fields.id', '=', 'properties_field_values.property_type_section_field_id')
->where('properties_field_values.property_id', $propertyId)
->where('property_type_section_fields.field_identifier', 'basic_feature_image')
->select( 'properties_field_values.id', 'properties_field_values.property_type_section_field_value', 'property_type_section_fields.field_identifier')
->groupBy('properties_field_values.id')
->first();
if( isset($removeImgId) ){
$uploadedImages = json_decode($properties->property_type_section_field_value, true);
if(file_exists(public_path(\Config::get('constants.IMAGE_FOLDER_NAME') . '/' . $uploadedImages[$removeImgId]['image']))) {
unlink(public_path(\Config::get('constants.IMAGE_FOLDER_NAME') . '/' . $uploadedImages[$removeImgId]['image']));
unlink(public_path(\Config::get('constants.IMAGE_FOLDER_NAME') . '/' . 'thumb_' . $uploadedImages[$removeImgId]['image']));
}
unset($uploadedImages[$removeImgId]);
$uploadedImages = array_values($uploadedImages);
foreach($uploadedImages as $key => $value) {
$uploadedImages[$key]['id'] = $key;
}
$uploadedImages;
$data['property_type_section_field_value'] = json_encode($uploadedImages);
$updateQuery = (new PropertyFieldValue())
->where('properties_field_values.id', json_decode($properties->id, true))
->update($data);
return response()->json(['success'=>true,'message'=>'Image is removed successfully', 'data' => json_encode($uploadedImages) ] );
}
}
}
<file_sep>/app/PropertyTypeSectionField.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class PropertyTypeSectionField extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
public function propertytypesectionfieldoption()
{
return $this->hasMany('App\PropertyTypeSectionFieldOption', 'property_type_section_field_id', 'id');
}
public function propertytypesection()
{
return $this->belongsTo('App\PropertyTypeSection', 'property_type_section_id', 'id');
}
public function propertyTypeSectionFieldValue()
{
return (new PropertyTypeSectionField())->hasMany(PropertyTypeSectionFieldOption::class, 'property_type_section_field_id', 'id');
}
}
<file_sep>/app/Http/Controllers/BuyerController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class BuyerController extends Controller
{
/***==== MY PROFILE ====***/
public function myProfile() {
return view('Buyer.my_profile');
}
/***==== CHANGE PASSWORD ====***/
public function changePassword() {
return view('Buyer.change_password');
}
/***==== UPCOMING BOOKING ====***/
public function upcomingBooking() {
return view('Buyer.upcoming_bookings');
}
/***==== PAST BOOKING ====***/
public function pastBooking() {
return view('Buyer.past_bookings');
}
}
<file_sep>/app/PropertyReviews.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PropertyReviews extends Model
{
protected $table = 'property_reviews';
protected $fillable = [
'property_id', 'rating_from_user', 'rating_to_user', 'rating', 'reason_for_rating', 'comments', 'comment_type', 'booking_id'
];
/*===========================================
Get Property Review With user information
Param 1 : Property Id
Join : User
=============================================*/
public function getReviewOfBuyer( $propertyId ){
return $this
->leftjoin('users', 'users.id', 'property_reviews.rating_from_user' )
->where(array('property_reviews.property_id' => $propertyId, 'property_reviews.comment_type' => 1 ))
->select( 'property_reviews.comments', 'property_reviews.rating', 'property_reviews.reason_for_rating', 'property_reviews.created_at', 'users.id as user_id','users.first_name', 'users.last_name', 'users.image')
->orderBy('property_reviews.created_at', 'DESC')
->take(6)
->get()
->toArray();
}
/*===========================================
Get Property Review With user information
Param 1 : Property Id
Join : User
=============================================*/
public function getTotalReviewOfBuyer( $propertyId ){
return $this
->where(array('property_reviews.property_id' => $propertyId, 'property_reviews.comment_type' => 1 ))
->select( 'property_reviews.rating')
->get()
->toArray();
}
/*===========================================
Get Booking id of Buyer
Param 1 : $propertyId , $userId, $bookingId
=============================================*/
public function getBookingId( $propertyId , $userId, $bookingId ){
return $this
->where(array('property_reviews.property_id' => $propertyId, 'property_reviews.comment_type' => 1, 'property_reviews.rating_from_user'=>$userId, 'property_reviews.booking_id'=>$bookingId ))
->value('booking_id');
}
/*===========================================
Get Booking id of Buyer
Param 1 : $propertyId , $userId, $bookingId
=============================================*/
public function getIdReviewOfSeller( $propertyId , $userId, $bookingId ){
return $this
->where(array('property_reviews.property_id' => $propertyId, 'property_reviews.comment_type' => 2, 'property_reviews.rating_from_user'=>$userId, 'property_reviews.booking_id'=>$bookingId ))
->value('booking_id');
}
/*===========================================
Get Property Review With user information
Param 1 : Property Id
Join : User
=============================================*/
public function getReviewOfSeller( $propertyId ){
return $this
->leftjoin('users', 'users.id', 'property_reviews.rating_from_user' )
->where(array('property_reviews.property_id' => $propertyId, 'property_reviews.comment_type' => 2 ))
->select( 'property_reviews.comments', 'property_reviews.rating', 'property_reviews.reason_for_rating', 'property_reviews.created_at', 'users.first_name', 'users.last_name', 'users.image')
->orderBy('property_reviews.created_at', 'DESC')
->get()
->toArray();
}
/*===========================================
Get Property Review With user information
Param 1 : Property Id
Join : User
=============================================*/
public function getReviewOfSellerToBuyer( $userId, $offSet ){
return $this
->leftjoin('users', 'users.id', 'property_reviews.rating_from_user' )
->where(array('property_reviews.rating_to_user'=>$userId, 'comment_type'=>2))
->select('property_reviews.rating','property_reviews.reason_for_rating','property_reviews.comments','property_reviews.created_at','users.first_name','users.last_name', 'users.image')
->take(4)
->skip($offSet)
->get()
->toArray();
}
/*===========================================
Get Property Review With user information
Param 1 : Property Id
Join : User
=============================================*/
public function ajaxGetReviewOfBuyer( $propertyId, $offset ){
return $this
->leftjoin('users', 'users.id', 'property_reviews.rating_from_user' )
->where(array('property_reviews.property_id' => $propertyId, 'property_reviews.comment_type' => 1 ))
->select( 'property_reviews.comments', 'property_reviews.rating', 'property_reviews.reason_for_rating', 'property_reviews.created_at', 'users.first_name', 'users.last_name', 'users.image')
->orderBy('property_reviews.created_at', 'DESC')
->skip($offset)
->take(2)
->get()
->toArray();
}
}
<file_sep>/app/Http/Controllers/CommonController.php
<?php
namespace App\Http\Controllers;
use App\TemplateLog;
use App\User;
use App\PropertyReviews;
use App\Bookings;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use App\Http\Requests\UserRegistration;
use App\Http\Requests\Seller\PropertyReviewsRequest;
use Auth;
use DB;
class CommonController extends Controller
{
/*** ===== Test function ======***/
public function testval(Request $request){
if($request->all()){
pr($request->all());
$rules = [
'no1' => 'required',
'jo2' => 'numeric',
];
$this->validate($request,$rules);
}
return view('testval');
}
/***==== PROPERTY DETAIL ====***/
public function index(){
return view('Common.property_detail');
}
/***==== FORGOT PASSWORD ====***/
public function forgotPassword() {
return view('Common.forgot_password');
}
/***==== ABOUT US ====***/
public function aboutUs() {
return view('Common.about_us');
}
/***==== CONTACT US ====***/
public function contactUs() {
return view('Common.contact_us');
}
/***==== 404 NOT FOUND ====***/
public function notFound404() {
return view('Common.404');
}
/*=====================
User Registration
=======================*/
protected function userRegister(UserRegistration $request) {
$input = $request->all();
$registration = User::create([
'first_name' => $input['first_name'],
'last_name' => $input['last_name'],
'email' => $input['email'],
'registration_token' => md5(time()),
'is_verified' => 0,
'role' => 2,
'password' => <PASSWORD>($input['<PASSWORD>']),
'mobile_number' => $input['mobile_number'],
]);
$message = array();
$message['registration_token'] = $registration->registration_token;
$message['email'] = $registration->email;
$message['subject'] = "Email Verification";
$templateLog = (new TemplateLog())->where(['template_log_id' => '1'])->first();
$userName = $input['first_name'].' '.$input['last_name'];
$Link = "<a href=".route('verify.useremail').'?verify_link='.$message['registration_token'].">Click Here </a>";
$messagee = $templateLog->message;
$userTaskDes = array("#user_name#","#click_here#");
$userTaskRep = array($userName,$Link);
$newTaskDes = str_replace($userTaskDes,$userTaskRep,$messagee);
$messageBody = $newTaskDes;
//pr($messageBody,1);
\Mail::send('email.email', array('body' => $messageBody), function($email) use ($message){
$email->to($message['email'])->subject($message['subject']);
});
return redirect('/login')->with('message', 'You have been registered successfully. Please check your mail to verify the account.');
}
/*======================
Verify User Profile
========================*/
public function verifyUserEmail(Request $request){
/*$v = Validator::make($request->all(), [
'verify_link' => 'exists:users,is_verified',
],
[
'verify_link.exists' => 'Sorry, This email is already verified',
]
);*/
$input = $request->all();
$user = User::where( array( 'registration_token' => $input['verify_link'],'is_verified' => '0') )->first();
if(count($user) > 0) {
if ($user->update(array('is_verified' => 1))) {
return redirect('/login')->with('message', 'Your email is verified successfully.');
} else {
return redirect('/login')->with('error', 'Something wend wrong.');
}
}else{
Session::Flash('verify_link','Sorry, This email is already verified');
return redirect('/login');
}
}
/*========================
Save Property Review
==========================*/
public function savePropertyReview(PropertyReviewsRequest $request){
$input = $request->all();
if($input['commentType']==1){
$ratingTo = Bookings::where(array('bookings.booking_id'=> $input['booking_id']))->value('property_owner_id');
}
if($input['commentType']==2){
$ratingTo = Bookings::where(array('bookings.booking_id'=> $input['booking_id']))->value('user_id');
}
$data['property_id'] = $input['propertyid'];
$data['rating_from_user'] = isset(Auth::user()->id) ? Auth::user()->id : '' ;
$data['rating_to_user'] = $ratingTo;
$data['rating'] = $input['rating'];
$data['reason_for_rating'] = $input['reason_for_rating'];
$data['comments'] = $input['comments'];
$data['comment_type'] = $input['commentType'];
$data['booking_id'] = $input['booking_id'];
$propertyReviewsObj = new PropertyReviews($data);
if($propertyReviewsObj->save()){
return response()->json(['success'=>true, 'message' => 'Review is submitted successfully']);
}else{
return response()->json(['success'=>false]);
}
}
/*=======================================
Get All Reviews Of Property By Vikas
==========================================*/
public function allReviewsOfProperty(Request $request){
$input = $request->all();
$propertyId = $input['propertyId'];
$offset = isset($input['offset']) ? $input['offset'] : 0;
$propertyReviews = (new PropertyReviews())->ajaxGetReviewOfBuyer( $propertyId, $offset );
return response()->json($propertyReviews);
}
/*======================================
Function For Reset Password By Link
=======================================*/
public function resetPasswordByLink(Request $request){
$input = $request->all();
$validation = Validator::make($input, [
'email' => 'exists:users,email',
],
[
'email.exists' => 'We can not find a user with that e-mail address.',
]
);
if ($validation->fails()){
return redirect()->back()->withErrors($validation->errors());
}
$token = User::where(array('email'=>$input['email']))->value('registration_token');
DB::table('password_resets')->insert(
['email' => $input['email'], 'token' => $token]
);
$user = (new User())->where(['email' => $input['email']])->first();
$message = array();
$message['email'] = $input['email'];
$message['subject'] = "Reset Password";
$templateLog = (new TemplateLog())->where(['template_log_id' => '2'])->first();
$userName = $user->first_name.' '.$user->last_name;
$Link = "<a href=".route('reset.password').'?token='.$token.">Click Here </a>";
$messagee = $templateLog->message;
$userTaskDes = array("#user_name#","#click_here#");
$userTaskRep = array($userName,$Link);
$newTaskDes = str_replace($userTaskDes,$userTaskRep,$messagee);
$messageBody = $newTaskDes;
\Mail::send('email.email', array('body' => $messageBody), function($email) use ($message){
$email->to($message['email'])->subject($message['subject']);
});
return redirect()->back()->with('message', 'Please check your email to change the password');
}
/*========================================================
Function For Loading the Form for Filling New Password
==========================================================*/
public function changePasswordView(Request $request){
$inputs = $request->all();
$validation = Validator::make($inputs, [
'token' => 'exists:password_resets,token',
],
[
'token.exists' => 'This Link is expired.',
]
);
if($validation->fails()){
return redirect('password/reset')->with('linkExists', 'This Link is expired.');//->back()->withErrors($validation->errors());
}
$token = $inputs['token'];
return view('auth.passwords.reset',compact('token'));
}
/*=========================================
Function For Change Password Final Step
===========================================*/
public function resetPasswordFinalStep(Request $request){
$inputs = $request->all();
$email = User::where( array( 'registration_token' => $inputs['token'] ) )->value('email');
$validation = Validator::make($inputs, [
'token' => 'exists:password_resets,token',
'password' => '<PASSWORD>|min:12|regex:/^(?=.*[a-z])(?=.*\d).+$/',
'password_confirmation' => 'required|same:password',
],
[
'token.exists' => 'Token is not valid.',
'password.regex' => 'Password should contain at least 1 number and 1 alphabet.',
]
);
if($validation->fails()){
return redirect()->back()->withErrors($validation->errors());//->back()->withErrors($validation->errors());
}
DB::table('password_resets')->where(array('email' => $email))->delete(); // Delete token from Table
$user = User::where( array( 'email' => $email ) )->first();
$data['password']=<PASSWORD>($inputs['<PASSWORD>']);
if($user->update( $data )){
return redirect('login')->with('message', 'Your password is changed successfully');
}
}
}
<file_sep>/database/migrations/2017_10_24_043437_add_is_booked_to_property_availaibility_dates.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddIsBookedToPropertyAvailaibilityDates extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('property_availaibility_dates', function($table) {
$table->boolean('is_booked')->comment = "0->Not Booked, 1->Booked";
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('property_availaibility_dates', function($table) {
$table->dropColumn('is_booked');
});
}
}
<file_sep>/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
/*
Route::get('/', function () {
return view('Propertytype.home');
});*/
Route::any('sendEmail','HomeController@sendEmail')->name('sendEmail');
Auth::routes();
Route::get( 'verify-useremail', 'CommonController@verifyUserEmail')->name('verify.useremail');
Route::post( 'user-register', 'CommonController@userRegister')->name('user.register');
Route::post( 'save-property-reviews', 'CommonController@savePropertyReview')->name('save-property-reviews');
Route::get('all-reviews-of-property','CommonController@allReviewsOfProperty')->name('all-reviews-of-property');
Route::post('/reset-password', 'CommonController@resetPasswordByLink')->name('reset.password.custom');
Route::get( '/reset-password-view', 'CommonController@changePasswordView')->name('reset.password');
Route::post('/reset-password-final-step', 'CommonController@resetPasswordFinalStep')->name('password.request.final.step');
Route::get('test', function () {
return view('test');
});
Route::any('testval', 'CommonController@testval')->name('testval');
Route::get('', function () {
return view('design.property_detail');
});
Route::get('/design/property-detail', function () {
return view('design.property_detail');
});
Route::get('/design/my-properties', function () {
return view('design.my_properties');
});
//Buyer routes
Route::get('buyer/my-profile', 'BuyerController@myProfile')->name('buyer-profile');
Route::get('buyer/change-password','BuyerController@changePassword')->name('buyer-change-password');
Route::get('buyer/upcoming-booking','BuyerController@upcomingBooking')->name('buyer-upcoming-booking');
Route::get('buyer/past-booking','BuyerController@pastBooking')->name('buyer-past-booking');
// Common Routes
Route::get('common/property-details', 'CommonController@index')->name('property-details');
Route::get('common/forgot-password', 'CommonController@forgotPassword')->name('forgot-password');
Route::get('common/about-us', 'CommonController@aboutUs')->name('about-us');
Route::get('common/contact-us', 'CommonController@contactUs')->name('contact-us');
Route::get('common/404', 'CommonController@notFound404')->name('404');
Route::get('cronjob', 'CronjobController@index')->name('cronjob');
Route::get('not-approved-property', 'CronjobController@maiToNotAprovedProperty')->name('not.approved.property');
Route::get('not-approved-properties', 'CronjobController@maiToNotAprovedPropertySecond')->name('not.approved.properties');
Route::get('approved-property-cancel', 'CronjobController@approvedPropertyMail')->name('approved.property.cancel');
Route::get('/', 'PropertyController@index')->name('home');
Route::get('/search-result', 'PropertyController@propertyIndex')->name('search.result');
Route::get('/search-result-ajax', 'PropertyController@propertyIndexAjax')->name('search.result.ajax');
Route::any('/property-detail', 'PropertyController@propertyDetail')->name('property.detail');
Route::Post('/book-property/', 'PropertyController@bookProperty')->name('book.property');
Route::get('/success/{token}', 'PropertyController@approvedBooking')->name('success');
Route::get('/thanks', 'PropertyController@thanks')->name('thanks');
Route::get('/seller-properties-at-detail-page', 'PropertyController@sellerProperties')->name('seller-properties-at-detail-page');
Route::any('seller-profile/', 'Seller\SellerProperty@sellerprofile')->name('seller.profile');
Route::group(['middleware' => 'auth'], function() {
Route::group(['middleware' => 'admin'], function()
{
Route::resource('propertytype', 'Admin\PropertyTypeController');
Route::get('/change-password', 'Admin\AdminProfile@changePasswordView')->name('change-password-view');
Route::post('/change-password', 'Admin\AdminProfile@ChangeAdminPassword')->name('change-password');
Route::get('/PropertyTypeSectionField/create/{propertysectionid}/propertytype{propertypeid}', 'Admin\PropertyTypeSectionFieldController@create')->name('PropertyTypeSectionFieldCreate');
Route::Post('/PropertyTypeSectionField/store/', 'Admin\PropertyTypeSectionFieldController@store')->middleware('web')->name('PropertyTypeSectionFieldStore');
Route::get('PropertyTypeSectionField/destroyPropertySection/{id}', 'Admin\PropertyTypeSectionFieldController@destroyPropertySection')->name('PropertyTypeSectionDestroy');
Route::get('PropertyTypeSectionField/destroyPropertyTypeSectionField/{id}', 'Admin\PropertyTypeSectionFieldController@destroyPropertyTypeSectionField')->name('PropertyTypeSectionFieldDestroy');
Route::get('PropertyTypeSectionField/update/{id}', 'Admin\PropertyTypeSectionFieldController@update')->name('PropertyTypeSectionFieldUpdate');
Route::get('PropertyTypeSectionField/singlefieldedit/{field_id}', 'PropertyTypeSectionFieldController@singlefieldedit')->name('PropertyTypeSectionFieldSinglefieldedit');
Route::get('PropertyTypeSectionField/order/', 'Admin\PropertyTypeSectionFieldController@order')->name('PropertyTypeSectionFieldOrder');
Route::post('checkSectionBeforeRemove/{id?}', 'Admin\PropertyTypeSectionFieldController@checkSectionBeforeRemove')->name('checkSectionBeforeRemove');
});
//Seller routes
Route::group(['middleware' => 'seller'], function()
{
Route::get('seller/my-properties', 'Seller\SellerProperty@index')->name('seller-properties');
Route::get('seller-property-detail','Seller\SellerProperty@propertyDetail')->name('seller-property-detail');
Route::get('seller/my-profile', 'Seller\SellerProfile@myProfile')->name('seller-profile');
Route::post('seller/edit-profile','Seller\SellerProfile@editProfile')->name('edit-profile');
Route::get('seller/change-password-view','Seller\SellerProfile@changePasswordView')->name('seller-change-password-view');
Route::post('seller/change-password','Seller\SellerProfile@changeSellerPassword')->name('change-seller-password');
Route::get('seller/upcoming-properties','Seller\SellerProperty@upcomingProperties')->name('upcoming-properties');
Route::get('seller/booked-upcoming-properties','Seller\SellerProperty@bookedUpcomingProperties')->name('booked-upcoming-properties');
Route::get('seller/past-booking-properties','Seller\SellerProperty@pastBookingProperties')->name('past-booking-properties');
Route::get('seller/booked-past-booking-properties','Seller\SellerProperty@bookedPastBookingProperties')->name('booked-past-booking-properties');
/********************** Pending Booking **************/
Route::get('seller/pending-approval-booking-properties','Seller\SellerProperty@bookedPendingBookingProperties')->name('pending-approval-booking-properties');
Route::get('seller/pending-properties','Seller\SellerProperty@pendingProperties')->name('pending-properties');
/********************** Pending Booking **************/
Route::get('seller/rejected-approval-booking-properties','Seller\SellerProperty@bookedRejectedBookingProperties')->name('rejected-approval-booking-properties');
Route::get('seller/approved-booking-properties/{id?}','Seller\SellerProperty@bookedApproveProperties')->name('approved-booking-properties');
Route::get('seller/approved-properties','Seller\SellerProperty@approveProperties')->name('approved-properties');
Route::get('seller/rejected-booking-properties','Seller\SellerProperty@rejectedBookingProperties')->name('rejected-booking-properties');
Route::get('seller/cancel-booking/','Seller\SellerProperty@cancelBooking')->name('cancel-booking');
Route::get('seller/cancel-booking/{id}','Seller\SellerProperty@cancelBooking')->name('cancel-booking');
Route::get('seller/approve-booking/','Seller\SellerProperty@approveBooking')->name('approve-booking');
Route::get('seller/approve-booking/{id}','Seller\SellerProperty@approveBooking')->name('approve-booking');
Route::get('/property/information/{property_type_id?}', 'Seller\SellerProperty@propertyInformation')->name('property_information');
Route::post('/property/information/store', 'Seller\SellerProperty@storePropertyTypeData')->name('store.property.type.data');
Route::get('/property/availaibility/show/{propertyTypesId}', 'Seller\SellerProperty@showPropertyAvailability')->name('show.property.availaibility');
Route::post('/property/availaibility/store', 'Seller\SellerProperty@storePropertyAvailabilityData')->name('store.property.availaibility.data');
Route::match(['get', 'post'],'/property/index/{property_type_id?}', 'PropertyController@propertyIndex')->name('property.index');
Route::get('/property/{property_id?}/edit', 'Seller\SellerProperty@propertyEdit')->name('property.edit');
Route::post('/property/update', 'Seller\SellerProperty@propertyUpdate')->name('property.update');
Route::any('calendar-events/{id?}', 'Seller\SellerProperty@getCalenderEvents')->name('calendar.events');
Route::any('calendar-events-date/{id?}/{date?}', 'Seller\SellerProperty@getCalenderEventsDates')->name('calendar.events.date');
Route::any('block-unblock-dates/{id?}{is_blocked}/', 'Seller\SellerProperty@blockunblockdates')->name('block-unblock-dates');
Route::any('update-images', 'Seller\SellerProperty@updateImage')->name('update-images');
Route::any('seller-detail/', 'Seller\SellerProperty@sellerDetail')->name('seller.detail');
Route::any('buyer-detail', 'Seller\SellerProperty@buyerDetail')->name('buyer.detail');
Route::get('seller/review-from-seller', 'Seller\SellerProperty@reviewFromSeller')->name('review-from-seller');
});
});
//Route::get('PropertyTypeSectionField/singlefieldedit/{field_id}', 'PropertyTypeSectionFieldController@singlefieldedit')->name('PropertyTypeSectionFieldSinglefieldedit');
//Route::get('PropertyTypeSectionField/order/', 'PropertyTypeSectionFieldController@order')->name('PropertyTypeSectionFieldOrder');
//Route::get('PropertyTypeSectionField/order/', 'PropertyTypeSectionFieldController@order')->name('PropertyTypeSectionFieldOrder');
<file_sep>/app/Http/Controllers/Admin/PropertyTypeSectionFieldController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\PropertyType;
use App\PropertyTypeSection;
use App\InputFieldType;
use App\Validation;
use App\User;
use App\PropertyTypeSectionField;
use App\PropertyTypeSectionFieldOption;
use Mockery\CountValidator\Exception;
use Validator;
use Illuminate\Support\Facades\DB;
class PropertyTypeSectionFieldController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(){
$PropertyTypes = PropertyType::Paginate(10);
return view('Propertytype.index', compact('PropertyTypes'));
}
public function order(Request $request) {
$custom_query_part1 = "";
$custom_query_part2 = implode(",",$request->section_field_id);
$order_id_counter = 1;
foreach($request->section_field_id as $value) {
$custom_query_part1 .= " WHEN id = $value THEN $order_id_counter ";
$order_id_counter++;
}
$main_query = "UPDATE `property_type_section_fields` SET `order_id` = CASE
$custom_query_part1
ELSE `order_id`
END
WHERE id in ($custom_query_part2)";
DB::update($main_query);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create($propertysectionid, $propertypeid) {
$section_fields = PropertyTypeSectionField::with(['propertytypesectionfieldoption' => function ($query) {
}])
->where('property_type_section_id', $propertysectionid)->orderBy('order_id', 'asc')->get();
$InputFieldTypes = InputFieldType::all();
$Validations = Validation::all();//pr($Validations->toArray(),1);
return view('admin/property_type_section_field.create', compact('InputFieldTypes', 'Validations', 'propertysectionid', 'section_fields','propertypeid'));
}
public function singlefieldedit($field_id){
$InputFieldTypes = InputFieldType::all();
$Validations = Validation::all();
$section_field = PropertyTypeSectionField::with(['propertytypesectionfieldoption' => function ($query) {
}])->where('id', $field_id)->get();
$section_field = $section_field->toArray();
$section_field = $section_field[0];
return view('PropertyTypeSectionField.singlefieldedit', compact('InputFieldTypes', 'section_field', 'Validations'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request) {
try {
$PropertyTypeSection_data = PropertyTypeSection::find($request->property_type_section_id);
$PropertyTypeSection_data = PropertyTypeSection::find($request->property_type_section_id);
$propertytypesection_id_arr = PropertyTypeSection::where('property_type_id', $PropertyTypeSection_data->property_type_id)->get();
$arr_propertytypesectionid = array();
foreach ($propertytypesection_id_arr as $value) {
$arr_propertytypesectionid[] = $value->id;
}
$arr_propertytypesectionid = implode(",", $arr_propertytypesectionid);
$rules = [
// 'property_type_section_field_name' =>"required|unique:property_type_section_fields,name,NULL,id,property_type_section_id," . $request->property_type_section_id,
//'validations' => 'required',
//'property_type_section_field_name' => 'unique_custom:property_type_section_fields,property_type_section_id,name,, ,
//unique_custom:property_type_section_fields,NULL,NULL,name,property_type_section_id,' . $arr_propertytypesectionid,
'property_type_section_field_name' => 'required',
'property_type_section_field_option_name.*' => 'required',
'selected_field' => 'required',
];
$customMessages = [
'property_type_section_field_name.required' => 'The Field Name is required',
//'validations.required' => 'Please select atleast 1 of the field validations',
'property_type_section_field_option_name.*required' => 'The Section Field Option is Required',
'selected_field.required' => 'The Field Type is Required',
'property_type_section_field_name.unique_custom' => 'The Field Name must be unique, you have already defined the field with same name',
];
$this->validate($request, $rules, $customMessages);
$property_type_section_field_name = $request->property_type_section_field_name;
$selected_field = $request->selected_field;
$validations = $request->validations;
$InputFieldTypes = InputFieldType::all();
$Validations = Validation::all()->toArray();
if (sizeof($Validations)) {
foreach ($Validations as $value) {
$newvalidations[$value["id"]] = $value["validation"];
}
}
if (!$validations) {
$validations = array();
}
$validations = array_flip($validations);
$result = array_intersect_key($newvalidations, $validations);
$validation_string = implode(",", $result);
//echo "validation string is " . $validation_string;
//$validation_string = array_intersect_key($a1,$a2);
$PropertyTypeSectionField = new PropertyTypeSectionField;
$PropertyTypeSectionField->property_type_section_id = $request->property_type_section_id;
$PropertyTypeSectionField->name = $request->property_type_section_field_name;
$PropertyTypeSectionField->display_to_filter = isset($request->display_to_filter) ? 1 : 0;
$PropertyTypeSectionField->input_field_type_id = $request->selected_field;
$PropertyTypeSectionField->validations = $validation_string;
if ($PropertyTypeSectionField->save()) {
if (sizeof($request->property_type_section_field_option_name) > 0) {
$option_counter = 1;
foreach ($request->property_type_section_field_option_name as $field_option_value) {
if ($field_option_value) {
$PropertyTypeSectionFieldOption = new PropertyTypeSectionFieldOption;
$PropertyTypeSectionFieldOption->property_type_section_field_id = $PropertyTypeSectionField->id;
$PropertyTypeSectionFieldOption->display_value = $field_option_value;
$PropertyTypeSectionFieldOption->order_id = $option_counter;
$PropertyTypeSectionFieldOption->save();
}
$option_counter++;
}
}
}
if(!empty($PropertyTypeSection_data->property_type_id)) {
(new PropertyType())->where(['id' => $PropertyTypeSection_data->property_type_id])->update(['updated_at' => date('Y-m-d H:i:s')]);
}
//return view('home');
//return with a success message
//return redirect('/propertytype/')->with('status', 'Property Type Saved successfully');
return redirect()->back()->with('status', 'Section Field Added successfully');
} catch(Exception $e){
//pr($e->getMessage(),1);
}
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id) {
$PropertyType = new PropertyType;
$PropertyTypeSection = new PropertyTypeSection;
//Get all the information associated with given ID
$PropertyType = PropertyType::find($id);
$PropertyTypeSections = PropertyTypeSection::where('property_type_id', $id)->orderBy('order_id', 'asc')->get();
$InputFieldTypes = InputFieldType::all();
$Validations = Validation::all();
//And return to edit.blade.php view file.
return view('Propertytype.edit', compact('PropertyType', 'PropertyTypeSections', 'InputFieldTypes', 'Validations'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id) {
$PropertyTypeSection_data = PropertyTypeSection::find($request->property_type_section_id);
$propertyTypeSectionIds = PropertyTypeSection::where('property_type_id', $PropertyTypeSection_data->property_type_id)->pluck('id')->toArray();
$propertyTypeSectionIds = implode(",",$propertyTypeSectionIds);
$rules = [
//'property_type_section_field_name' => 'unique_custom:property_type_section_fields,name,id,'. $id_value.',property_type_section_id,' . $propertyTypeSectionIds,
'property_type_section_field_name' => 'unique_custom:property_type_section_fields,id,'. $id.',name,property_type_section_id,' . $propertyTypeSectionIds,
//'validations' => 'required',
'property_type_section_field_option_name.*' => 'required',
'selected_field' => 'required',
];
$customMessages = [
'property_type_section_field_name.required' => 'The Field Name is required',
//'validations.required' => 'Please select atleast 1 of the field validations',
'property_type_section_field_option_name.*required' => 'The Section Field Option is Required',
'selected_field.required' => 'The Field Type is Required',
'property_type_section_field_name.unique_custom' => 'The Field Name must be unique, you have already defined the field with same name',
];
$this->validate($request, $rules, $customMessages);
$propertyTypeSectionFieldOptionsIds = PropertyTypeSectionFieldOption::where('property_type_section_field_id', $id)->pluck('id')->toArray(); // vikas
if(isset($request->field_option_id)){
$arr_PropertyTypeSectionFieldOption_diff = array_diff($propertyTypeSectionFieldOptionsIds ,$request->field_option_id);
}else if(!isset($request->field_option_id)){
$empty_arr = array();
$arr_PropertyTypeSectionFieldOption_diff = array_diff($propertyTypeSectionFieldOptionsIds , $empty_arr);
}
if(sizeof($arr_PropertyTypeSectionFieldOption_diff) >0 ) {
PropertyTypeSectionFieldOption::whereIn('id', $arr_PropertyTypeSectionFieldOption_diff)->delete();
}
$inputs = $request->all();
if($request->input('property_type_section_field_name') == 'Feature Image'){
$rules = [
'multipleImagesLimit' => 'required|numeric|min:1',
];
$customMessages = [
'multipleImagesLimit.required' => 'Please Set File Limit',
'multipleImagesLimit.numeric' => 'Please enter the numeric value',
'multipleImagesLimit.min' => 'Please enter minimum 1 value',
];
$this->validate($request, $rules, $customMessages);
}
$property_type_section_field_name = $request->property_type_section_field_name;
$selected_field = $request->selected_field;
$validations = $request->validations;
// pr($validations,1);
$InputFieldTypes = InputFieldType::all();
//pr($request->all(),1);
$Validations = Validation::all()->toArray();
if(sizeof($Validations)) {
foreach($Validations as $value){
$newvalidations[$value["id"]] = $value["validation"];
}
}
if(!isset($validations)) {
$validations = array();
}
$fileLimitsString = '';
$validations = array_flip($validations);
$result = array_intersect_key($newvalidations,$validations);
$validation_string = implode(",",$result);
$validation_string = str_replace("upload_count","",$validation_string);
if(!empty($validations) && !empty($request->multipleImagesLimit)){
$fileLimits = $request->multipleImagesLimit;
$fileLimitsString = ',upload_count:'.$fileLimits;
}else if(empty($validations) && !empty($request->multipleImagesLimit)){
$fileLimits = $request->multipleImagesLimit;
$fileLimitsString = 'upload_count:'.$fileLimits;
}
$validation_string = $validation_string.''.$fileLimitsString;
$PropertyTypeSectionField = PropertyTypeSectionField::find($id);
$PropertyTypeSectionField->property_type_section_id = $request->property_type_section_id;
$PropertyTypeSectionField->name = $request->property_type_section_field_name;
$PropertyTypeSectionField->input_field_type_id = $request->selected_field;
$PropertyTypeSectionField->display_to_filter = isset($request->display_to_filter) ? 1 : 0;
$PropertyTypeSectionField->validations = $validation_string;
if($PropertyTypeSectionField->save()) {
$counter = 0;
$PropertyTypeSectionFieldOptionCounter = 1;
if(sizeof($request->property_type_section_field_option_name) > 0) {
$custom_query_part1 = "";
$custom_query_part2 = "";
foreach($request->property_type_section_field_option_name as $value) {
if($request->field_option_id[$counter] && $value){
$option_id = $request->field_option_id[$counter];
$custom_query_part1 .= " WHEN id = $option_id THEN $PropertyTypeSectionFieldOptionCounter ";
$custom_query_part2 .= " WHEN id = $option_id THEN " . "'" .$value . "'";
$existingOptionid_arr[] = $request->field_option_id[$counter];
} else if(!$request->field_option_id[$counter] && $value) {
$PropertyTypeSectionFieldOption = new PropertyTypeSectionFieldOption;
$PropertyTypeSectionFieldOption->display_value = $value;
$PropertyTypeSectionFieldOption->order_id = $PropertyTypeSectionFieldOptionCounter;
$PropertyTypeSectionFieldOption->property_type_section_field_id = $id;
$PropertyTypeSectionFieldOption->save();
}
$counter++;
$PropertyTypeSectionFieldOptionCounter++;
}
if(isset($existingOptionid_arr)) {
$custom_query_part3 = implode(",", $existingOptionid_arr);
$main_query = "UPDATE property_type_section_field_options
SET order_id = CASE
$custom_query_part1
ELSE order_id END,
display_value = CASE
$custom_query_part2
ELSE display_value
END
WHERE id IN ($custom_query_part3);";
//pr($main_query,1);
DB::update($main_query);
}
}
if(!empty($PropertyTypeSection_data->property_type_id)) {
(new PropertyType())->where(['id' => $PropertyTypeSection_data->property_type_id])->update(['updated_at' => date('Y-m-d H:i:s')]);
}
}
//return with a success message
//return redirect('/propertytype/')->with('status', 'Property Type Field Updated successfully!');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroyPropertySection($id) {
$propertyTypeSection = PropertyTypeSection::find($id)->delete();
if($propertyTypeSection){
return response()->json(['success'=>true]);
} else{
return response()->json(['success'=>false]);
}
}
public function destroyPropertyTypeSectionField($id) {
$PropertyTypeSectionField = PropertyTypeSectionField::find($id);
if(!$PropertyTypeSectionField->field_identifier){
if($PropertyTypeSectionField->input_field_type_id == (2||3)) {
$deletedRows = PropertyTypeSectionFieldOption::where('property_type_section_field_id', $id)->delete();
}
$PropertyTypeSectionField->delete();
return redirect()->back()->with('status', 'Section Field Deleted successfully');
} else{
return redirect()->back()->with('status', 'Thats a permanent field, you Are Not Allowed to Delete');
}
}
public function checkSectionBeforeRemove(Request $request, $id){
$data = (new PropertyTypeSectionField())
->join('properties_field_values','properties_field_values.property_type_section_field_id','=','property_type_section_fields.id')
->where(['property_type_section_fields.property_type_section_id' => $id])
->get(['property_type_section_id','property_id'])->toArray();
if(!empty($data)){
$ary = [
'success' => '100',
'data' => count($data),
];
}else{
$ary = [
'success' => '0',
'data' => '0',
];
}
return $ary;
}
}
<file_sep>/database/seeds/SellerSeeder.php
<?php
use Illuminate\Database\Seeder;
class SellerSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//DB::table('users')->truncate();
/*DB::table('users')->insert([
'first_name' => 'Jorge',
'last_name' => 'Seller',
'email' => '<EMAIL>',
'password' => bcrypt('<PASSWORD>'),
'is_verified' => 1,
'role' => 2
]);*/
}
}
<file_sep>/app/PropertyTypeSection.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use DB;
class PropertyTypeSection extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = [
'property_type_id', 'name','order_id'
];
public function propertytypesectionfield(){
return $this->hasMany('App\PropertyTypeSectionField', 'property_type_section_id', 'id');
}
public function propertytype() {
return $this->belongsTo('App\PropertyType', 'property_type_id', 'id');
}
/*=====================================================================
Get Property Filters Using Property id
Param 1 : Property type Id
Join With : property_type_section_fields, properties_field_values
========================================================================*/
/*public function getPropertyFilters( $propertyTypesId, $min_price, $max_price ){
return $this
->join( 'property_type_section_fields', 'property_type_sections.id', '=', 'property_type_section_fields.property_type_section_id' )
->join( 'properties_field_values', 'properties_field_values.property_type_section_field_id', '=', 'property_type_section_fields.id' )
->where( array( 'property_type_sections.property_type_id' => $propertyTypesId, 'property_type_section_fields.display_to_filter' => 1 ) )
// ->select( 'property_type_section_fields.id', 'property_type_section_fields.name','property_type_section_fields.property_type_section_id')
->pluck( 'property_type_section_fields.id')
->toArray();
}*/
/*public function getPropertyFilters( $propertyTypesId, $min_price, $max_price ){
return $this
->join( 'property_type_section_fields', 'property_type_sections.id', '=', 'property_type_section_fields.property_type_section_id' )
->join( 'properties_field_values', 'properties_field_values.property_type_section_field_id', '=', 'property_type_section_fields.id' )
->join( 'property_type_section_field_options', 'properties_field_values.property_type_section_field_id', '=', 'property_type_section_field_options.property_type_section_field_id' )
->where( array( 'property_type_sections.property_type_id' => $propertyTypesId, 'property_type_section_fields.display_to_filter' => 1 ) )
->whereIn( 'property_type_section_fields.input_field_type_id',[2,3,11] )
->select( 'property_type_section_field_options.display_value', 'properties_field_values.id', 'property_type_section_fields.name', 'properties_field_values.property_type_section_field_value','field_identifier' )
->distinct()
->get()
->toArray();
}*/
public function getPropertyFilters( $propertyTypesId, $min_price, $max_price ){
return $this
->leftjoin( 'property_type_section_fields', 'property_type_sections.id', '=', 'property_type_section_fields.property_type_section_id' )
->join( 'property_type_section_field_options', 'property_type_section_fields.id', '=', 'property_type_section_field_options.property_type_section_field_id' )
//->join( 'properties_field_values', 'properties_field_values.property_type_section_field_id', '=', 'property_type_section_fields.id' )
// ->join( 'property_type_section_field_options', 'properties_field_values.property_type_section_field_id', '=', 'property_type_section_field_options.property_type_section_field_id' )
->where( array( 'property_type_sections.property_type_id' => $propertyTypesId, 'property_type_section_fields.display_to_filter' => 1 ) )
->whereIn( 'property_type_section_fields.input_field_type_id',[2,3,11] )
->select( 'property_type_section_field_options.id','property_type_section_field_options.display_value', 'property_type_section_fields.name' )
// ->groupBy('properties_field_values.property_type_section_field_value')
->get()
->toArray();
}
/*public function getPropertyFilters( $propertyTypesId, $min_price, $max_price ){
return $this
->join( 'property_type_section_fields', function($join) {
$join->on('property_type_sections.id', '=', 'property_type_section_fields.property_type_section_id')
->where('field_identifier', '=', 'basic_price');
})
->join( 'properties_field_values', 'properties_field_values.property_type_section_field_id', '=', 'property_type_section_fields.id' )
->where( array( 'property_type_sections.property_type_id' => $propertyTypesId, 'property_type_section_fields.display_to_filter' => 0 ) )
->where(function($query) use ($min_price,$max_price) {
if( (isset($min_price)) && (isset($max_price))) {
$query->where('field_identifier', '=', 'basic_price')->whereBetween('properties_field_values.property_type_section_field_value', [(int)$min_price, (int)$max_price]);
}
})
// ->whereBetween('properties_field_values.property_type_section_field_value', [(int)$min_price, (int)$max_price])
->select( 'properties_field_values.id', 'property_type_section_fields.name', 'properties_field_values.property_type_section_field_value', 'field_identifier' )
->get()
->toArray();
}*/
}
<file_sep>/database/migrations/2017_12_14_050606_add_through_approval_to_bookings.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddThroughApprovalToBookings extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('bookings', function (Blueprint $table) {
$table->boolean('through_approval')->after('is_approved');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('bookings', function (Blueprint $table) {
$table->dropColumn('through_approval');
});
}
}
<file_sep>/app/Http/Requests/BookingPropertyRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class BookingPropertyRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'total_amount' => 'required|numeric',
'start_date' => 'required|',
'end_date' => 'required|after_or_equal:start_date',
];
}
/*=====================================
Function to display Custom Messages
========================================*/
public function messages() {
return [
'start_date.required' => 'Please Enter Start Date.',
'end_date.required' => 'Please Enter End Date.',
'end_date.after' => 'End Date must be greater than Start Date.'
];
}
}
<file_sep>/app/Http/Requests/Admin/ChangePassword.php
<?php
namespace App\Http\Requests\Admin;
use Illuminate\Foundation\Http\FormRequest;
class ChangePassword extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'old_password' => '<PASSWORD>|',
'password' => array(
'required',
'min:6',
'regex:/^(?=.*[a-z])(?=.*\d).+$/',
),
'password_confirmation' => 'required|same:password',
];
}
/*=====================================
Function to display Custom Messages
========================================*/
public function messages() {
return [
'old_password' => 'Please Enter Old Password.',
'password' => '<PASSWORD> Enter New Password.',
'password.min' => 'Password should be at least 6 characters long.',
'password_confirmation' => 'Please Enter Confirmed Password.',
'password.regex' => 'Password should contain at least 1 number and 1 alphabet.',
'password_confirmation.same' => 'New password and confirm password do not match.Please enter both again.',
];
}
}
| 5fcc2c947b712ab73ed110afa8d94f5de2be5744 | [
"PHP"
] | 54 | PHP | amarjitbh/mitsShare | 27eb003f175a2e1c54fadf2aeeea811ba3ab07ed | 8be8bd7440c11f96254ccf7299d287155415e284 |
refs/heads/master | <repo_name>jlianphoto/theEight<file_sep>/js/util.js
(function(){
var $ = window.$ = function(el){
return new $.prototype.init(el);
}
$.prototype = {
init : function(el){
var els = document.querySelectorAll(el);
for (var i = 0; i < els.length; i++) {
this[i] = els[i];
}
this.length = els.length;
return this;
},
show : function(){
for (var i = 0; i < this.length; i++) {
this[i].style.display = "block";
}
return this;
},
hide : function(){
for (var i = 0; i < this.length; i++) {
this[i].style.display = "none";
}
return this;
},
css : function(k,v){
for (var i = 0; i < this.length; i++) {
this[i].style[k] = v;
}
return this;
}
}
$.prototype.init.prototype = $.prototype;
})()<file_sep>/js/Game.js
window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
var analyser ;
var timer ;
function Game(){
this.role = new Role();
this.blocks = [];
}
Game.prototype.init = function(){
this.die = false;
this.voiceSize = 0;
this.role.h=140;
for(var i = 0, length1 = this.blocks.length; i < length1; i++){
document.querySelector('.stage').removeChild(this.blocks[i].block);
}
this.blocks = [];
var block = new Block(320 , 140 , 0);
this.blocks.push(block);
};
Game.prototype.gameStart = function() {
this.init();
AudioAPI.start().then(a => {
analyser = a;
this.startGetVoiceSize();
})
};
Game.prototype.startGetVoiceSize = function() {
let voiceSize = AudioAPI.getVoiceSize(analyser)
this.voiceSize = voiceSize/1000;
if (!this.die) {
if (this.voiceSize>0.5) {
//jump
if (this.voiceSize > 30) {
this.role.jump(this.voiceSize-30);
}
//move
this.role.move();
this.blocks.forEach(function(item){
item.move(this.voiceSize/100);
}.bind(this));
}else{
this.role.static();
this.role.jump(0);
}
}
// jumpDown
if (this.die || (this.blocks[0].deltaX > this.blocks[0].w+288 && this.blocks[1].deltaX < 252 && this.voiceSize<0.5)) {
this.role.jumpDown()
}
// if delete block
if (this.blocks[0].deltaX>this.blocks[0].w+320) {
document.querySelector('.stage').removeChild(this.blocks[0].block);
this.blocks.shift();
}
//change role height
if (this.blocks[1] && this.blocks[1].deltaX>252) {
this.role.h = this.blocks[1].h;
}
// create block
var len = this.blocks.length-1;
if (this.blocks[len].deltaX>this.blocks[len].w+60) {
var block = new Block();
this.blocks.push(block);
}
//game over
if (((this.blocks[1] && this.blocks[1].deltaX>252) || this.blocks[0].deltaX > this.blocks[0].w+252) && this.role.h<this.blocks[1].h/2) {
this.die = true;
}
//game over
if (this.role.h <0) {
cancelAnimationFrame(timer);
$mask.show();
$mask.css("backgroundColor","rgba(255,255,255,0.7)");
$btnAgain.show();
}else{
timer = requestAnimationFrame(this.startGetVoiceSize.bind(this));
}
};
<file_sep>/js/Block.js
function Block(w,h,x){
this.w = w || this.random(300,100);
this.h = h || this.random(180,94);
if (x==0) {
this.x = 0;
this.deltaX = 320;
}else{
this.x = 320;
this.deltaX = 0;
}
this.block = document.createElement('div');
this.block.classList.add('block')
this.block.style.width = `${this.w}px`;
this.block.style.height = `${this.h}px`;
document.querySelector(".stage").appendChild(this.block);
}
// move
Block.prototype.move = function(voice) {
this.x -= voice;
this.deltaX += voice;
this.block.style.webkitTransform = `translate(${this.x}px)`;
};
// return a random number
Block.prototype.random = function(max , min) {
var Range = max - min;
var Rand = Math.random();
return (min + Math.round(Rand * Range));
};<file_sep>/js/AudioAPI.js
// audio
(function(){
const navigator = window.navigator
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia
const AudioContext = window.AudioContext ||
window.webkitAudioContext
const isSupport = !!(navigator.getUserMedia && AudioContext)
const context = isSupport && new AudioContext()
function start () {
return new Promise((resolve, reject) => {
navigator.getUserMedia({audio: true}, stream => {
const source = context.createMediaStreamSource(stream)
const analyser = context.createAnalyser()
source.connect(analyser)
analyser.fftSize = 2048
resolve(analyser)
}, () => {
reject()
})
})
}
function getVoiceSize (analyser) {
const dataArray = new Uint8Array(analyser.frequencyBinCount)
analyser.getByteFrequencyData(dataArray)
const data = dataArray.slice(100, 1000)
const sum = data.reduce((a, b) => a + b)
return sum
}
window.AudioAPI = {
start : start,
getVoiceSize : getVoiceSize
}
})()<file_sep>/README.md
# THE EIHGT GAME
> A game about voice

<file_sep>/js/index.js
var $btnNewGame = $(".btn-new"),
$btnAgain = $(".btn-again"),
$mask = $('.mask');
(function () {
var game = new Game();
$btnNewGame[0].onclick = function(){
$mask.hide();
game.gameStart();
}
$btnAgain[0].onclick = function(){
$mask.hide();
game.gameStart();
}
})() | a17a12be8944063e863c620c19f8354bace8ebfc | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | jlianphoto/theEight | afc1e01d7179a0e6075208cd4c56875993cccdaf | 9c1373d52f6f824509a2186296a6c9063b494706 |
refs/heads/master | <repo_name>sebilasse/widget-core<file_sep>/README.md
# @dojo/widget-core
[](https://travis-ci.org/dojo/widget-core)
[](https://codecov.io/gh/dojo/widget-core)
[](https://badge.fury.io/js/%40dojo%2Fwidget-core)
This repo provides users with the ability to write their own Dojo 2 widgets.
We also provide a suite of pre-built widgets to use in your applications: [(@dojo/widgets)](https://github.com/dojo/widgets).
**WARNING** This is _beta_ software. While we do not anticipate significant changes to the API at this stage, we may feel the need to do so. This is not yet production ready, so you should use at your own risk.
- [Usage](#usage)
- [Features](#features)
- [Overview](#overview)
- [`v` & `w`](#v--w)
- [`v`](#v)
- [`w`](#w)
- [tsx](#tsx)
- [Writing custom widgets](#writing-custom-widgets)
- [Public API](#public-api)
- [The 'properties' lifecycle](#the-properties-lifecycle)
- [Individual Property Diffing](#individual-property-diffing)
- [Property Diffing Reactions](#property-diffing-reactions)
- [Render Lifecycle](#render-lifecycle)
- [Projector](#projector)
- [Server Side Rendering](#server-side-rendering)
- [Event Handling](#event-handling)
- [Widget Registry](#widget-registry)
- [Injecting State](#injecting-state)
- [Theming](#theming)
- [Internationalization](#internationalization-i18n)
- [Web Components](#web-components)
- [Attributes](#attributes)
- [Properties](#properties)
- [Events](#events)
- [Initialization](#initialization)
- [Meta](#meta)
- [DomWrapper](#domwrapper)
- [Key Principles](#key-principles)
- [API](#api)
- [How Do I Contribute?](#how-do-i-contribute)
- [Installation](#installation)
- [Testing](#testing)
- [Licensing Information](#licensing-information)
## Usage
To use @dojo/widget-core, install the package along with its required peer dependencies:
```shell
npm install @dojo/widget-core
# peer dependencies
npm install @dojo/has
npm install @dojo/shim
npm install @dojo/core
npm install @dojo/i18n
npm install maquette
```
You can also use the [dojo cli](https://github.com/dojo/cli) to create a complete Dojo 2 skeleton application.
## Features
Constructing your own widgets (Custom widgets) is simple and straightforward.
The smallest `@dojo/widget-core` example looks like this:
```ts
class MyWidget extends WidgetBase<WidgetProperties> {
render() {
return v('h1', [ 'Hello, Dojo!' ]);
}
}
const Projector = ProjectorMixin(MyWidget);
const projector = new Projector();
projector.append(root);
```
This code renders a `h1` element onto the page, that says "Hello, Dojo!".
### Overview
All widgets in Dojo 2 are designed using key reactive architecture concepts.
These concepts include unidirectional data flow, inversion of control and property passing.
Dojo 2's widget-core is built with TypeScript, leveraging Class mixins to construct and manipulate traits and mixins.
We also make use of a VirtualDOM (VDOM) in Dojo 2.
In order to interact with our VDOM, you need to pass it [HyperScript](https://github.com/dominictarr/hyperscript).
In Dojo 2 we provide 2 functions that make interacting with the VDOM, easy and intuitive: `v` and `w`.
### `v` & `w`
These functions express structures that will be passed to the VDOM.
`v` creates nodes that represent DOM tags, e.g. `div`, `header` etc.
This function allows Dojo 2 to manage lazy hyperscript creation and element caching.
`w` creates Dojo 2 widgets or custom widget.
This function provides support for lazy widget instantiation, instance management and caching.
The `v` & `w` functions are available from the `@dojo/widget-core/d` package.
```ts
import { v, w } from '@dojo/widget-core/d';
```
The argument and return types for `v` and `w` are available from `@dojo/widget-core/interfaces`, and are as follows:
```ts
import { DNode, HNode, WNode } from '@dojo/widget-core/interfaces';
```
#### `v`
The following code creates an element with the specified `tag`
```ts
v(tag: string): HNode[];
```
The following code renders an element with the `tag` and `children`.
```ts
v(tag: string, children: DNode[]): HNode[];
```
The following code renders an element with the `tag`, `properties` and `children`.
```ts
v(tag: string, properties: VirtualDomProperties, children?: DNode[]): HNode[];
```
As well as interacting with the VDOM by passing it HyperScript, you can also pass it Dojo 2 Widgets or Custom Widgets using the `w` function.
#### `w`
The following code creates a widget using the `widgetConstructor` and `properties`.
```ts
w<W extends WidgetBaseInterface>(widgetConstructor: W | RegistryLabel, properties: W['properties']): WNode<W>;
```
The following code creates a widget using the `widgetConstructor`, `properties` and `children`
```ts
w<W extends WidgetBaseInterface>(widgetConstructor: W | RegistryLabel, properties: W['properties'], children: W['children']): WNode<W>;
```
Example `w` constructs:
```ts
w(WidgetClass, properties);
w(WidgetClass, properties, children);
w('my-widget', properties);
w('my-widget', properties, children);
```
The example above that uses a string for the `widgetConstructor `, is taking advantage of the [widget registry](#widget-registry) functionality.
The widget registry allows for the lazy loading of widgets.
### tsx
In additional to the programatic functions `v` and `w`, widget-core optionally supports the use of the `jsx` syntax known as [`tsx`](https://www.typescriptlang.org/docs/handbook/jsx.html) in TypeScript.
To start to use `jsx` in your project the widgets need to be named with a `.tsx` extension and some configuration is required in the project's `tsconfig.json`:
Add the configuration options for `jsx`:
```
"jsx": "react",
"jsxFactory": "tsx",
```
Include `.tsx` files in the project:
```
"include": [
"./src/**/*.ts",
"./src/**/*.tsx"
]
```
Once the project is configured, `tsx` can be used in a widget's `render` function simply by importing the `tsx` function as `import { tsx } from '@dojo/widget-core/tsx';`
```tsx
class MyWidgetWithTsx extends WidgetBase<MyProperties> {
protected render(): DNode {
const { clear, properties: { completed, count, activeCount, activeFilter } } = this;
return (
<footer classes={this.classes(css.footer)}>
<span classes={this.classes(css.count)}>
<strong>{`${activeCount}`}</strong>
<span>{`${count}`}</span>
</span>
<TodoFilter activeFilter={activeFilter} />
{ completed ? ( <button onclick={clear} /> ) : ( null ) }
</footer>
);
}
}
```
**Note:** Unfortunately `tsx` is not directly used within the module so will report as an unused import so would be needed to be ignored by linters.
### Writing Custom Widgets
The `WidgetBase` class provides the functionality needed to create Custom Widgets.
This functionality includes caching and widget lifecycle management.
The `WidgetBase` class is available from the `@dojo/widget-core/WidgetBase ` package.
```ts
import { WidgetBase } from '@dojo/widget-core/WidgetBase';
```
**All** widgets should extend from this class.
#### The 'properties' lifecycle
The properties lifecycle occurs immediately the widget render lifecycle. Properties are defined by an interface passed as a generic type to `WidgetBase` and represent the public default API. By default properties are automatically diffed against previous properties using the `auto` diff function (see table below).
**Note:** If a property contains complex data structures that you need to diff, then individual control is required using the `diffProperty` decorator.
##### Individual Property Diffing
Property diffing can be controlled for an individual property using the `diffProperty` decorator on a widget class.
`widget-core` provides a set of diffing function from `diff.ts` that can be used or a custom diffing function can be provided. Properties that have been configured with a specific diffing type will be excluded from the automatic diffing provided.
| Diff Function | Description |
| -------------------- | ----------------------------------------------------------------------------------|
| `always` | Always report a property as changed. |
| `auto` | Ignore functions, shallow compare objects, and reference compare all other values.| |
| `ignore` | Never report a property as changed. |
| `reference` | Compare values by reference (`old === new`) |
| `shallow` | Treat the values as objects and compare their immediate values by reference. |
**Important:** All diffing functions should be pure functions and are called *WITHOUT* any scope.
```ts
// using a diff function provided by widget-core#diff
@diffProperty('title', reference)
class MyWidget extends WidgetBase<MyProperties> { }
//custom diff function; A pure function with no side effects.
function customDiff(previousProperty: string, newProperty: string): PropertyChangeRecord {
return {
changed: previousProperty !== newProperty,
value: newProperty
};
}
// using a custom diff function
@diffProperty('title', customDiff)
class MyWidget extends WidgetBase<MyProperties> { }
```
##### Property Diffing Reactions
It can be necessary to perform some internal logic when one or more properties change, this can be done by registering a reaction callback.
A reaction function is registered using the `diffProperty` decorator on a widget class method. This method will be called when the specified property has been detected as changed and receives both the old and new property values.
```ts
class MyWidget extends WidgetBase<MyProperties> {
@diffProperty('title', auto)
protected onTitleChange(previousProperties: any, newProperties: any): void {
this._previousTitle = previousProperties.title;
}
}
```
`diffProperty` decorators can be stacked on a single class method and will be called if any of the specified properties are considered changed.
```ts
class MyWidget extends WidgetBase<MyProperties> {
@diffProperty('title', auto)
@diffProperty('subtitle', auto)
protected onTitleOrSubtitleChange(previousProperties: any, newProperties: any): void {
this._titlesUpdated = true;
}
}
```
For non-decorator environments (Either JavaScript/ES6 or a TypeScript project that does not have the experimental decorators configuration set to true in the `tsconfig`), the functions need to be registered in the constructor using the `addDecorator` API with `diffProperty` as the key.
```ts
class MyWidget extends WidgetBase<WidgetProperties> {
constructor() {
super();
diffProperty('foo', auto, this.diffFooReaction)(this);
}
diffFooReaction(previousProperty: any, newProperty: any) {
// do something to reaction to a diff of foo
}
}
```
#### Render Lifecycle
<!-- TODO: render lifecycle goes here -->
Occasionally, in a mixin or base widget class, it my be required to provide logic that needs to be executed before or after a widget's `render` call. These lifecycle hooks are supported in `WidgetBase` and operate as before and after aspects.
The functionality is provided by the `beforeRender` and `afterRender` decorators.
***Note:*** Both the `beforeRender` and `afterRender` functions are executed in the order that they are specified from the super class up to the final class.
##### BeforeRender
The `beforeRender` call receives the widget's `render` function, `properties` and `children` and is expected to return a function that satisfies the `render` API. The `properties` and `children` are passed to enable them to be manipulated or decorated prior to the `render` being called.
This is the only time in the widget lifecycle that exposes either of these attributes to be manipulated outside of the property system.
```ts
class MyBaseClass extends WidgetBase<WidgetProperties> {
@beforeRender
myBeforeRender(renderFunc: () => DNode, properties: any, children: DNode[]): () => DNode {
// decorate/manipulate properties or children.
properties.extraAttribute = 'foo';
// Return or replace the `render` function
return () => {
return v('my-replaced-attribute');
};
}
}
```
And using the `beforeRender` function for non decorator environments:
```ts
class MyBaseClass extends WidgetBase<WidgetProperties> {
constructor() {
super();
beforeRender(this.myOtherBeforeRender)(this);
}
myOtherBeforeRender(renderFunc: () => DNode, properties: any, children: DNode[]): () => DNode {
// do something with the result
return renderFunc;
}
}
```
##### AfterRender
The `afterRender` call receives the returned `DNode`s from a widget's `render` call, so that the nodes can decorated, manipulated or even swapped.
```ts
class MyBaseClass extends WidgetBase<WidgetProperties> {
@afterRender
myAfterRender(result: DNode): DNode {
// do something with the result
return result;
}
}
```
And using the `afterRender` function for non decorator environments:
```ts
class MyBaseClass extends WidgetBase<WidgetProperties> {
constructor() {
super();
afterRender(this.myOtherAfterRender)(this);
}
myOtherAfterRender(result: DNode): DNode {
// do something with the result
return result;
}
}
```
#### Projector
Projector is a term used to describe a widget that will be attached to a DOM element, also known as a root widget.
Any widget can be converted into a projector simply by mixing in the `ProjectMixin` mixin.
```ts
const MyProjector = ProjectorMixin(MyWidget);
```
Projectors behave in the same way as any other widget **except** that they need to be manually instantiated and managed outside of the standard widget lifecycle.
There are 3 ways that a projector widget can be added to the DOM - `.append`, `.merge`, `.replace`, or `.sandbox`, depending on the type of attachment required.
- `append` - Creates the widget as a child to the projector's `root` node
- `merge` - Merges the widget with the projector's `root` node
- `replace` - Replace the projector's `root` node with the widget
- `sandbox` - Create a document fragment as the projector's `root` node
```ts
const MyProjector = ProjectorMixin(MyWidget);
const myProjector = new MyProjector()
myProjector.append(root);
```
##### Server Side Rendering
The `Projector` provides several features which facilitate server side rendering and progressive enhancement. For rendering on the server, there are the methods `.sandbox()` and `.toHtml()`.
###### .sandbox()
`.sandbox()` does two things. It creates the `root` of the projector as a `DocumentFragment`. This ensures that the rendering of the projector does not interfere with the `document`. In order to server side render, you still need something like `jsdom` though in order to provide the functionality needed to generate the DOM structure which will be shipped to the browser. Also, when the projector is attached it will render synchronously. Usually the projector renders asyncronously to ensure that renders have a minimal impact on the user experience, helping eliminate _jank_. This can cause problems though in that when exporting the HTML, the projector needs to be in a _known_ render state. `.sandbox()` takes a single optional argument which is a `Document`. If none is supplied, then the global `document` will be used.
An example using [`jsdom`](https://github.com/tmpvar/jsdom):
```ts
import { JSDOM } from 'jsdom';
import ProjectorMixin from '@dojo/widget-core/mixins/Projector';
import App from './widgets/App';
const dom = new JSDOM('', { runScripts: 'dangerously' });
const projector = new (ProjectorMixin(App))();
const projector.sandbox(dom.window.document);
```
###### .toHtml()
`.toHtml()` returns a string which represents the current render of the `Projector`. While it can be used with any attachment mode, it is most effective when using `.sandbox()`, as this mode operates synronously, ensuring that the string returned accuretly represents the current rendered DOM structure. Building on the example from above:
```ts
import { JSDOM } from 'jsdom';
import ProjectorMixin from '@dojo/widget-core/mixins/Projector';
import App from './widgets/App';
const dom = new JSDOM('', { runScripts: 'dangerously' });
const projector = new (ProjectorMixin(App))();
const projector.sandbox(dom.window.document);
/* set any App properties/children/state */
const html = projector.toHtml();
/* `html` contains the rendered HTML */
```
#### Event Handling
The recommended pattern for custom event handlers is to declare them on the widget class and reference the function using `this`.
Event handlers are most commonly called from `render`.
Event handlers can be internal logic encapsulated within a widget or delegate to a function passed into the widget via `properties`.
For convenience event handlers are automatically bound to the scope of their enclosing widget.
*internally defined handler*
```ts
class MyWidget extends WidgetBase<WidgetProperties> {
private selected: boolean;
onClick() {
this.selected = !this.selected;
}
render(this: MyWidget): DNode {
return v('div', [
v('input', { type: 'checkbox', onclick: this.onClick }),
v('input', { type: 'text', disabled: this.selected })
]);
}
}
```
*Handler passed via properties*
```ts
class MyWidget extends WidgetBase<WidgetProperties> {
onClick(): void {
this.properties.mySpecialFunction();
}
}
```
*Binding a function passed to a child widget*
```ts
import { specialClick } from './mySpecialFunctions';
class MyWidget extends WidgetBase<WidgetProperties> {
render() {
return w(ChildWidget, { onClick: specialClick });
}
}
```
#### Widget Registry
The widget registry provides the ability to define a `string` or `symbol` as a label for a `WidgetRegistryItem`.
The `WidgetRegistryItem`, can be one of the following types:
1. `WidgetConstructor`
2. `Promise<WidgetConstructor>`
3. `() => Promise<WidgetConstructor>`
A global widget registry is exported from the `d` module.
```ts
import { registry } from '@dojo/widget-core/d';
import MyWidget from './MyWidget';
// registers the widget that will be available immediately
registry.define('my-widget-1', MyWidget);
// registers a promise that is resolving to a widget and will be
// available as soon as the promise resolves.
registry.define('my-widget-2', Promise.resolve(MyWidget));
// registers a function that will be lazily executed the first time the
// label is used within a widget render pipeline. The widget will be available
// as soon as the promise is resolved after the initial get.
registry.define('my-widget-3', () => Promise.resolve(MyWidget));
```
It is recommended to use the widget registry when defining widgets with [`w`](#w--d), to support lazy widget resolution.
Example of registering a function that returns a `Promise` that resolves to a `widget`.
```ts
import load from '@dojo/core/load';
registry.define('my-widget', () => {
return load(require, './MyWidget')
.then(([ MyWidget ]) => MyWidget.default);
});
```
#### Injecting State
Working with larger widget structures, it can quickly become tiresome and complex to pass all the required properties down the tree. Needing to pass all required properties also means widgets often need to be aware of properties that are only needed for ensuring their propagation to child widgets.
Dojo 2 provides a mechanism to inject state directly to parts of the widget tree; this is done by defining an `Injector` in the `registry` and passing a context object that will source the state that is to be injected.
```ts
import { Injector, BaseInjector } from '@dojo/widget-core/Injector';
const myStateContext = {
theme: 'solid'
};
registry.define('state', Injector(BaseInjector, myStateContext));
```
To use the injected state, create a `beforeRender` method that returns a render function which creates a `w` reference to the registry item like any other widget and pass the properties required by the `InjectorProperties` interface.
```ts
beforeRender(renderFunc: () => DNode, properties: any, children: any): DNode {
return () => {
return w('state', {
render: renderFunc,
getProperties(context: any, properties: any): any {
return context;
},
properties,
getChildren(context: any, children: DNode[]): DNode[] {
return [];
},
children
});
};
}
```
This will inject the values of `myState` as properties to the widget, as the returned object from `getProperties` is mixed over the widget's existing properties.
For convenience, Dojo 2 provides a mixin called `Container` that will decorate a widget with the above `beforeRender` implementation. Using the `Container` mixin enables any view widget to have state injected without coupling the widget to always have state injected. This means the widget can also be used as a normal widget with properties being passed from its parent.
```ts
import { MyViewWidget } from './MyViewWidget';
import { Container } from '@dojo/widget-core/Container';
function getProperties(context: any, properties: any): any {
return context;
}
const MyViewWidgetContainer = Container(MyViewWidget, 'state', { getProperties });
```
**Note:** that both the `getProperties` and `getChildren` functions do not need to be provided, if the functions are not defined the default mappers will be used that return an empty object and an empty array respectively.
There may be times when the default `BaseInjector` doesn't fully meet your needs. For example if the context contains a reference to an eventable instance, you may want to add an event listener in the `Injector` to perform some logic, perhaps invalidate the widget.
To do this the `BaseInjector` can be extended easily to add the extra logic required.
```ts
interface MyContext {
eventeableInstance: Evented;
bar: number;
}
class MyInjector extends BaseInjector<MyContext> {
constructor(context: MyContext) {
super(context);
const { eventeableInstance } = context;
eventeableInstance.on('change', () => {
this.invalidate();
});
}
protected toInject(): any {
const { eventeableInstance, bar } = this.context;
return {
eventeableInstance,
bar
};
}
}
```
#### Theming
##### Overview
Widgets are themed using `css-modules` and the `Themeable` mixin. Each widget must implement a .css file that contains all the css classes that will be used to style it. The `baseClasses` object is the css API for the Widget: `baseClasses` css classes can be overridden by external themes. Further customization of specific Custom Widget classes can be achieved by passing `extraClasses` into the widget.
The `Themeable` mixin provides a `classes` function that controls the classes to be applied to each node. Classes from the base `css` object passed to the `classes` function can be themed and overridden. To create fixed classes that cannot be changed, the chained `fixed` function can be used.
##### Authoring a Base Theme
A base theme is authored using `css-modules` and `cssnext`. The base theme `css` file should be located in a `styles` folder within the Widget's package directory.
The `typed-css-modules` [cli](https://github.com/Quramy/typed-css-modules#cli) should be used in `watch` mode in order to generate typings for TypeScript usage. This is automatically included within the `dojo build -w` command from `dojo-cli`.
```
tabPanel
├── createTabPanel.ts
└── styles
└── tabPanel.css
```
The `baseClasses` css must contain a complete set of all of the classes you wish to apply to a widget as all theme and extra classes are limited by the classnames made available here.
Classnames are locally scoped as part of building a Dojo application. A theme `key` is generated at build time to locate the themes for each class where a theme is set.
```css
/* tabpanel.css */
.root {
background: red;
}
.tab {
background: blue;
}
```
##### Registering `baseClasses`
To apply `baseClasses` a widget must use `ThemeableMixin` and the `theme` decorator from `mixins/Themeable` to register the `baseClasses`.
```ts
import { WidgetProperties } from '@dojo/widget-core/interfaces';
import { WidgetBase } from '@dojo/widget-core/WidgetBase';
import { ThemeableMixin, theme } from '@dojo/widget-core/mixins/Themeable';
import * as baseClasses from './styles/tabpanel.css';
@theme(baseClasses)
class MyThemeableWidget extends ThemeableMixin(WidgetBase)<WidgetProperties> {
// ...
}
```
Basic usage:
```ts
import { WidgetProperties } from '@dojo/widget-core/interfaces';
import { WidgetBase } from '@dojo/widget-core/WidgetBase';
import { ThemeableMixin, ThemeableProperties, theme } from '@dojo/widget-core/mixins/Themeable';
import * as baseClasses from './styles/tabpanel.css';
interface MyThemeableWidgetProperties extends WidgetProperties, ThemeableProperties;
@theme(baseClasses)
class MyThemeableWidget extends ThemeableMixin(WidgetBase)<MyThemeableWidgetProperties> {
render: function () {
const { root, tab } = baseClasses;
return
v('ul', { classes: this.classes(root) }, [
v('li', { classes: this.classes(tab) }, [ 'tab1' ])
// ...
]);
}
}
```
##### Applying a Theme
Themeable widgets include an optional `theme` property which can be set to pass in a theme. Theme classes will override `baseClasses`. When a `theme` property is set or changed, the widgets `theme` classes will be regenerated and the widget invalidated such that it is redrawn. Themes are used to apply consistent styling across the widget codebase.
Usage Extending on the previous `tabPanel` example.
``` css
/* customTheme/tabPanel.css */
.tabs {
background: green;
}
```
Import the theme and pass it to the widget via its `properties`. The theme classes will be automatically mixed into the widget and available via `this.classes`.
```ts
import * as customTheme from './themes/customTheme.css';
interface MyThemeableWidgetProperties extends WidgetProperties, ThemeableProperties;
class MyThemeableWidget extends ThemeableMixin(WidgetBase)<MyThemeableWidgetProperties> {
render: function () {
// Resulting widget will have green tabs instead of baseTheme red.
return w(TabPanel, { theme: customTheme });
}
}
```
The theme can be applied to individual widgets or to a project and property passed down to its children.
##### Injecting a theme
The theming system supports injecting a theme that is configured externally to the usual mechanism of passing properties down the widget tree.
This is done using a `ThemeInjectorContext` instance that is passed to the `Injector` mixin along with the `ThemeInjector` class. Once the theme injector is defined in the registry, the `theme` can be changed by calling the `ThemeInjectorContext#set(theme: any)` API on the instance of the injector context.
```ts
// Create the singleton injector context
const themeInjectorContext = new ThemeInjectorContext(myTheme);
// Create the base ThemeInjector using the singleton context and the Injector mixin
const ThemeInjectorBase = Injector<ThemeInjectorContext, Constructor<ThemeInjector>>(ThemeInjector, themeInjectorContext);
// Define the created ThemeInjector against the static key exported from `Themeable`
registry.define(INJECTED_THEME_KEY, ThemeInjectorBase);
```
Once this theme injector is defined, any themeable widgets without an explicit `theme` property will be controlled via the theme set within the `themeInjectorContext`. To change the theme simply call `themeInjectorContext.set(myNewTheme);` and all widgets that are using the injected theme will be updated to the new theme.
To make this even easier, `Themeable` exports a helper function wraps the behavior defined above and returns the context, with a parameter for the `theme` and an optional `registry` for the injector to be defined. If a `registry` is not provided then the global `registry` is used.
```ts
// Uses global registry
const context = registerThemeInjector(myTheme);
// Setting the theme
context.set(myNewTheme);
// Uses the user defined registry
const context = registryThemeInjector(myTheme, myRegistry);
```
##### Overriding Theme Classes
As we are using `css-modules` to scope widget css classes, the generated class names cannot be used to target specific nodes and apply custom styling to them. Instead you must use the `extraClasses` property to pass your generated classes to the widget. This will only effect one instance of a widget and will be applied on top of, rather than instead of, theme classes.
```css
/* tabPaneExtras.css */
.tabs {
font-weight: bold;
}
```
```ts
import * as myExtras from './extras/myExtras.css';
interface MyThemeableWidgetProperties extends WidgetProperties, ThemeableProperties;
class MyThemeableWidget extends ThemeableMixin(WidgetBase)<MyThemeableWidgetProperties> {
render: function () {
// Resulting widget will still have baseTheme red tabs,
// but will have font-weight: bold; applied also
return w(TabPanel, { extraClasses: myExtras });
}
}
```
##### Applying Fixed Classes
The `this.classes` function returns a chained `fixed` function that can be used to set non-themeable classes on a node. This allows a widget author to apply classes to a widget that cannot be overridden.
``` ts
import { WidgetProperties } from '@dojo/widget-core/interfaces';
import { WidgetBase } from '@dojo/widget-core/WidgetBase';
import { ThemeableMixin, ThemeableProperties, theme } from '@dojo/widget-core/mixins/Themeable';
import * as baseClasses from './styles/tabpanel.css';
interface MyThemeableWidgetProperties extends WidgetProperties, ThemeableProperties;
@theme(baseClasses)
class MyThemeableWidget extends ThemeableMixin(WidgetBase)<MyThemeableWidgetProperties> {
render: function () {
const { root, tab } = baseClasses;
return
v(`ul`, { classes: this.classes(root) }, [
v('li', { classes: this.classes().fixed(tab) }, [ 'tab1' ])
// ...
]);
}
}
```
In the above example, the `root` class is still themeable, but the `tab` class is applied using `.fixed()` so it will not be themeable. The classes passed to `.fixed()` can be any string, and unlike the `.classes()` parameters, `fixed()` css classes do not need to originate from `baseClasses`.
#### Internationalization (i18n)
Widgets can be internationalized by mixing in `@dojo/widget-core/mixins/I18n`.
[Message bundles](https://github.com/dojo/i18n) are localized by passing them to `localizeBundle`.
If the bundle supports the widget's current locale, but those locale-specific messages have not yet been loaded, then the default messages are returned.
The widget will be invalidated once the locale-specific messages have been loaded.
Each widget can have its own locale by passing a property - `properties.locale`.
If no locale is set, then the default locale, as set by [`@dojo/i18n`](https://github.com/dojo/i18n), is assumed.
```ts
class I18nWidget extends I18nMixin(WidgetBase)<I18nWidgetProperties> {
render: function () {
// Load the "greetings" messages for the current locale. If the locale-specific
// messages have not been loaded yet, then the default messages are returned,
// and the widget will be invalidated once the locale-specific messages have
// loaded.
const messages = this.localizeBundle(greetingsBundle);
return v('div', { title: messages.hello }, [
w(Label, {
// Passing a message string to a child widget.
label: messages.purchaseItems
}),
w(Button, {
// Passing a formatted message string to a child widget.
label: messages.format('itemCount', { count: 2 })
})
]);
}
}
```
#### Web Components
Widgets can be turned into [Custom Elements](https://www.w3.org/TR/2016/WD-custom-elements-20161013/) with
minimal extra effort.
Just create a `CustomElementDescriptor` factory and use the `@dojo/cli` build tooling to do the rest of the work,
```ts
import { CustomElementDescriptor } from '@dojo/widget-core/customElements';
import MyWidget from './path/to/MyWidget';
export default function createCustomElement(): CustomElementDescriptor {
return {
tagName: 'my-widget',
widgetConstructor: MyWidget,
attributes: [
{
attributeName: 'label'
}
],
events: [
{
propertyName: 'onChange',
name: 'change'
}
]
};
};
```
By convention, this file should be named `createMyWidgetElement.ts`.
To build your custom element, use [@dojo/cli](https://github.com/dojo/cli),
```bash
$ dojo build --element=/path/to/createMyWidget.ts
```
This will generate the following files:
* `dist/my-widget/my-widget.html` - HTML import file that includes all widget dependencies. This is the only file you need to import into your HTML page to use your widget.
* `dist/my-widget/my-widget.js` - A compiled version of your widget.
* `dist/my-widget/my-widget.css` - The CSS for your widget
* `dist/my-widget/widget-core.js` - A shared base widget library. Keeping this separate means that you can include HTML imports for multiple Dojo widgets and the applicartion environment will not re-request this shared file for each widget.
Using your widget would be a simple matter of importing the HTML import:
```html
<!DOCTYPE html>
<html>
<head>
<!-- this will include all JS and CSS used by your widget -->
<link rel="import" href="/path/to/my-widget.html" />
</head>
<body>
<!-- this will actually create your widget -->
<my-widget></my-widget>
</body>
</html>
```
##### Tag Name
Your widget will be registered with the browser using the provided tag name. The tag name **must** have a `-` in it.
##### Widget Constructor
A widget class that you want wrapped as a custom element.
##### Attributes
You can explicitly map widget properties to DOM node attributes with the `attributes` array.
```ts
{
attributes: [
{
attributeName: 'label'
},
{
attributeName: 'placeholder',
propertyName: 'placeHolder'
},
{
attributeName: 'delete-on-focus',
propertyName: 'deleteOnFocus',
value: value => Boolean(value || 0)
}
]
}
```
* `attributeName` - the attribute that will set on the DOM element, e.g. `<text-widget label="test" />`.
* `propertyName` - the property on the widget to set; if not set, it defaults to the `attributeName`.
* `value` - specify a transformation function on the attribute value. This function should return the value that
will be set on the widget's property.
Adding an attribute to the element will also automatically add a corresponding property to the element.
```ts
// as an attribute
textWidget.setAttribute('label', '<NAME>');
// as a property
textWidget.label = '<NAME>';
```
##### Properties
You can map DOM element properties to widget properties,
```ts
{
properties: [
{
propertyName: 'placeholder',
widgetPropertyName: 'placeHolder'
}
]
}
// ...
textWidget.placeholder = 'Enter <NAME>';
```
* `propertyName` - name of the property on the DOM element
* `widgetPropertyName` - name of the property on the widget; if unspecified, `propertyName` is used instead
* `getValue` - if specified, will be called with the widget's property value as an argument. The returned value is returned as the DOM element property value.
* `setValue` - if specified, is called with the DOM elements property value. The returned value is used for the widget property's value.
##### Events
Some widgets have function properties, like events, that need to be exposed to your element. You can use the
`events` array to map widget properties to DOM events.
```ts
{
events: [
{
propertyName: 'onChange',
eventName: 'change'
}
]
}
```
This will add a property to `onChange` that will emit the `change` custom event. You can listen like any other
DOM event,
```ts
textWidget.addEventListener('change', function (event) {
// do something
});
```
##### Initialization
Custom logic can be performed after properties/attributes have been defined but before the projector is created. This
allows you full control over your widget, allowing you to add custom properties, event handlers, work with child nodes, etc.
The initialization function is run from the context of the HTML element.
```ts
{
initialization(properties) {
const footer = this.getElementsByTagName('footer');
if (footer) {
properties.footer = footer;
}
const header = this.getElementsByTagName('header');
if (header) {
properties.header = header;
}
}
}
```
It should be noted that children nodes are removed from the DOM when widget instantiation occurs, and added as children
to the widget instance.
#### Meta
Widget meta is used to access additional information about the widget, usually information only available through the rendered DOM element - for example, the dimensions of an HTML node. You can access and respond to meta data during a widget's render operation.
```typescript
class TestWidget extends WidgetBase<WidgetProperties> {
render() {
const dimensions = this.meta(Dimensions).get('root');
return v('div', {
key: 'root',
innerHTML: `Width: ${dimensions.width}`
});
}
}
```
If an HTML node is required to calculate the meta information, a sensible default will be returned and your widget will be automatically re-rendered to provide more accurate information.
###### Dimensions
The `Dimensions` meta provides size/position information about a node.
```
const dimensions = this.meta(Dimensions).get('root');
```
In this simple snippet, `dimensions` would be an object containing `offset`, `position`, `scroll`, and `size` objects.
The following fields are provided:
| Property | Source |
| -----------------| ------------------------------------- |
| `position.bottom`| `node.getBoundingClientRect().bottom` |
| `position.left` | `node.getBoundingClientRect().left` |
| `position.right` | `node.getBoundingClientRect().right` |
| `position.top` | `node.getBoundingClientRect().top` |
| `size.width` | `node.getBoundingClientRect().width` |
| `size.height` | `node.getBoundingClientRect().height` |
| `scroll.left` | `node.scrollLeft` |
| `scroll.top` | `node.scrollTop` |
| `scroll.height` | `node.scrollHeight` |
| `scroll.width` | `node.scrollWidth` |
| `offset.left` | `node.offsetLeft` |
| `offset.top` | `node.offsetTop` |
| `offset.width` | `node.offsetWidth` |
| `offset.height` | `node.offsetHeight` |
If the node has not yet been rendered, all values will contain `0`. If you need more information about whether or not the node has been rendered you can use the `has` method:
```
const hasRootBeenRendered = this.meta(Dimensions).has('root');
```
##### Implementing Custom Meta
You can create your own meta if you need access to DOM nodes.
```typescript
import MetaBase from "@dojo/widget-core/meta/Base";
class HtmlMeta extends MetaBase {
get(key: string): string {
this.requireNode(key);
const node = this.nodes.get(key);
return node ? node.innerHTML : '';
}
}
```
And you can use it like:
```typescript
class MyWidget extends WidgetBase<WidgetProperties> {
// ...
render() {
// run your meta
const html = this.meta(HtmlMeta).get('comment');
return v('div', { key: 'root', innerHTML: html });
}
// ...
}
```
Meta classes are provided with a few hooks into the widget, passed to the constructor:
* `nodes` - A map of `key` strings to DOM elements. Only `v` nodes rendered with `key` properties are stored.
* `requireNode` - A method that accept a `key` string to inform the widget it needs a rendered DOM element corresponding to that key. If one is available, it will be returned immediately. If not, the widget will be re-rendered and if the node does not exist on the next render, an error will be thrown.
* `invalidate` - A method that will invalidate the widget.
Extending the base class found in `meta/Base` will automatically add these hooks to the class instance as well as providing a `has` method:
* `has(key: string)` - A method that returns `true` if the DOM element with the passed key exists in the rendered DOM.
Meta classes that require extra options should accept them in their methods.
```typescript
import MetaBase from "@dojo/widget-core/meta/Base";
interface IsTallMetaOptions {
minHeight: number;
}
class IsTallMeta extends MetaBase {
isTall(key: string, { minHeight }: IsTallMetaOptions = { minHeight: 300 }): boolean {
this.requireNode(key);
const node = this.nodes.get(key);
if (node) {
return node.offsetHeight >= minHeight;
}
return false;
}
}
```
#### DomWrapper
`DomWrapper` is used to wrap DOM that is created _outside_ of the virtual DOM system. This is the main mechanism to integrate _foreign_ components or widgets into the virtual DOM system.
The `DomWrapper` generates a class/constructor function that is then used as a widget class in the virtual DOM. `DomWrapper` takes up to two arguments. The first argument is the DOM node that it is wrapping. The second is an optional set of options.
The currently supported options:
|Name|Description|
|-|-|
|`onAttached`|A callback that is called when the wrapped DOM is flowed into the virtual DOM|
As an example, we want to integrate a 3rd party library where we need to pass the component factory a _root_ element and then flow that into our virtual DOM. In this situation we don't want to create the component until the widget is being flowed into the DOM, so `onAttached` is used to perform the creation of the component:
```ts
import { w } from '@dojo/widget-core/d';
import DomWrapper from '@dojo/widget-core/util/DomWrapper';
import WidgetBase from '@dojo/widget-core/WidgetBase';
import createComponent from 'third/party/library/createComponent';
export default class WrappedComponent extends WidgetBase {
private _component: any;
private _onAttach = () => {
this._component = createComponent(this._root);
}
private _root: HTMLDivElement;
private _WrappedDom: DomWrapper;
constructor() {
super();
const root = this._root = document.createElement('div');
this._WrappedDom = DomWrapper(root, { onAttached: this._onAttached });
}
public render() {
return w(this._WrappedDom, { key: 'wrapped' });
}
}
```
The properties which can be set on `DomWrapper` are the combination of the `WidgetBaseProperties` and the `VirtualDomProperties`, which means effectively you can use any of the properties passed to a `v()` node and they will be applied to the wrapped DOM node. For example the following would set the classes on the wrapped DOM node:
```ts
const div = document.createElement('div');
const WrappedDiv = DomWrapper(div);
const wnode = w(WrappedDiv, {
classes: {
'foo': true
}
});
```
### Key Principles
These are some of the **important** principles to keep in mind when creating and using widgets:
1. The widget's *`__render__`*, *`__setProperties__`*, *`__setChildren__`* functions should **never** be called or overridden
2. Except for projectors, you should **never** need to deal directly with widget instances
3. Hyperscript should **always** be written using the @dojo/widget-core `v` helper function
4. **Never** set state outside of a widget instance
5. **Never** update `properties` within a widget instance
### API
[API Documentation](http://dojo.io/api/widget-core/v2.0.0-alpha.28/)
## How Do I Contribute?
We appreciate your interest! Please see the [Dojo Meta Repository](https://github.com/dojo/meta#readme) for the
Contributing Guidelines and Style Guide.
### Installation
To start working with this package, clone the repository and run `npm install`.
In order to build the project, run `grunt dev` or `grunt dist`.
### Testing
Test cases MUST be written using [Intern](https://theintern.github.io) using the Object test interface and Assert assertion interface.
90% branch coverage MUST be provided for all code submitted to this repository, as reported by Istanbul’s combined coverage results for all supported platforms.
To test locally in node run:
`grunt test`
To test against browsers with a local selenium server run:
`grunt test:local`
To test against BrowserStack or Sauce Labs run:
`grunt test:browserstack`
or
`grunt test:saucelabs`
## Licensing Information
© 2017 [JS Foundation](https://js.foundation/). [New BSD](http://opensource.org/licenses/BSD-3-Clause) license.
<file_sep>/src/mixins/Stateful.ts
import { deepAssign } from '@dojo/core/lang';
import { Constructor } from './../interfaces';
import { WidgetBase } from './../WidgetBase';
/**
* State
*/
export interface State {
[key: string]: any;
}
/**
* Stateful interface
*/
export interface StatefulMixin {
/**
* state property
*/
readonly state: State;
/**
* Set the internal state. Accepts a partial and mixes on top of the existing state.
* To clear a key it needs to be specifically set to undefined.
*
* @param state state to mix over the stored state
*/
setState(state: Partial<State>): void;
}
/**
* State change event type
*/
const stateChangedEventType = 'state:changed';
export function StatefulMixin<T extends Constructor<WidgetBase<any>>>(Base: T): T & Constructor<StatefulMixin> {
return class extends Base {
private _state: State;
constructor(...args: any[]) {
super(...args);
this._state = Object.create(null);
this.own(this.on('state:changed', () => {
this.invalidate();
}));
}
public get state(): State {
return this._state;
}
public setState(state: Partial<State>): void {
this._state = deepAssign({}, this._state, state);
const eventObject = {
type: stateChangedEventType,
state: this._state,
target: this
};
this.emit(eventObject);
}
};
}
export default StatefulMixin;
<file_sep>/tests/unit/mixins/Stateful.ts
import * as registerSuite from 'intern!object';
import * as assert from 'intern/chai!assert';
import { StatefulMixin } from './../../../src/mixins/Stateful';
import { WidgetBase } from './../../../src/WidgetBase';
class Test extends StatefulMixin(WidgetBase)<any> { }
registerSuite({
name: 'mixins/StatefulMixin',
creation() {
const stateful = new Test();
assert.deepEqual(stateful.state, {}, 'stateful should have empty state');
},
'get and set state'() {
const stateful = new Test();
const state = {
foo: 'bar'
};
stateful.setState(state);
assert.deepEqual(stateful.state, state);
},
'partially update state'() {
const stateful = new Test();
const state = {
foo: 'bar'
};
const updatedState = {
baz: 'qux'
};
stateful.setState(state);
assert.deepEqual(stateful.state, state);
stateful.setState(updatedState);
assert.deepEqual(stateful.state, { foo: 'bar', baz: 'qux' });
},
'emits `state:changed` event on state update'() {
const stateful = new Test();
const state = {
foo: 'bar'
};
let called = false;
stateful.on('state:changed', (event: any) => {
called = true;
assert.equal(event.target, stateful);
assert.equal(event.type, 'state:changed');
assert.deepEqual(event.state, state);
});
stateful.setState(state);
assert.isTrue(called);
},
'invalidate is called on state change'() {
let invalidateCalled = false;
const stateful = new class extends Test {
invalidate() {
super.invalidate();
invalidateCalled = true;
}
}();
stateful.setState({});
assert.isTrue(invalidateCalled);
}
});
| a147c5fee04ee0d5166a33b26335ef19a5a0226c | [
"Markdown",
"TypeScript"
] | 3 | Markdown | sebilasse/widget-core | 82751974837e6421ab694b9671ec72d1ac0e67eb | e0a972c61db3e16c8c5cb607576b765456f63943 |
refs/heads/master | <repo_name>chousemath/njtransit<file_sep>/script.js
// Generated by CoffeeScript 2.3.2
(function() {
var color1, color2, color3, colorElements, dateElement, expElement, fullOpacity, gradientBtm, gradientTop, inputColor1, inputColor2, inputColor3, inputGradient, monthNames, setOpacityTo0, setOpacityTo1, timeConfig, timeElement, timeLimit, weekdays;
timeConfig = {
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: true
};
weekdays = new Array(7);
weekdays[0] = 'Sunday';
weekdays[1] = 'Monday';
weekdays[2] = 'Tuesday';
weekdays[3] = 'Wednesday';
weekdays[4] = 'Thursday';
weekdays[5] = 'Friday';
weekdays[6] = 'Saturday';
monthNames = new Array();
monthNames[0] = 'Jan';
monthNames[1] = 'Feb';
monthNames[2] = 'Mar';
monthNames[3] = 'Apr';
monthNames[4] = 'May';
monthNames[5] = 'Jun';
monthNames[6] = 'Jul';
monthNames[7] = 'Aug';
monthNames[8] = 'Sep';
monthNames[9] = 'Oct';
monthNames[10] = 'Nov';
monthNames[11] = 'Dec';
timeElement = document.getElementById('span-time');
dateElement = document.getElementById('span-date');
expElement = document.getElementById('span-expiration');
colorElements = document.getElementsByClassName('container-color-1');
gradientTop = document.getElementById('container-ticket-gradient-1');
gradientBtm = document.getElementById('container-ticket-gradient-2');
inputGradient = document.getElementById('input-gradient');
color1 = document.getElementById('color-1');
color2 = document.getElementById('color-2');
color3 = document.getElementById('color-3');
inputColor1 = document.getElementById('input-color-1');
inputColor2 = document.getElementById('input-color-2');
inputColor3 = document.getElementById('input-color-3');
gradientTop.addEventListener('click', function() {
return inputGradient.click();
});
gradientBtm.addEventListener('click', function() {
return inputGradient.click();
});
color1.addEventListener('click', function() {
return inputColor1.click();
});
color2.addEventListener('click', function() {
return inputColor2.click();
});
color3.addEventListener('click', function() {
return inputColor3.click();
});
inputColor1.addEventListener('change', function() {
console.log(inputColor1.value);
return color1.style.backgroundColor = inputColor1.value;
});
inputColor2.addEventListener('change', function() {
console.log(inputColor2.value);
return color2.style.backgroundColor = inputColor2.value;
});
inputColor3.addEventListener('change', function() {
console.log(inputColor3.value);
return color3.style.backgroundColor = inputColor3.value;
});
inputGradient.addEventListener('change', function() {
console.log(inputGradient.value);
gradientTop.style.backgroundImage = `linear-gradient(${inputGradient.value}, #fff)`;
return gradientBtm.style.backgroundImage = `linear-gradient(#fff, ${inputGradient.value})`;
});
timeLimit = 150 * 60; // number of minutes to count down
fullOpacity = true; // whether or not the colors are showing
setOpacityTo1 = function(element) {
return element.style.opacity = "1";
};
setOpacityTo0 = function(element) {
return element.style.opacity = "0";
};
setInterval(function() {
var date, dateString, day, dayString, elem, i, j, len, len1, limitHours, limitMinutes, limitSeconds, limitStrHours, limitStrMinutes, limitStrSeconds, month, now, nowString, results, results1, weekday, year;
timeLimit--;
date = new Date();
now = date.toLocaleString('en-US', timeConfig);
weekday = weekdays[date.getDay()];
month = monthNames[date.getMonth()];
day = date.getDate();
year = date.getFullYear();
nowString = now.length === 10 ? `0${now}` : `${now}`;
dayString = `${day}`;
if (dayString.length === 1) {
dayString = `0${day}`;
}
dateString = `${weekday}, ${month} ${dayString}, ${year}`;
// console.log nowString, '\t', dateString
timeElement.innerHTML = nowString;
dateElement.innerHTML = dateString;
limitHours = Math.floor(timeLimit / 3600);
limitMinutes = Math.floor((timeLimit / 60) - limitHours * 60);
limitSeconds = timeLimit - limitMinutes * 60 - limitHours * 60 * 60;
limitStrHours = `${limitHours}`;
limitStrMinutes = `${limitMinutes}`;
limitStrSeconds = `${limitSeconds}`;
if (limitStrHours.length === 1) {
limitStrHours = `0${limitStrHours}`;
}
if (limitStrMinutes.length === 1) {
limitStrMinutes = `0${limitStrMinutes}`;
}
if (limitStrSeconds.length === 1) {
limitStrSeconds = `0${limitStrSeconds}`;
}
expElement.innerHTML = `Expires in 00:${limitStrHours}:${limitStrMinutes}:${limitStrSeconds}`;
if (fullOpacity) {
fullOpacity = false;
results = [];
for (i = 0, len = colorElements.length; i < len; i++) {
elem = colorElements[i];
results.push(setOpacityTo0(elem));
}
return results;
} else {
fullOpacity = true;
results1 = [];
for (j = 0, len1 = colorElements.length; j < len1; j++) {
elem = colorElements[j];
results1.push(setOpacityTo1(elem));
}
return results1;
}
}, 1000);
}).call(this);
<file_sep>/README.md
```bash
# running coffeescript compiler
$ /Users/jo/Desktop/fake-ticket/node_modules/coffeescript/bin/coffee -c script.coffee
``` | 1f5a0de0a0fcc92e0f669f8aac6e65bf1f96d74b | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | chousemath/njtransit | 1282764be2854b46ff2bb1df2bbbeeae050933b5 | 86bc8364ac7882a651a1ccc347c40e1ca3abf041 |
refs/heads/master | <file_sep>package lesson4;
public class Home7 {
public static void main(String[] args){
int[]array = {1,2,3,4,3,2,1};
int[]array2 = {1,2,3,4,3,2,1,9};
System.out.print("ARR ");
printArray(array);
System.out.println(" ");
System.out.print("ARR 2 ");
printArray(array2);
System.out.println(" ");
System.out.println("Полиндромный ли массив?");
isArrayPalindrom(array);
if (isArrayPalindrom(array)== true){
System.out.println("ARR TRUE");
}else{
System.out.println("ARR FALSE");
}
isArrayPalindrom(array2);
if (isArrayPalindrom(array2)== true){
System.out.println("ARR2 TRUE");
}else{
System.out.println("ARR2 FALSE");
}
}
public static boolean isArrayPalindrom(int[]array){
for (int i = 0 ; i < array.length/2 ; i++ ) {
if (array[i] != array[array.length - i - 1]) {
return false;
}
}
return true;
}
public static void printArray(int[]array){
for (int i = 0 ; i < array.length ; i++ ){
if (i == 0) {
System.out.print("["+array[i]+",");
}else if ((i > 0) && (i < (array.length-1))) {
System.out.print( array[i]+"," );
}else {
System.out.print(array[i]+"]");
}
}
}
}
<file_sep>package lesson6;
import java.util.ArrayList;
import java.util.Arrays;
public class Task1 {
public static void main(String[]args) {
//ArrayList<String> list = new ArrayList<String>() // проверка что все строки Generic
//ArrayList list<int> = new ArrayList<int>;
//ArrayList list<Integer> = new ArrayList<Integer>;
byte b = 10;
Byte b1 = 10;//обертка byte
Byte b2 = null;
short s = 10;
Short s1 = 10;
int i =10;
Integer i1 =10;
Integer i2 = new Integer(10);
Integer i3 = Integer.valueOf(10);
char ch ='a';
Character ch1 = 'a';
ArrayList list = new ArrayList(); //в списке не указан размер в отличии от массива
System.out.println(list.size());
ArrayList list2 = new ArrayList(100); //в списке не указан размер в отличии от массива
System.out.println(list2.size());
list.add("Hello");
list.add("World");
list.add("Java");
list.add(999);
list.add(false);
list.add('A');
System.out.println(list.size());
System.out.println(list);
System.out.println(list.get(2)); //можно только прочитать значение из списка но не записать
list.set(3, "CoOL"); //заменяет значение
System.out.println(list);
list.add(2, "val"); //вставка со сдвигом вправо индекс+1
System.out.println(list);
list.remove(2);//удаление 2го из списка
System.out.println(list);
//list.clear();
//System.out.println(list);
System.out.println(list.contains("Hello"));
System.out.println(list);
System.out.println(list.indexOf("Java"));
String val = (String)list.get(2);
System.out.println(val);
Integer [] arr = new Integer[0];
arr = (Integer[]) list.toArray(arr);
System.out.println(Arrays.toString(arr));
//list.toArray(args);
}
}
<file_sep>package lesson2;
import java.util.Scanner;
import java.io.*;
public class Home4 {
public static void main(String []args){
Scanner in = new Scanner(System.in);
System.out.println("Введите имя пользователя");
String usr = in.next();
System.out.println("Hello" + " " + usr);
System.out.println("Введите число");
int val = in.nextInt();
if ((val % 2) == 0 ) {
System.out.println("Число "+ val +" - четное");
}
else{
if ((val % 2) == 1 ){
System.out.println("Число "+ val +" - нечетное");
}
}
}
}
<file_sep>package lesson4;
public class Home8 {
public static void main(String[] args){
int[]array = {3,2,5,8,6,4,5,3,7};
int[]array1 = {3,2,5,8,6,4};
printArray(array);
System.out.println(" ");
printArray(array1);
System.out.println(" ");
revertArray(array);
revertArray(array1);
printArray(array);
System.out.println(" ");
printArray(array1);
}
public static void revertArray(int[]array){
int count = array.length;
System.out.println(count);
for (int i = 0 ; i < count/2 ; i++ ){
int tmp = array[i];
array[i] = array[count - i - 1];
array[count -i - 1] = tmp;
}
}
public static void printArray(int[]array){
for (int i = 0 ; i < array.length ; i++ ){
if (i == 0) {
System.out.print("["+array[i]+",");
}else if ((i > 0) && (i < (array.length-1))) {
System.out.print( array[i]+"," );
}else {
System.out.print(array[i]+"]");
}
}
}
}
<file_sep>package lesson4;
public class Task3 {
public static void main (String[] args){
int [] array = new int[10];
for(int i = 0; i < array.length ; i++){
array[i] = (int)(Math.random() * 100);
}
for(int i = 0; i < array.length ; i++){
System.out.print(array[i] +" " );
}
System.out.println(" ");
for(int i = 0; i < array.length ; i++){
if(array[i] <30) {
array[i] = 0;
}
}
for(int i = 0; i < array.length ; i++){
System.out.print(array[i] +" " );
}
System.out.println(" ");
int sum = 0; //переменна для подсчета суммы
for(int i = 0; i < array.length ; i++){
sum = sum + array[i];
}
System.out.print("Summa - "+ sum ); //вывод суммы к конце цикла
int count = 0;
int count1 = 0;
for(int i = 0; i < array.length ; i++){
if (array[i]%2 == 1){
count++;
}else{
count1++;
}
}
System.out.println(" ");
System.out.print("Нечетных "+ count ); //вывод суммы к конце цикла
System.out.println(" ");
System.out.print("четных "+ count1 ); //вывод суммы к конце цикла
}
}
<file_sep>package lesson4;
public class Home9 {
public static void main(String[] args) {
drawStair(4);
drawStair1(4);
drawStair2(4);
}
public static void drawStair(int height){
if (height <= 0) {
System.out.println("Error");
return;
}else{
for (int i = height -1 ; i >= 0 ; i--) {
for (int j = i ; j < height ; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
public static void drawStair1(int height){
if (height <= 0) {
System.out.println("Error");
return;
}else{
for (int i = height -1 ; i >= 0 ; i--) {
for (int j = 0 ; j < height ; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
public static void drawStair2(int height){
if (height <= 0) {
System.out.println("Error");
return;
}else{
for (int i = 0 ; height > i ; i++) {
for (int j = i ; height > j ; j++) {
System.out.print("*");
}
System.out.println("");
}
}
}
}
<file_sep>package lesson5;
public class Task2 {
public static void main(String[]args) {
String str = "Hello World"; //так делать
String str3 = String.valueOf("Hello World"); //пул строк(отдельный)
String str1 = new String("Hello World"); //так НЕ делать
String str2 = str1;
System.out.println(str == str1);//сравниваются ссылки (адреса в памяти)
System.out.println(str1 == str2);
System.out.println(str3 == str1); //идентичность
System.out.println(str3.equals (str1)); //эквивалентность
}
}
<file_sep>package lesson4;
public class Home3 {
public static void main (String[] args){
int[]array = new int[10];
int minRandom,maxRandom;
printArray(array);
System.out.println(" ");
fillArrayByRandom(array,3,9);
printArray(array);
}
public static void fillArrayByRandom(int[]array,int minRandom, int maxRandom){
for (int i = 0; i < array.length; i++ ){
array[i] = (int)(Math.random()*10); //*(maxrandom-minrandom)
//array[i] = minrandom +(int)(Math.random()*(maxrandom-minrandom))
if ((array[i] >= minRandom) && (array[i] <= maxRandom)){
array[i]=array[i];
}else{
i= i-1;
}
}
}
public static void printArray(int[]array){
for (int i = 0 ; i < array.length ; i++ ){
if (i == 0) {
System.out.print("["+array[i]+",");
}else if ((i > 0) && (i < (array.length-1))) {
System.out.print( array[i]+"," );
}else {
System.out.print(array[i]+"]");
}
}
}
}
<file_sep>package lesson2;
public class Task6 {
public static void main(String []args){
int a = 11;
int b = 10;
boolean result1 = a < b;
System.out.println(result1);
System.out.println(a == b); /*== сравнение равно ли*/
System.out.println(a != b); /*== не равно ли*/
System.out.println(a > b); /*== больше ли*/
System.out.println(a < b); /*== меньше ли*/
System.out.println(a <= b); /*== меньше или равно*/
System.out.println(a >= b); /*== больше или равно*/
}
}
<file_sep>package lesson1;
public class Task2 {
public static void main(String []args){
int value;
value = 110;
System.out.println(value);
value = 15;
System.out.println(value * 10/3);
System.out.println(value);
value = value - 9;
System.out.println(value);
/* Eny text +-/*% */
}
}
<file_sep>package lesson2;
public class Home6 {
public static void main(String []args){
int k1 = 1234567;
System.out.println(k1);
int k2 = (k1 - k1%10)/10;
System.out.println(k2);
int k3 = (k2 - k2%10)/10;
System.out.println(k3);
int k4 = (k3 - k3%10)/10;
System.out.println(k4);
int k5 = (k4 - k4%10)/10;
System.out.println(k5);
int k6 = (k5 - k5%10)/10;
System.out.println(k6);
int k7 = (k6 - k6%10)/10;
System.out.println(k7);
System.out.println(k1%10);
System.out.println(k2%10);
System.out.println(k3%10);
System.out.println(k4%10);
System.out.println(k5%10);
System.out.println(k6%10);
System.out.println(k7%10);
System.out.println("среднее арифметическое - " + (k1%10 + k2%10 + k3%10 + k4%10 + k5%10 + k6%10 + k7%10)/7.0);
}
}
<file_sep>package lesson4;
public class Hometest {
public static void main(String[] args) {
System.out.println("test");
int []array = {1,2,3,4,5};
printArray(array);
}
public static void printArray (int[]array){
for(int i = 0; i < array.length ; i++){
System.out.print(array[i] +" " );
}
}
}
<file_sep>package lesson5;
public class Home2 {
public static void main(String[]args) {
String str = "Hello World Hello World Hello World";
String sub = "lo";
indexOfv2(str, sub);
}
public static void indexOfv2(String str, String sub) {
int idx = 0;
// do{
// idx = str.indexOf(sub,idx);
// if(idx != -1){
// System.out.println(idx);
// idx +=sub.length();
// }
// }while(idx != -1);
//_________________________________________________________________________
// while((idx = str.indexOf(sub, idx)) != -1){ // ()запишется после подсчета
// System.out.println(idx);
// idx +=sub.length();
// System.out.println("+="+ idx);
//
// }
//_________________________________________________________________________
for (int i = 0;(i=str.indexOf(sub, i)) != -1; i += sub.length()){
System.out.println(i);
}
}
}<file_sep>package lesson4;
public class Task1 {
public static void main(String[] args) {
//int [] array = {4, 2, 5, 1, 6}; //литерал типа массив
int [] array = new int[10];
//System.out.println(array[0]);
//System.out.println(array[4]); // встроенно в ждк (оут оф боундс - вне размерности массива(элемента нет под таким индексом))
int val = array[4];
array[0] = 999;
// System.out.println(array[0]);
// System.out.println(array+ "");
// System.out.println("");
//записать массив случайными значениями
int idx = 0;
while (idx < array.length){
int rnd = (int)( Math.random() * 100);
array[idx] = rnd;
idx++;
}
idx = 0;
while(idx < array.length){ //length - хранит колличество элементов массива
System.out.print(array[idx]+ " ");
idx++;
}
System.out.println("");
idx = 0;
while(idx < array.length){
if (array[idx] < 50){
array[idx] = 0;}
//System.out.print(array[idx]+ " "); //print вывод в стоку println- в столбец
idx++;
}
idx = 0;
while(idx < array.length){ //length - хранит колличество элементов массива
System.out.print(array[idx]+ " ");
idx++;
}
}
}
<file_sep>package lesson4;
public class Home0 {
public static void main (String[] args){
int[]array = {1,2,3,4,5,6,7,8,9};
calcNonPairCount(array);
}
public static void calcNonPairCount (int[]array){ //int
int index = 0;
for(int i = 0; i < array.length; i++){
if (array[i]%2 == 1) {
index ++;
}
}
System.out.println(" Непарных - " + index); //return index
}
}<file_sep>package lesson6;
import java.io.FileWriter; //в файлик
import java.io.IOException;//исключения
public class Task5 {
public static void main(String[] args) throws IOException {
//путь мак
FileWriter writer = new FileWriter("/Alex/Desctop/text.txt",true); //true дописывает
for (int i = 0; i < 1000; i++){
writer.write("Hello World" + System.lineSeparator());//что пишем или дописываем в файл- буферизируется
} //System.lineSeparator()- подстраивает под операционку
//проверить буфер ссд)))) 745 строк на уроке влезло
//writer.flush();//записать с буфера в файл
writer.close();//прекратить обращение к врайтеру
}
}
<file_sep>package lesson2;
import java.util.Scanner;
public class Task4 {
public static void main(String []args){
Scanner scan = new Scanner(System.in);
System.out.println("Введите первое число");
int val1 = scan.nextInt();
System.out.println("Введите второе число");
int val2 = scan.nextInt();
double zadacha = Math.pow(val1, 1.0 / val2); /* задачка на вичисление корня квадратного 2го числа из 1го */
System.out.println(zadacha);
}
}
<file_sep>package lesson2;
import java.util.Scanner;
import java.io.*;
public class Home2 {
public static void main(String []args){
Scanner in = new Scanner(System.in);
System.out.println("Введите имя пользователя");
String usr = in.next();
System.out.println("Hello" + " " + usr);
System.out.println("Введите 1-е число");
int val1 = in.nextInt();
System.out.println("Введите 2-е число");
int val2 = in.nextInt();
System.out.println("Введите 3-е число");
int val3 = in.nextInt();
if ((val1 > val2) && (val1 > val3) && (val2 > val3)) {
System.out.println("Большее - " + val1 + ", Меньшее - " + val3 + "");
}
if ((val1 > val2) && (val1 > val3) && (val2 < val3)) {
System.out.println("Большее - " + val1 + ", Меньшее - " + val2 + "");
}
if ((val2 > val1) && (val2 > val3) && (val1 > val3)) {
System.out.println("Большее - " + val2 + ", Меньшее - " + val3 + "");
}
if ((val2 > val1) && (val2 > val3) && (val1 < val3)) {
System.out.println("Большее - " + val2 + ", Меньшее - " + val1 + "");
}
if ((val3 > val1) && (val3 > val2) && (val1 > val2)) {
System.out.println("Большее - " + val3 + ", Меньшее - " + val2 + "");
}
if ((val3 > val1) && (val3 > val2) && (val1 < val2)) {
System.out.println("Большее - " + val3 + ", Меньшее - " + val1 + "");
}
}
}
<file_sep>package lesson2;
import java.util.Scanner;
import java.io.*;
public class Home3 {
public static void main(String []args){
Scanner in = new Scanner(System.in);
System.out.println("Введите имя пользователя");
String usr = in.next();
System.out.println("Hello" + " " + usr);
System.out.println("Введите первое число");
int val1 = in.nextInt();
System.out.println("Введите второе число");
int val2 = in.nextInt();
if (val1 > val2) {
System.out.println(val1);
}
if (val2 > val1) {
System.out.println(val2);
}
else {
System.out.println("Числа равны ");
}
}
}
<file_sep>package lesson2;
import java.util.Scanner;
import java.io.*;
public class Home9 {
public static void main(String []args){
Scanner in = new Scanner(System.in);
System.out.println("Введите координаты точчки в декартовой системе коодинат");
long x = in.nextLong();
System.out.println("x = " + x);
long y = in.nextLong();
System.out.println("y = " + y);
if (x == 0 && y == 0){
System.out.println("Точка находится между четвертями , 0");
}
else if (x >= 0 && y >= 0){
System.out.println("Точка находится в 1-й четверти");
}
else if (x <= 0 && y >= 0){
System.out.println("Точка находится в 2-й четверти");
}
else if (x <= 0 && y <= 0){
System.out.println("Точка находится в 3-й четверти");
}
else if (x >= 0 && y <= 0){
System.out.println("Точка находится в 4-й четверти");
}
}
}
<file_sep>package lesson3;
import java.util.Scanner;
import java.io.*;
public class Task3 {
public static void main(String []args){
int i = 0; //пока было больше 10 вывод 10
do{
System.out.println(i);
i++;
}while (i<10);
}
}<file_sep>package lesson2;
import java.util.Scanner;
import java.io.*;
public class Home5_1 {
public static void main(String []args){
Scanner in = new Scanner(System.in);
/*
System.out.println("Введите певую переменную");
byte val1 = in.nextByte();
System.out.println("Введите вторую переменную");
float val2 = in.nextFloat();
System.out.println("Byte" + " " + val1);
System.out.println("Float" + " " + val2);
// /* x = 1; y = 3 */
// val1 *= val2; /* x = x + y = 1 +(*) 3 = 4 */
// val2 = (byte)(val1 / val2); /* y = x - y = 4 -(/) 3 = 1 */
// val1 /= val2; /* x = y - x = 4 -(/) 1 = 3 */
byte b = 10;
float f = 15.2F;
System.out.println(b);
System.out.println(f);
b = (byte) (f + b); // будет округление 15.2 to 15
System.out.println(b);
f = b- f;
System.out.println(f);
b = (byte)(b - f);
System.out.println(b);
// System.out.println("Byte" + " " + val1);
// System.out.println("Float" + " " + val2);
}
}
<file_sep>package lesson2;
public class Task7 {
public static void main(String []args){ /*Конструкция условий*/
int age = 17;
/* ; означает конец инструкции,не будет связывать последующий вывод*/
if(age >= 18){ /*{ } если условие не выполняется то то что в скобках не выводится */
System.out.println("ты совершеннолетний");
} else {
System.out.println("ты НЕ совершеннолетний ");
}
System.out.println("Конец опроса");
}
}
<file_sep>package lesson5;
public class Task1 {
public static void main(String[]args) {
int val = 10;
String str = " Hello World "; //так делать
String str1 = new String("Hello World"); //так НЕ делать
System.out.println(str1);
String str2 = String.valueOf(val); //и так делать
System.out.println(str1 +" "+ str2);
System.out.println(str.length());
System.out.println(str2.length());
System.out.println(str.charAt(0));
String sub = str.substring(3); // с 3го и до конца
System.out.println(sub);
String sub1 = str.substring(3,7); // с 3го по 7 (не включая)
System.out.println(sub1);
String res = str.trim(); //трим убирает пробелы
System.out.println(res);
String conc = str.concat(" fooo"); //склеить строку
System.out.println(conc);
String toUpper = str.toUpperCase(); //в верхний регистр (loLowerCase)
System.out.println(toUpper);
System.out.println(str1.contains("Hello"));//совпадает ли целиком
System.out.println(str1.indexOf("world"));//индекс в котором начинается совпадение
System.out.println(str1.indexOf("World"));//индекс в котором начинается совпадение
System.out.println(str1.indexOf('W')); // один чар ' ' для одного символа
System.out.println(str1.lastIndexOf('W')); //ищет с конца метод последнего вхождения
//str1.indexOf(, fromIndex) //искать начиная с индекса
//public static void indexof(String str , String sub){
//вывести индексы всех вхождений(если их много)(метод который INdex oF,fromIndex)
//}
System.out.println(str == str1);
}
}
<file_sep>package lesson4;
public class Task4 {
//очередность описания метода не важнаю
//описание не может быть внутри дугого метоад
//описание может быть в любом месте класса
public static void main(String[] args) {
Task4.sayHello("Sasha");
Task4.sayHello("Sasha))");
// TODO Auto-generated method stub
int max = Math.max(3, 6); //max - metod
System.out.println(max); //println - metod
int result = Task4.sum(2, 3);
System.out.println(result);
}
//void такой метод никакого значение не отдает в консоль(результат)
public static void sayHello(String name){ //не с цифры метод имя
System.out.println("Hi heloo ooo - " + name);
}
public static int sum(int a,int b){
int val = a + b; //процедура ничего не возвращает
return val ; // функция - обрабатывает и возвращает результат
}
}
<file_sep>package lesson2;
import java.util.Scanner; /*подключаем инструмент*/
public class Task3 {
public static void main(String []args){
Scanner scan = new Scanner(System.in); /*Создаем инструмент*/
System.out.println("Введите число");
int val1 = scan.nextInt(); /*Используем созданный сканнер (блокирующий ввод ожидающий ввода с консоли)*/
System.out.println("Введите еще разок");
int val2 = scan.nextInt(); /*Используем созданный сканнер (блокирующий ввод ожидающий ввода с консоли)*/
System.out.println(val1 + " + " + val2 + " * " + val1 + " = " + (val1 + val2 * val1));
System.out.println("Вы ввели : ");
System.out.println(val1 + val2 * val1);
}
}
<file_sep>package lesson4;
public class Home10 {
public static void main(String[] args) {
drawRectangle(6, 5);
}
public static void drawRectangle(int height, int width) {
if (((height <= 0) && (width <= 0))||(height <= 0)||(width <= 0)){
System.out.println("Error");
return;
}else{
for (int i = 0 ; height > i ; i++) {
for (int j = 0 ; width > j ; j++) {
System.out.print("*");
}
System.out.println(" ");
}
}
}
}
<file_sep>package lesson2;
import java.util.Scanner;
import java.io.*;
public class Home8_2 {
public static void main(String []args){
Scanner in = new Scanner(System.in);
System.out.println("Введите год , я проверю высокосный ли он ");
int year = in.nextInt();
if ((year%4 == 0) && (year%100 == 0)) {
System.out.println(year + " - " + "Год Не высокосный");
}else if (((year%400 == 0) && (year%100 == 0) && (year%4 == 0)) || (year%4 == 0)) {
System.out.println(year + " - " + "Год высокосный");
}else{
System.out.println(year + " - " + "Год Не высокосный");
}
}
}
<file_sep>package lesson3;
import java.util.Scanner;
import java.io.*;
public class Task5 {
public static void main(String []args){
Scanner scan = new Scanner(System.in);
int rnd = (int)( Math.random() * 100);
int input;
int count = 0;
int modul;
do{
count++;
System.out.println("Введите число");
input = scan.nextInt();
if ((Math.abs(input-rnd) <= 3) && (count <11 ) && (Math.abs(input-rnd) != 0)){
System.out.println("Гарячо !" );
}else if ((input > rnd) && (count < 11)){
System.out.println("твое Число больше");
}else if ((input < rnd) && (count < 11)) {
System.out.println(" твое Число меньше"); // бинарный поиск - деление
}else if ((input == rnd) && (count < 11)) {
System.out.println("Ураа, " + "тебе нужно было " + count + " попытки" + " чтобы угадать число - " + rnd );
}else if (count > 10){
System.out.println("Количество попыток > 10 " + " Я загадал -" +rnd);
input = rnd;
}
modul = Math.abs(input-rnd);
// count++; // count = ++count;
//System.out.println(modul + " modul, " + input + " input, " + rnd + " rnd");
} while (rnd != input);
}
}
<file_sep>package lesson4;
public class Home1 {
public static void main(String[] args) {
int[]array = {1,2,3,4,5,6,7,8,9,10};
printArray(array);
}
public static void printArray(int[]array) {
for (int i = 0 ; i < array.length ; i++ ){
if (i == 0) {
System.out.print("["+array[i]+";");
}else if ((i > 0) && (i < (array.length-1))) {
System.out.print( array[i]+";" );
}else {
System.out.println(array[i]+"]");
}
}
}
}<file_sep>package lesson2;
import java.util.Scanner;
import java.io.*;
public class Home8 {
public static void main(String []args){
Scanner in = new Scanner(System.in);
System.out.println("Введите год , я проверю высокосный ли он");
int year = in.nextInt();
if ((year%4 == 0) && (year%100 != 0) || (year % 400 == 0)) {
//1900 ((true(1) && false(0)) = false(0) || false(0) = (false(0)) === false(0) "Год Не высокосный"
//2000 ((true(1) && false(0)) = false(0) || true(1) = (true(1)) === true(1) "Год высокосный"
//2004 ((true(1) && true(1)) = true(1) || false(0) = (false(0)) === true(1) "Год высокосный"
System.out.println(year + " - " + "Год высокосный");
}else{
System.out.println(year + " - " + "Год Не высокосный");
}
}
}
| efc911149fbbf297b4edba81088952d0464e3d70 | [
"Java"
] | 31 | Java | bla3e316/OOP | 48e1180198049c8ec4233296f86da9e7e07386d4 | b6ce6c44383e3bbc09ce16d6f70b89e7888f17c9 |
refs/heads/master | <repo_name>vingenuity/mr-assassin<file_sep>/MRAssassin/src/com/badideastudios/mrassassin/ReceiverC2DM.java
package com.badideastudios.mrassassin;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.util.Log;
public class ReceiverC2DM extends BroadcastReceiver {
private static String KEY = "c2dmPref";
private static String REGISTRATION_KEY = "registrationKey";
private SharedPreferences sharedPrefsAssassin;
private Context context;
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("Message receieved");
this.context = context;
if(intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION"))
{
handleRegistration(context, intent);
}else if(intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE"))
{
handleMessage(context, intent);
}
}
private void handleRegistration(Context context, Intent intent)
{
String registration = intent.getStringExtra("registration_id");
if(intent.getStringExtra("eror") != null)
{
Log.d("c2dm", "registration failed");
String error = intent.getStringExtra("error");
if(error == "SERVICE_NOT_AVAILABLE"){
Log.d("c2dm", "SERVICE_NOT_AVAILABLE");
}else if(error == "ACCOUNT_MISSING"){
Log.d("c2dm", "ACCOUNT_MISSING");
}else if(error == "AUTHENTICATION_FAILED"){
Log.d("c2dm", "AUTHENTICATION_FAILED");
}else if(error == "TOO_MANY_REGISTRATIONS"){
Log.d("c2dm", "TOO_MANY_REGISTRATIONS");
}else if(error == "INVALID_SENDER"){
Log.d("c2dm", "INVALID_SENDER");
}else if(error == "PHONE_REGISTRATION_ERROR"){
Log.d("c2dm", "PHONE_REGISTRATION_ERROR");
}
}else if(intent.getStringExtra("unregistered") != null)
{
Log.d("c2dm", "unregistered");
System.out.println("Unregistration successful");
}else if(registration != null)
{
sharedPrefsAssassin = context.getSharedPreferences("AssassinPrefs", 0);
Editor editor2 = sharedPrefsAssassin.edit();
editor2.putString(REGISTRATION_KEY, registration);
editor2.commit();
Log.d("c2dm", registration);
// Editor edit = sharedPrefs.edit();
Editor editor = context.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
editor.putString(REGISTRATION_KEY, registration);
editor.commit();
// Attempts to update C2DM regID from the C2DM receiver
/*
Context context3 = context.getApplicationContext();
CreateUserTask cut = new CreateUserTask((Activity) context3);
//cut.SetAddress("http://mr-assassin.appspot.com/rest/assassin");
//cut.SetContent("5");
cut.SetAddress("http://mr-assassin.appspot.com/rest/update/assassin");
cut.SetContentType("application/xml");
String updateC2DM = "<assassin>" +
"<tag>" +
sharedPrefsAssassin.getString("Username", "") +
"</tag>" +
"<regID>" +
sharedPrefsAssassin.getString("registrationKey", "") +
"</regID>" +
"</assassin>";
System.out.println(sharedPrefsAssassin.getString("registrationKey", ""));
cut.SetContent(updateC2DM);
cut.execute();
*/
}
}
private void handleMessage(Context context, Intent intent)
{
System.out.println("Message handled");
String message = intent.getExtras().getString("payload");
String killed = "killed";
String warning = "warning";
if(message.equals(killed))
{
NotificationManager nManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.dagger;
CharSequence tickerText = "DEAD";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
Context context2 = context.getApplicationContext();
CharSequence contentTitle = "MRAssassins";
CharSequence contentText = "You have been killed by a pursuer!";
Intent notificationIntent = new Intent(context, ReceiverC2DM.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
sharedPrefsAssassin = PreferenceManager.getDefaultSharedPreferences(context);
if( sharedPrefsAssassin.getBoolean("NoteSoundPref", true) == true)
notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.stab);
if( sharedPrefsAssassin.getBoolean("NoteVibePref", true) == true)
notification.defaults |= Notification.DEFAULT_VIBRATE;
final int KILL_ID = 1;
nManager.notify(KILL_ID, notification);
}
if(message.equals(warning))
{
NotificationManager nManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.dagger;
CharSequence tickerText = "WARNING";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
Context context2 = context.getApplicationContext();
CharSequence contentTitle = "MRAssassins";
CharSequence contentText = "A pursuer is nearby!";
Intent notificationIntent = new Intent(context, ReceiverC2DM.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
sharedPrefsAssassin = PreferenceManager.getDefaultSharedPreferences(context);
if( sharedPrefsAssassin.getBoolean("NoteSoundPref", true) == true)
notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.warning);
if( sharedPrefsAssassin.getBoolean("NoteVibePref", true) == true)
notification.defaults |= Notification.DEFAULT_VIBRATE;
final int WARN_ID = 1;
nManager.notify(WARN_ID, notification);
}
Log.e("", "message: " + message);
// Handle the message here
}
}
<file_sep>/MRAssassin/src/com/badideastudios/mrassassin/MoneyListAdapter.java
package com.badideastudios.mrassassin;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class MoneyListAdapter extends BaseAdapter
{
private ArrayList<AssassinObj> list;
private LayoutInflater mInflater;
public MoneyListAdapter(Context context, ArrayList<AssassinObj> list)
{
mInflater = LayoutInflater.from(context);
this.list = list;
}
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.stat_list_item, parent, false);
}
TextView title = (TextView) convertView.findViewById(R.id.stat_title_text);
TextView sub = (TextView) convertView.findViewById(R.id.stat_summary_text);
AssassinObj assassin = list.get(position);
title.setText( assassin.returnTag() );
sub.setText( "$" + Integer.toString( assassin.returnMoney() ) );
sub.setTextColor(Color.YELLOW);
return convertView;
}
public int getCount()
{
return list.size();
}
public Object getItem(int arg0)
{
return list.get(arg0);
}
public long getItemId(int arg0)
{
return arg0;
}
}
<file_sep>/README.md
MRAssassin is a mixed-reality game in which players use Android phones to assassinate each other in the real world.
This game was my capstone project at Texas A&M.
This project is a refugee from the recent closure of Google Code.
Automatically exported from code.google.com/p/mr-assassin
<file_sep>/MRAssassin/src/com/badideastudios/mrassassin/LoginActivity.java
package com.badideastudios.mrassassin;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity
{
private EditText userForm;
//private EditText passForm;
private EditText servForm;
private SharedPreferences settings;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
userForm = (EditText) findViewById(R.id.username_entry);
//passForm = (EditText) findViewById(R.id.password_entry);
servForm = (EditText) findViewById(R.id.server_entry);
/* Load previous user settings, if available. */
settings = getSharedPreferences("AssassinPrefs", 0);
String savedName = settings.getString("Username", ""), savedServer = settings.getString("Server", "");
if(savedName.length() > 0)
userForm.setText(savedName);
if(savedServer.length() > 0)
servForm.setText(savedServer);
}
public void onDestroy()
{
super.onDestroy();
Intent unregIntent = new Intent("com.google.android.c2dm.intent.UNREGISTER");
unregIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));
startService(unregIntent);
}
public void login(View v)
{
// If all fields are not empty...
if(userForm.length() <= 0 /*|| passForm.length() <=0 */|| servForm.length() <= 0)
{
Toast.makeText(this, "All fields must be filled in.", Toast.LENGTH_LONG).show();
return;
}
/* Grab the form data. */
String username, server;
//String password;
username = userForm.getText().toString();
//password = <PASSWORD>Form.getText().toString();
server = servForm.getText().toString();
/* Check for any errors. */
if( username.contains(" ") )
{
Toast.makeText(this, "Username cannot contain a space.", Toast.LENGTH_LONG).show();
return;
}
/*if( password.length() < 6 )
{
Toast.makeText(this, "Password is too short. Password must be at least 6 characters.", Toast.LENGTH_LONG).show();
return;
}*/
/* Save user name and server data to user preferences for use if they need to login again. */
settings = getSharedPreferences("AssassinPrefs", 0);
SharedPreferences.Editor settingEditor = settings.edit();
settingEditor.putString("Username", username);
settingEditor.putString("Server", server);
// Send a command to the server to create the user
// If they already exist, the server ignores this command
String xmlString = new String();
xmlString = "<assassin>" +
"<tag>" +
username +
"</tag>" +
"</assassin>";
CreateUserTask cut = new CreateUserTask(this);
cut.SetAddress("http://mr-assassin.appspot.com/rest/add/assassin");
cut.SetContent(xmlString);
cut.SetContentType("application/xml");
cut.execute();
/*
CreateUserTask cut2 = new CreateUserTask(this);
cut2.SetAddress("http://mr-assassin.appspot.com/rest/get/newtarget");
cut2.SetContent("");
cut2.SetContent("plain/text");
cut2.execute();
*/
settingEditor.commit();
/* Perform a login at our server. */
/* Launch the game. */
Intent gameActivity = new Intent(getBaseContext(), TabWidget.class);
startActivity(gameActivity);
}
/** Handle the menu button press and present options */
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.login_menu, menu);
return true;
}
/** Handle callback when a menu option is selected */
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch( item.getItemId() )
{
case R.id.exit:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
<file_sep>/MRAssassin/src/com/badideastudios/mrassassin/LeaderboardHandler.java
package com.badideastudios.mrassassin;
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class LeaderboardHandler extends DefaultHandler {
StringBuffer buffer;
ArrayList<AssassinObj> assassinList = new ArrayList<AssassinObj>();
AssassinObj assassin = new AssassinObj();
@Override
public void startDocument() throws SAXException
{
// Called when the document starts
}
@Override
public void endDocument() throws SAXException
{
// Called when the document ends
}
@Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException
{
if(localName.equals("following"))
{
System.out.println("Do nozing!");
}
if(localName.equals("assassin"))
assassin = new AssassinObj();
if(localName.equals("tag"))
buffer = new StringBuffer();
else if(localName.equals("target"))
buffer = new StringBuffer();
else if(localName.equals("bounty"))
buffer = new StringBuffer();
else if(localName.equals("lon"))
buffer = new StringBuffer();
else if(localName.equals("lat"))
buffer = new StringBuffer();
else if(localName.equals("money"))
buffer = new StringBuffer();
else if(localName.equals("macaddr"))
buffer = new StringBuffer();
else if(localName.equals("kills"))
buffer = new StringBuffer();
//assassinName = atts.getValue("name");
// Called each time the parser starts a new element
}
@Override
public void characters(char ch[], int start, int length) throws SAXException
{
for(int i = start; i < start + length; i ++)
{
buffer.append(ch[i]);
}
// Called when the parser encounters characters between tags
}
@Override
public void endElement(String namespaceURI, String localName, String qName) throws SAXException
{
if(localName.equals("tag"))
assassin.setTag(buffer.toString());
else if(localName.equals("target"))
assassin.setTarget(buffer.toString());
else if(localName.equals("bounty"))
assassin.setBounty(Integer.parseInt(buffer.toString()));
else if(localName.equals("lon"))
assassin.setLon(Double.parseDouble(buffer.toString()));
else if(localName.equals("lat"))
assassin.setLat(Double.parseDouble(buffer.toString()));
else if(localName.equals("money"))
assassin.setMoney(Integer.parseInt(buffer.toString()));
else if(localName.equals("macaddr"))
assassin.setMAC(buffer.toString());
else if(localName.equals("kills"))
assassin.setKills(Integer.parseInt(buffer.toString()));
else if(localName.equals("assassin"))
assassinList.add(assassin);
// Called when the parser ends an element
}
}
<file_sep>/MRAssassin/src/com/badideastudios/mrassassin/LauncherActivity.java
package com.badideastudios.mrassassin;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
public class LauncherActivity extends Activity
{
private SharedPreferences sharedPrefs;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
sharedPrefs = getSharedPreferences("AssassinPrefs", 0);
/** Set up C2DM */
Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0)); // Boilerplate
registrationIntent.putExtra("sender", "<EMAIL>");//"<EMAIL>");
startService(registrationIntent);
/*Get C2DM identifier */
String savedC2DM_ID = sharedPrefs.getString("registrationKey", "");
/* If we have user data already available, just run, else show login */
if(sharedPrefs.getString("Username", "") == "" || sharedPrefs.getString("Server", "") == "" )
{
Intent loginActivity = new Intent(getBaseContext(), LoginActivity.class);
startActivity(loginActivity);
}
else
{
Intent gameActivity = new Intent(getBaseContext(), TabWidget.class);
startActivity(gameActivity);
}
finish();
}
}
| e67c543ddbed78650203a7eb2913181d1d49e06a | [
"Markdown",
"Java"
] | 6 | Java | vingenuity/mr-assassin | afe2b8411e9add18aa4c0fc396382950a481a43f | 6c4551be37e39f9140018abaf2fa779999757c43 |
refs/heads/master | <repo_name>cavoixanha/blog<file_sep>/README.md
# README
## Run step by step ##
```ruby
rake db:create
rake db:migrate
rake db:seed
```
## Username/Password ##
**Username:**
<EMAIL>
<EMAIL>
<EMAIL>
**Password (all user use same password)**
<PASSWORD>//
## Require Login when "New Post" and "Comment on Post" ##
Login with username and password above
## Link ##
Posts:
https://blog-nam.herokuapp.com/
Comment on Post (click to show)
https://blog-nam.herokuapp.com/posts/16
SignIn(Click on Sign In on navigation bar)
https://blog-nam.herokuapp.com/users/sign_in
### Sort Post click Button Asc and Desc right of title Post ###
## Provides a RESTful API for retrieve posts ##
List Post
https://blog-nam.herokuapp.com/api/v1/posts
Search Post on FullTextSearch
https://blog-nam.herokuapp.com/api/v1/posts/search?term=Veniam%20adipisci
## GitHub ##
https://github.com/cavoixanha/blog
## Heroku ##
https://blog-nam.herokuapp.com
## Gem Use ##
```ruby
gem 'devise'
# See https://github.com/rails/execjs#readme for more supported runtimes
gem 'therubyracer', platforms: :ruby
# UI
gem 'simple_form'
gem "less-rails" #Sprockets (what Rails 3.1 uses for its asset pipeline) supports LESS
gem "twitter-bootstrap-rails", '3.2.2'
# gem 'bootstrap-sass', '~> 3.3.6'
gem 'haml-rails'
gem 'kaminari'
# gem 'kaminari_themes', :git => 'https://github.com/amatsuda/kaminari_themes.git'
gem "pundit"
gem "pg_search"
gem 'faker'
group :development, :test do
# If you use gems that require environment variables to be set before they are loaded,
# then list dotenv-rails in the Gemfile before those other gems and require dotenv/rails-now.
gem 'dotenv-rails', require: 'dotenv/rails-now'
gem 'capistrano-env-config'
end
```
<file_sep>/app/policies/post_policy.rb
class PostPolicy < ApplicationPolicy
class Scope < Scope
def resolve
scope
end
end
def update?
return true if user.present? && user == post.user
end
def destroy?
return true if user.present? && user == post.user
end
private
def post
record
end
end
<file_sep>/db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
require 'faker'
puts "### 1/3 ###"
users = User.create!([
{email: "<EMAIL>", password: "<PASSWORD>//", password_confirmation: "<PASSWORD>//", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 1, current_sign_in_at: "2015-02-06 14:02:10", last_sign_in_at: "2015-02-06 14:02:10", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1"},
{email: "<EMAIL>", password: "<PASSWORD>//", password_confirmation: "<PASSWORD>//", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 1, current_sign_in_at: "2015-02-06 14:03:01", last_sign_in_at: "2015-02-06 14:03:01", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1"},
{email: "<EMAIL>", password: "<PASSWORD>//", password_confirmation: "<PASSWORD>//", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 1, current_sign_in_at: "2015-02-06 14:03:44", last_sign_in_at: "2015-02-06 14:03:44", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1"}
])
puts "### 2/3 ###"
posts =
15.times do |i|
begin
Post.create(title: Faker::Lorem.sentence, description: Faker::Lorem.paragraph, user_id: User.order("RANDOM()").first.id)
rescue => e
puts "Error #{e.message}"
end
end
puts "### 3/3 ###"
comment =
15.times do |i|
begin
Comment.create(message: Faker::Lorem.sentence, post_id: Post.order("RANDOM()").first.id, user_id: User.order("RANDOM()").first.id)
rescue => e
puts "Error #{e.message}"
end
end
<file_sep>/config/deploy.rb
# config valid only for current version of Capistrano
lock "3.8.1"
set :application, "bag_umbala"
set :repo_url, ENV['GIT']
# Default branch is :master
set :branch, 'master'
# ask :branch, `git rev-parse --abbrev-ref HEAD`.chomp
# Default deploy_to directory is /var/www/my_app_name
# set :deploy_to, "/var/www/my_app_name"
set :deploy_root, '/home/deploy'
set :deploy_to, "#{fetch(:deploy_root)}/bag-umbala"
set :deploy_via, :remote_cache
# set :scm, :git
# Default value for :format is :airbrussh.
# set :format, :airbrussh
set :format, :pretty
# You can configure the Airbrussh format using :format_options.
# These are the defaults.
# set :format_options, command_output: true, log_file: "log/capistrano.log", color: :auto, truncate: :auto
# Default value for :pty is false
set :pty, true
set :ssh_options, {:forward_agent => true}
# default_run_options[:pty] = true
# Default value for :linked_files is []
# append :linked_files, "config/database.yml", "config/secrets.yml"
# Default value for linked_dirs is []
# append :linked_dirs, "log", "tmp/pids", "tmp/cache", "tmp/sockets", "public/system"
# Default value for default_env is {}
# set :default_env, { path: "/opt/ruby/bin:$PATH" }
require 'capistrano/rvm'
set :rails_env, 'production'
set :rvm_type, :user
set :rvm_ruby_version, '2.2.2'
set :default_env, {rvm_bin_path: "~/.rvm/bin"}
set :environment, "production"
require 'sshkit'
# SSHKit.config.default_env = { BAG_UMBALA_DATABASE_USERNAME: '. $HOME/.bash_profile; echo $BAG_UMBALA_DATABASE_USERNAME' }
# bundler
require "capistrano/bundler"
puts "shared_path: #{shared_path}"
puts "release_path: #{release_path}"
puts "env: #{ENV['BAG_UMBALA_DATABASE_USERNAME']}"
set :bundle_gemfile, -> { release_path.join('Gemfile') }
set :bundle_dir, -> { shared_path.join('bundle') }
set :bundle_flags, ''
set :bundle_without, %w{test development}.join(' ')
set :bundle_binstubs, -> { release_path.join('bin') }
set :bundle_roles, :all
set :stages, ["staging", "production"] # importance
set :default_stage, "production" # importance
set :assets_roles, [:web, :app]
set :rails_assets_groups, :assets
# set :instance_id, "i-082f935ffdf336ce0"
# set :file_socket, "unicorn.qlxekhachGT.sock"
# Default value for keep_releases is 5
set :keep_releases, 5
# set :whenever_identifier, ->{ "#{fetch(:application)}_#{fetch(:stage)}" }
desc 'Test Task'
task :test do
on roles(:db) do
puts "bundle_gemfile: #{fetch(:bundle_gemfile)}"
puts "bundle_binstubs: #{fetch(:bundle_binstubs)}"
# run "#{sudo} echo 'Hello World' > ~/hello"
# execute("cd #{deploy_to}/current && ~/.rvm/bin/rvm 2.2.2 do bundle exec rake seo:sitemap")
# split 2 row is error "Could not locate Gemfile or .bundle/ directory"
# execute("cd #{deploy_to}/current")
# execute("~/.rvm/bin/rvm 2.2.2 do bundle exec rake seo:sitemap")
end
end
# gem https://github.com/tablexi/capistrano3-unicorn
set :shared_dir, "#{release_path}/shared"
set :unicorn_pid, "#{fetch(:shared_dir)}/pids/unicorn.pid"
# set :pid, "`cat /home/deploy/bag-umbala/current/shared/pids/unicorn.pid`"
set :unicorn_config_path , "config/unicorn.rb"
# set :use_sudo, false
set :default_env, {
# 'BAG_UMBALA_DATABASE_USERNAME' => '. $HOME/.bash_profile; echo $BAG_UMBALA_DATABASE_USERNAME'
'PHUONG_HENG_DATABASE_HOST' => ENV['PHUONG_HENG_DATABASE_HOST'],
'BAG_UMBALA_DATABASE_USERNAME' => ENV['BAG_UMBALA_DATABASE_USERNAME'],
'BAG_UMBALA_DATABASE_PASSWORD' => ENV['<PASSWORD>'],
'SECRET_KEY_BASE_BAG_UMBALA' => ENV['SECRET_KEY_BASE_BAG_UMBALA'],
'DEVISE_SECRET_KEY_BAG_UMBALA' => ENV['DEVISE_SECRET_KEY_BAG_UMBALA'],
'BACKUP_QLXEKHACH_S3_ACCESS_KEY_ID' => ENV['BACKUP_QLXEKHACH_S3_ACCESS_KEY_ID'],
'BACKUP_QLXEKHACH_SECRET_ACCESS_KEY' => ENV['BACKUP_QLXEKHACH_SECRET_ACCESS_KEY']
# 'LENGTH_SUBDOMAIN' => ENV['LENGTH_SUBDOMAIN']
}
# Thiết lập các chỉ dẫn sau khi deploy tại đây
# Sau khi kết thúc việc deploy, Capistrano sẽ
# thực hiện các lệnh ở dưới.
namespace :deploy do
# desc 'DB Setup'
# task :db_setup do
# on roles(:app), in: :sequence, wait: 10 do
# puts "<---DB Setup---"
# within release_path do
# with rails_env: fetch(:rails_env) do
# execute :rake, 'db:setup'
# execute :rake, 'db:seed'
# # execute :rake, 'db:migrate'
# end
# end
# puts "---DB Setup--->"
# end
# end
desc 'Restart application'
task :restart do
on roles(:app), in: :sequence, wait: 10 do
puts "<---Restart application---"
within release_path do
with rails_env: fetch(:rails_env) do
invoke 'unicorn:legacy_restart'
sleep 3
execute "sudo service unicorn_#{fetch(:application)} restart"
sleep 6
execute "sudo service unicorn_#{fetch(:application)} restart"
# sleep 5
# puts "whats running now, eh unicorn?"
# execute "ps aux | grep unicorn"
# on roles(:app) do |host|
# # execute :sudo, '/etc/init.d/nginx restart'
# # execute :sudo, "/etc/init.d/unicorn_#{fetch(:application)} restart"
# execute :sudo, "service unicorn_#{fetch(:application)} restart"
# # execute :sudo, "aws ec2 reboot-instances --instance-ids #{fetch(:instance_id)}"
# end
# as :app do
# execute "#{fetch(:sudo)} /etc/init.d/unicorn_#{fetch(:application)} restart"
# execute "#{fetch(:sudo)} /etc/init.d/nginx restart"
# end
# on roles(:all) do
# execute "#{fetch(:sudo)} service unicorn_#{fetch(:application)} restart"
# end
# run "#{sudo} service unicorn_#{fetch(:application)} start", { :shell => 'bash'}
end
end
puts "---Restart application--->"
end
end
# %w( start stop restart ).each do |command|
# desc "#{command} unicorn server"
# task command, roles: :app, except: {no_release: true} do
# run "/etc/init.d/unicorn_#{application} #{command}"
# end
# end
desc "Prepare for Unicorn"
task :prepare_for_unicorn do
on roles(:app), in: :groups do
puts "<---Prepare for Unicorn---"
# within release_path do
# with rails_env: fetch(:rails_env) do
# execute "rm -rf shared/pids shared/sockets shared/log"
# execute "cd #{release_path} && mkdir -p shared/pids shared/sockets shared/log"
# # invoke 'deploy:start_unicorn'
# invoke 'unicorn:restart'
# end
# end
within release_path do
with rails_env: fetch(:rails_env) do
execute "cd #{fetch(:deploy_to)} && mkdir -p shared/pids shared/sockets shared/log"
execute "ln -nfs #{fetch(:deploy_to)}/shared #{release_path}/shared"
# invoke 'unicorn:restart'
end
end
puts "---Prepare for Unicorn--->"
end
end
desc "Symlink Shared"
task :symlink_shared do
puts "<---Symlink Shared---"
on roles(:app), in: :groups do
execute "rm -rf #{release_path}/app/store_module_general #{release_path}/app/store_module_private #{release_path}/app/store_module_using"
execute "ln -nfs #{fetch(:shared_dir)}/store_module_general #{release_path}/app/store_module_general"
execute "ln -nfs #{fetch(:shared_dir)}/store_module_private #{release_path}/app/store_module_private"
execute "ln -nfs #{fetch(:shared_dir)}/store_module_using #{release_path}/app/store_module_using"
execute "rm -rf #{release_path}/public/uploads"
execute "ln -nfs #{fetch(:shared_dir)}/uploads #{release_path}/public/uploads"
execute "ln -nfs #{fetch(:shared_dir)}/log/my_log4r.log #{release_path}/my_log4r.log"
end
puts "---Symlink Shared--->"
end
desc "Update the crontab file"
task :update_crontab do
puts "<---Update Crontab---"
on roles(:app), in: :groups do
within release_path do
execute :bundle, :exec, :"whenever --update-crontab #{fetch(:application)}"
end
end
puts "---Update Crontab--->"
end
desc "Prepare Seo File and Unicorn, then restart service"
after :publishing, :prepare do
on roles(:app), in: :groups do
puts "<---Prepare Seo File and Unicorn, then restart service---"
within release_path do
with rails_env: fetch(:rails_env) do
# execute :rake, 'seo:sitemap'
# execute :rake, "permissions:load_permissions"
# invoke "deploy:update_crontab"
invoke "deploy:symlink_shared"
invoke "deploy:prepare_for_unicorn"
invoke "deploy:restart"
end
end
puts "---Prepare Seo File and Unicorn, then restart service--->"
end
end
# after :restart, :clear_cache do
# on roles(:web), in: :groups, limit: 3, wait: 10 do
# # Here we can do anything such as:
# within release_path do
# # execute :rake, 'cache:clear'
# execute :rake, 'tmp:cache:clear'
# end
# end
# end
end<file_sep>/app/models/post.rb
class Post < ApplicationRecord
include PgSearch
pg_search_scope :search_full_text, against: {
title: "A",
description: "C"
}
belongs_to :user
has_many :comments, dependent: :destroy
scope :sort_by_created_at_desc, -> { order(created_at: :desc ) }
scope :sort_by_created_at_asc, -> { order(:created_at ) }
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
resources :comments
root 'posts#index'
resources :posts do
resources :comments do
collection do
get 'new_comment_for_post', as: :new_comment_for_post
end
end
# collection do
# get 'new_comment_for_post', as: :new_comment_for_post
# end
end
devise_for :users#, :controllers => { :sessions => "sessions" }
namespace :api do
namespace :v1 do
resources :posts do
collection do
get 'search'
end
end
resources :comments
end
end
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
| 5024069b1492fba7bb5b3503748ff0e61d806077 | [
"Markdown",
"Ruby"
] | 6 | Markdown | cavoixanha/blog | 87ea15e1080294fbbd05ac424769598e39a53dd5 | b02656192f8d9c991bbe5e71b72a5bb17b5a8531 |
refs/heads/master | <repo_name>wym037935/flanker<file_sep>/hw/list.py
#coding=utf-8
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render_to_response
import MySQLdb
import re
import os
import database
import init
import newtask
import thread
import subprocess
from apscheduler.schedulers.blocking import BlockingScheduler
class Task:
def __init__(self,taskname,status):
self.taskname=taskname
self.status=status
@csrf_exempt
def index(request):
init.first()
try:
buttonvalue = ''
task = ''
if request.POST.has_key('tasklist'):
buttonvalue = str(request.POST['buttonvalue'])
task = str(request.POST['tasklist'])
if(buttonvalue == "delete"):
database.execute('delete from tasklist where name = \'%s\'' % (task))
database.execute('delete from edges where u = \'%s\' or v = \'%s\'' % (task,task))
ss = str(request.path)
site = ""
if(buttonvalue == "modify"):
site = "modifypage/%s" % (task)
if(buttonvalue == "info"):
site = "infopage/%s" % (task)
if(buttonvalue == "presub"):
site = "/prepage"
if(buttonvalue == "start"):
database.execute('update tasklist set status = \'started\' where name = \'%s\'' %task)
init.checktask(task)
#fw = open('listerr.txt','a')
#fw.write(buttonvalue)
#fw.write('\n python scheduler.py %s %s.sql\n' %(task,task))
#fw.close()
if(buttonvalue == "execute"):
subprocess.Popen('python hw/scheduler.py %s %s.sql' %(task,task), shell = True)
if(buttonvalue == "terminate"):
res = database.getlist('select status from tasklist where name = \'%s\'' %task)[0]
if res == 'started':
database.execute('update tasklist set status = \'did not start\' where name = \'%s\'' %task)
elif res == 'running':
database.execute('update tasklist set status = \'failed\' where name = \'%s\'' %task)
fw = open("log.txt","w")
fw.write(site)
fw.close()
tasklist = database.getlist('select name from tasklist')
statuslist = database.getlist('select status from tasklist')
ll = []
for i in range(0,len(tasklist)):
ll.append(Task(tasklist[i],statuslist[i]))
return render_to_response('taskpage.html', {'tasklist': ll,'skipsite': site})
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
ferr = open("error.txt","w")
ferr.write("Mysql Error %d: %s" % (e.args[0], e.args[1]))
ferr.close()
<file_sep>/hw/work.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import loader,Context,RequestContext
from django.views.decorators.csrf import csrf_exempt
import subprocess
import MySQLdb
import sys
import os
import timevar
import init
@csrf_exempt
def work(request):
init.first()
code = ""
buttonvalue = ""
address = '127.0.0.1'
sqlname = 'python'
username = 'root'
password = '<PASSWORD>'
if(os.path.exists('config.txt')):
fr = open("config.txt")
list_of_all_the_lines = fr.readlines()
address = list_of_all_the_lines[0][0:-1]
sqlname = list_of_all_the_lines[1][0:-1]
username = list_of_all_the_lines[2][0:-1]
password = <PASSWORD>[3][0:-1]
fr.close()
if request.POST.has_key('hide'):
code = str(request.POST['hide'])
buttonvalue = str(request.POST['buttonvalue'])
if(os.path.exists('load.sql')):
fr = open('load.sql', 'r')
code = fr.read()
fr.close()
os.system("rm -f load.sql")
workvalue = 'workvalue'
if(code != ''):
fw = open('store.sql', 'w')
fw.write("use %s;\n" %(sqlname))
fw.write(timevar.timevar(code))
fw.close()
if(buttonvalue == "store"):
workvalue = 'yes'
result_store = ''
if(buttonvalue == "execute"):
#conn=MySQLdb.connect(host='127.0.0.1',user='root',passwd='<PASSWORD>',port=3306)
#cur=conn.cursor()
#cur.execute('create database if not exists python')
#conn.select_db('python')
#cur.execute('create table if not exists user(username varchar(20) primary key, password varchar(20))')
#cmd = 'mysql -h localhost -u root -pflanker < .\store.sql'
#cur.execute(cmd)
#conn.commit()
#cur.close()
#conn.close()
cmd = "mysql -h localhost -u %s -p%s < store.sql > result_store.txt" %(username, password)
temp = cmd.split()
child = subprocess.Popen(cmd, shell = True)
child.wait()
if(os.path.exists('result_store.txt')):
fr = open('result_store.txt','r')
result_store = fr.read()
fr.close()
return render_to_response('workpage.html', {'workvalue' : workvalue, 'sqlname' : sqlname, 'code' : code, 'cons' : result_store})
<file_sep>/a.sh
mysql -h localhost -u root -pflanker < a.sql
<file_sep>/result_store.sql
use python;
select * from edges;
<file_sep>/hw/timevar.py
import os
import sys
import re
import time
def timevar(code):
now = time.ctime()
now = now.replace(' ','_')
code = code.replace('${now}', now)
today = time.strftime('%Y-%m-%d',time.localtime(time.time()))
code = code.replace('${today}', today)
return code<file_sep>/c.sql
use python;
select * from takslist;<file_sep>/hw/load.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import loader,Context,RequestContext
from django.views.decorators.csrf import csrf_exempt
import MySQLdb
import sys
import glob
import os
import re
import init
@csrf_exempt
def load(request):
init.first()
codeList = []
#for filename in glob.glob(r'
path = os.path.dirname(os.path.abspath("store.sql"))
#codeList.append(path)
fileList = os.listdir(path)
for oneFile in fileList:
m = re.match("^\w+.sql$", oneFile)
if(m != None):
codeList.append(oneFile)
strs = 'r\'' + path + '\\*.sql'
for fileName in glob.glob(strs):
codeList.append(filename)
loadvalue = 'no'
if request.POST.has_key('codelist'):
sqlName = ''
sqlName = str(request.POST['codelist'])
fr = open(sqlName, 'r')
code = fr.read()
fr.close()
fw = open("load.sql", 'w')
fw.write(code)
fw.close()
loadvalue = 'yes'
return render_to_response('loadpage.html', {'codelist':codeList, 'loadvalue':loadvalue})
<file_sep>/hw/addpage.py
#coding=utf-8
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render_to_response
import MySQLdb
import re
import subprocess
import database
import init
@csrf_exempt
def index(request):
init.first()
if request.POST.has_key('taskname'):
taskname = str(request.POST['taskname'])
description = str(request.POST['taskdescription'])
content = str(request.POST['taskcode'])
fw = open("%s.sql" % taskname,"w")
fw.write(content)
fw.close()
#fw.write("mysql -h localhost -u root -pflanker < %s.sql\n" %(taskname))
#subprocess.Popen("chmod +x %s.sh" %(taskname), shell = True)
else:
taskname = ''
description = ''
content = ''
if taskname == '':
return render_to_response('addpage.html', {'taskname': taskname, 'taskdescription': description, 'sqlcode': content,'addstatus':'no'})
try:
database.execute('insert tasklist (name,file,status,description) values(\'%s\',\'%s.sql\',\'did not start\',\'%s\')' % (taskname, taskname, description))
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
taskkind = str(request.POST['taskkind'])
if taskkind == 'timed':
hour = str(request.POST['hour'])
minute = str(request.POST['minute'])
database.execute('update tasklist set type = \'%s-%s\' where name = \'%s\'' %(hour, minute, taskname))
else:
database.execute('update tasklist set type = NULL where name = \'%s\'' %taskname )
return render_to_response('addpage.html', {'taskname': taskname, 'taskdescription': description, 'sqlcode': content,'addstatus':'yes'})
<file_sep>/hw/dag.py
#coding=utf-8
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render_to_response
import MySQLdb
import re
import os
import database
import init
class Edge:
def __init__(self, u, v):
self.u = u
self.v = v
@csrf_exempt
def index(request):
init.first();
tasklist = database.getlist('select name from tasklist')
u = database.getlist('select u from edges')
v = database.getlist('select v from edges')
edges = []
for i in range(0,len(u)):
edges.append(Edge(u[i], v[i]))
fw = open('debug_dag', 'w')
for j in edges:
fw.write(j.u)
fw.close()
return render_to_response('chart2.html', {'tasklist': tasklist,'edgelist': edges})
<file_sep>/b.sql
use python;
select * from tasklist;<file_sep>/hw/newtask.py
import subprocess
import MySQLdb
import sys
import os
import database
import thread
def runsql(taskname,sqlfile):
username = 'root'
password = '<PASSWORD>'
if(os.path.exists('config.txt')):
fr = open("config.txt","r")
list_of_all_the_lines = fr.readlines()
username = list_of_all_the_lines[2][0:-1]
password = list_of_all_the_lines[3][0:-1]
fr.close()
cmd = "mysql -h localhost -u %s -p%s < %s" %(username, password, sqlfile)
ferr = open('test.txt','w')
ferr.write('update tasklist set status = \'running\' where name = \'%s\'' %taskname)
ferr.close()
database.execute('update tasklist set status = \'running\' where name = \'%s\'' %taskname)
child = subprocess.Popen(cmd, shell = True)
child.wait()
database.execute('update tasklist set status = \'finished\' where name = \'%s\'' %taskname)
nexttask = database.getlist("select name from tasklist where status = \'started\'")
for task in nexttask:
#parent = database.getlist("select u from edges where v = \'%s\'" %task)
#if taskname not in parent:
#continue
if judge(task):
thread.start_new_thread(runsql, (task, '%s.sql' %task))
def judge(task):
parent = database.getlist("select u from edges where v = \'%s\'" %task)
for i in parent:
result = database.getlist("select name from tasklist where name = \'%s\' and status = 'finished'" %i)
if len(result) == 0:
return False
return True<file_sep>/hw/urls.py
from django.conf.urls import patterns, include, url
from django.conf import settings
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'hw.views.home', name='home'),
# url(r'^hw/', include('hw.foo.urls')),
url(r'^$', 'hw.hw.index'),
url(r'^hw/$', 'hw.hw.indexhw'),
url(r'^taskpage/$','hw.list.index'),
url(r'^taskpage/addpage$','hw.addpage.index'),
url(r'^taskpage/modifypage/[\w]+$','hw.modifypage.index'),
url(r'^taskpage/infopage/[\w]+$','hw.infopage.index'),
url(r'^prepage/$','hw.addedge.index'),
url(r'^loginpage/$', 'hw.check.check'),
url(r'^storepage/$', 'hw.store.store'),
url(r'^workpage/$', 'hw.work.work'),
url(r'^configpage/$', 'hw.config.config'),
url(r'^loadpage/$', 'hw.load.load'),
url(r'^showpage/$', 'hw.show.show'),
url(r'^registerpage/$', 'hw.register.register'),
url(r'^dag/$', 'hw.dag.index')
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
)
<file_sep>/hw/init.py
import sys
import os
import database
import time
import newtask
import subprocess
import string
from apscheduler.schedulers.blocking import BlockingScheduler
def first():
today = time.strftime('%Y-%m-%d',time.localtime(time.time()))
if(os.path.exists('date.log')):
fr = open('date.log', 'r')
s = fr.read()
fr.close()
if(s != today):
init()
return True
else:
init()
return True
return False
def checktask(task):
res = str(database.getlist('select type from tasklist where name = \'%s\'' %task)[0])
if(newtask.judge(task)):
if(res == 'None'):
subprocess.Popen('python hw/scheduler.py %s %s.sql' %(task,task), shell = True)
else:
timelist = res.split('-')
hour = timelist[0]
minute = timelist[1]
subprocess.Popen('python hw/timetask.py %s %s %s' %(task,hour,minute), shell = True)
def init():
today = time.strftime('%Y-%m-%d',time.localtime(time.time()))
database.init()
database.execute('update tasklist set status = \'started\'')
fw = open('date.log', 'w')
fw.write(today)
fw.close()
tasklist = database.getlist('select name from tasklist')
statuslist = database.getlist('select status from tasklist')
for i in range(0,len(tasklist)):
if(statuslist[i] == 'started'):
checktask(tasklist[i])<file_sep>/hw/store.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import loader,Context,RequestContext
from django.views.decorators.csrf import csrf_exempt
import MySQLdb
import sys
import init
@csrf_exempt
def store(request):
init.first()
ans = "storevalue"
codename = str(request.POST.get('codename', ""))
if(codename != ""):
fr = open('store.sql', 'r')
texts = fr.read()
fw = open(codename, 'w')
fw.write(texts)
ans = "yes"
fr.close()
fw.close()
return render_to_response('storepage.html', {'storevalue': ans})
<file_sep>/hw/addedge.py
#coding=utf-8
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render_to_response
import MySQLdb
import re
import os
import sys, urllib
import database
import init
@csrf_exempt
def index(request):
init.first()
u = ''
v = ''
if request.POST.has_key('pretask'):
u = str(request.POST['pretask'])
v = str(request.POST['subtask'])
else:
return render_to_response('prepage.html')
try:
database.execute('insert edges (u,v) values(\'%s\',\'%s\')' % (u,v))
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
fw = open('error.txt','w')
fw.write("Mysql Error %d: %s" % (e.args[0], e.args[1]))
fw.close()
return render_to_response('prepage.html', {'loadvalue': 'yes'})
<file_sep>/wym510.sql
asf<file_sep>/hw/database.py
#coding=utf-8
import MySQLdb
import re
import os
import sys, urllib
def init():
try:
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='<PASSWORD>',port=3306)
cur = conn.cursor()
cur.execute('create database if not exists python')
conn.select_db('python')
cur.execute('create table if not exists tasklist(name varchar(125) primary key,type varchar(100),file varchar(100),status varchar(25),description varchar(2550))')
cur.execute('create table if not exists edges (u varchar(125),v varchar(125))')
cur.execute('create table if not exists user(username varchar(20) primary key, password varchar(20))')
conn.commit()
cur.close()
conn.close()
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
def execute(command):
try:
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='<PASSWORD>',port=3306)
cur = conn.cursor()
conn.select_db('python')
cur.execute(command)
conn.commit()
cur.close()
conn.close()
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
def getlist(command):
try:
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='<PASSWORD>',port=3306)
cur = conn.cursor()
conn.select_db('python')
cur.execute(command)
res = cur.fetchall()
result = []
for i in res:
for j in i:
result.append(j)
conn.commit()
cur.close()
conn.close()
return result
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
return []
def delete(taskName):
try:
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='<PASSWORD>',port=3306)
cur = conn.cursor()
conn.select_db('python')
cur.execute('delete from tasklist where name = \'%s\'' % (taskName))
cur.execute('delete from edges where u = \'%s\' or v = \'%s\'' % (taskName,taskName))
conn.commit()
cur.close()
conn.close()
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
def modify(oldName, newName, description):
try:
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='<PASSWORD>',port=3306)
cur = conn.cursor()
conn.select_db('python')
cur.execute(command)
cur.execute('update tasklist set name = \'%s\', file = \'%s.sql\', description = \'%s\' where name = \'%s\'' %(newName, newName, description, oldName))
cur.execute('update edges set u = \'%s\' where u = \'%s\'' %(newName, oldName))
cur.execute('update edges set v = \'%s\' where v = \'%s\'' %(newName, oldName))
conn.commit()
cur.close()
conn.close()
return result
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
return []<file_sep>/b.sh
mysql -h localhost -u root -pflanker < b.sql
<file_sep>/www.sh
mysql -h localhost -u root -pflanker < www.sql
<file_sep>/hw/config.py
#coding=utf-8
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import loader,Context,RequestContext
from django.views.decorators.csrf import csrf_exempt
import MySQLdb
import sys
import glob
import os
import re
import init
@csrf_exempt
def config(request):
init.first()
status = 'no'
if request.POST.has_key('sqladdress'):
address = str(request.POST['sqladdress'])
sql = str(request.POST['sqlsql'])
name = str(request.POST['sqlname'])
password = str(request.POST['sqlpassword'])
if address != '' and sql != '' and name != '' and password != '':
status = 'yes'
fw = open("config.txt", "w")
fw.write(address+'\n')
fw.write(sql+'\n')
fw.write(name+'\n')
fw.write(password+'\n')
fw.close()
return render_to_response('configpage.html',{'configvalue':status})
<file_sep>/hw/hw.py
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render_to_response
import sys
@csrf_exempt
def index(request):
return HttpResponse("Hello Django!")
def indexhw(request):
return HttpResponse("Hello World Demo!")
<file_sep>/hw/modifypage.py
#coding=utf-8
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render_to_response
import MySQLdb
import database
import init
@csrf_exempt
def index(request):
init.first()
try:
name = ''
ss = request.path
if name == '':
name = ss[21:]
res = database.getlist('select description from tasklist where name = \'%s\'' % (name))
description = res[0]
ferr = open("error_modify.log","w")
task = ''
if request.POST.has_key('taskname'):
task = str(request.POST['taskname'])
ferr.write(r'-----%s' %(task))
if task == name:
code = str(request.POST['taskcode'])
description = str(request.POST['taskdescription'])
isModify = 'yes'
fw = open("%s.sql" %(task),"w")
fw.write(code)
fw.close()
database.execute('update tasklist set name = \'%s\', file = \'%s.sql\', description = \'%s\' where name = \'%s\'' %(task, task, description, name))
database.execute('update edges set u = \'%s\' where u = \'%s\'' %(task, name))
database.execute('update edges set v = \'%s\' where v = \'%s\'' %(task, name))
else:
task = name
isModify = 'no'
fr = open("%s.sql" %(name),"r")
code = fr.read()
fr.close()
ferr.write(code)
ferr.close()
if request.POST.has_key('taskkind'):
taskkind = str(request.POST['taskkind'])
if taskkind == 'timed':
hour = str(request.POST['hour'])
minute = str(request.POST['minute'])
database.execute('update tasklist set type = \'%s-%s\' where name = \'%s\'' %(hour, minute, task))
else:
database.execute('update tasklist set type = NULL where name = \'%s\'' %task )
return render_to_response('modifypage.html', {'taskname': task,'modifystatus': isModify, 'taskdescription': description,'taskcode': code})
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
return render_to_response('modifypage.html')
<file_sep>/hw/register.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import loader,Context,RequestContext
from django.views.decorators.csrf import csrf_exempt
import MySQLdb
import sys
import init
@csrf_exempt
def register(request):
init.first()
username = ''
password = ''
ans = 'checkvalue'
if request.POST.has_key('username'):
username = str(request.POST['username'])
password = str(request.POST['password'])
fw = open('re.txt', 'a')
fw.write("lol")
fw.write(username)
fw.write(password)
fw.close()
if(username != ''):
try:
conn=MySQLdb.connect(host='127.0.0.1',user='root',passwd='<PASSWORD>',port=3306)
cur=conn.cursor()
cur.execute('create database if not exists python')
conn.select_db('python')
cur.execute('create table if not exists user(username varchar(20) primary key, password varchar(20))')
cur.execute('select username from user')
res = cur.fetchall()
fw = open('re.txt', 'w')
fw.write(username)
fw.write(password)
fw.write("lala")
ans = "yes"
for row in res:
fw.write(row[0])
fw.write(" ")
fw.write(ans)
if(row[0] == username):
ans = "no"
break
cmd = "INSERT INTO user(username, password) VALUES(\'" + username + "\', \'" + password + "\')"
if(ans == "yes"):
fw.write("execute")
cur.execute(cmd)
fw.write(ans)
fw.close()
conn.commit()
cur.close()
conn.close()
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
return render_to_response('registerpage.html', {'checkvalue': ans})
<file_sep>/wym510.sh
mysql -h localhost -u root -pflanker < wym510.sql
<file_sep>/hw/show.py
#coding=utf-8
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render_to_response
import MySQLdb
import re
import os
import database
import init
import newtask
import thread
import subprocess
from apscheduler.schedulers.blocking import BlockingScheduler
@csrf_exempt
def show(request):
init.first()
try:
task = ''
res = ''
if request.POST.has_key('tasklist'):
task = str(request.POST['tasklist'])
fw = open('result_store.sql','w')
fw.write('use python;\n')
fw.write('select * from %s;\n' % task)
fw.close()
cmd = "mysql -h localhost -u root -pflanker < result_store.sql > result_store.res"
child = subprocess.Popen(cmd, shell = True)
child.wait()
fr = open('result_store.res','r')
res = fr.read()
fr.close()
ll = database.getlist('show tables')
return render_to_response('showpage.html', {'tasklist': ll,'cons': res})
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
ferr = open("error.txt","w")
ferr.write("Mysql Error %d: %s" % (e.args[0], e.args[1]))
ferr.close()
<file_sep>/hw/scheduler.py
#!/usr/bin/env python
import sys
import newtask
#print sys.argv
#print sys.argv[1]
#print sys.argv[2]
newtask.runsql(str(sys.argv[1]),str(sys.argv[2]))
#fw = open('testsch.txt','w')
#fw.write(str(sys.argv[1]))
#fw.close()
<file_sep>/hw/infopage.py
#coding=utf-8
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render_to_response
import MySQLdb
import init
@csrf_exempt
def index(request):
init.first()
try:
conn=MySQLdb.connect(host='127.0.0.1',user='root',passwd='<PASSWORD>',port=3306)
cur=conn.cursor()
cur.execute('create database if not exists python')
conn.select_db('python')
cur.execute('create table if not exists tasklist(name varchar(125) primary key,type int,file varchar(100),status varchar(25),description varchar(2550))')
name = ''
if request.POST.has_key('taskname'):
name = str(request.POST['taskname'])
ss = request.path
if name == '':
name = ss[19:]
cur.execute('select status from tasklist where name = \'%s\'' % (name))
res = cur.fetchall()
for i in res:
for j in i:
status = str(j)
cur.execute('select description from tasklist where name = \'%s\'' % (name))
res = cur.fetchall()
for i in res:
for j in i:
description = str(j)
fr = open("%s.sql" %(name),"r")
code = fr.read()
fr.close()
conn.commit()
cur.close()
conn.close()
return render_to_response('infopage.html', {'taskname': name,'taskstatus': status,'taskdescription': description,'taskcode': code})
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
<file_sep>/hw/timetask.py
from apscheduler.schedulers.blocking import BlockingScheduler
import sys
import newtask
import string
task = str(sys.argv[1])
hour = str(sys.argv[2])
minute = str(sys.argv[3])
print task
print hour
print minute
scheduler = BlockingScheduler()
tmp = {'taskname':task,'sqlfile':'%s.sql' %task}
scheduler.add_job(newtask.runsql(**tmp), 'cron', hour = string.atoi(hour), minute = string.atoi(minute))
scheduler.start() | fbf9d596f55099ad2e4d319df1ae634f085f39c5 | [
"SQL",
"Python",
"Shell"
] | 28 | Python | wym037935/flanker | c8ca436960481d47fe5b3c631dfe4fbed591d45c | d29150d7313b132b2ba071197f6e59f61bf3ca1e |
refs/heads/master | <file_sep>package com.example.guest.socialnetworking.ui;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.example.guest.socialnetworking.R;
import com.google.firebase.auth.FirebaseAuth;
public class About extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_logout) {
logout();
return true;
}
if(id == R.id.action_about) {
Intent intent = new Intent(About.this, About.class);
startActivity(intent);
}
if(id == R.id.action_contact){
Intent intent = new Intent(About.this, Contact.class);
startActivity(intent);
}
if(id == R.id.action_home){
Intent intent = new Intent(About.this, Landing.class);
startActivity(intent);
}
if(id == R.id.action_explore){
Intent intent = new Intent(About.this, ExploreActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
private void logout() {
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(About.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}
<file_sep># VR Hub
VR Hub is a social media platform for Virtual Reality/Augmented Reality/Mixed Reality enthusiasts, developers, and designers.
## Details
This application is under active development and current features are changing daily. This app allows users to sign up
for access to the app using an email address and password. The App allows users to post messages on a community message board
that utilizes a firebase database. The App also uses the Twitter API to display tweets with #VirtualReality and users have the
ability to search for other keywords under #VirtualReality.
## Installation
* `git clone <https://github.com/stormihoebe/VR-Hub.git>`
* Open VR-Hub directory in Android Studio
* Follow any prompts to clean project of unfound files.
## API Credentials
* Navigate to <https://apps.twitter.com/app/new> in browser
* Log in to Twitter (if necessary)
* Fill out Application Details form (dummy text is acceptable, name must be unique)
* Select `Create your Twitter application` button to submit form
* Navigate to `Keys and Access Tokens`
* Select `Create my access token` button to generate access token.
* You will see your Consumer Key (API Key), Consumer Secret (API Secret) at the top of the page, and your Access Token and Access Token Secret at the bottom of the page. You will need all of these values to make a proper API call.
## Adding API Credentials to App
* Open VR-Hub in Android Studio, navigate to root directory.
* Create file in root directory named gradle.properties (this file is included in the .ignore file)
* Add API Credentials to gradle.properties
* Your gradle.properties should look like this (replacing the X with your credentials, of course):
```
TwitterConsumerKey = "<KEY>"
TwitterConsumerSecret = "<KEY>"
TwitterToken = "<KEY>"
TwitterTokenSecret = "<KEY>"
```
* Sync gradle to prepare to run
## Running
* Follow the APU Credentials steps above.
* Run 'app' on Android Emulator
* Sign up for an account with a valid email address and 6+ digit password.
## Current Bugs
* Login/Join: User is currently prompted to sign in/ join regardless if the device is already signed into the account. Clicking
either login or join will lead the user to the landing page if they are already signed on.
* App does not record author to messages when they are posted at this time.
### Useful Links
### Support and contact details
Contact Stormi at Epicodus
<EMAIL>
### License
Copyright (c) 2017 **_MIT License_**
<file_sep>package com.example.guest.socialnetworking.models;
/**
* Created by Guest on 6/1/17.
*/
public class Tweet {
private String mTime;
private String mText;
private String mUrl;
public Tweet(String text, String time, String url) {
this.mTime = time;
this.mText = text;
this.mUrl = url;
}
public String getText(){
return mText;
}
public String getTime() {
return mTime;
}
public String getUrl() { return mUrl; }
}
<file_sep>package com.example.guest.socialnetworking.services;
import com.example.guest.socialnetworking.Constants;
import com.example.guest.socialnetworking.models.Tweet;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import se.akerfeldt.okhttp.signpost.OkHttpOAuthConsumer;
import se.akerfeldt.okhttp.signpost.SigningInterceptor;
public class TwitterService {
public static void findTweets(String search, Callback callback){
OkHttpOAuthConsumer consumer = new OkHttpOAuthConsumer(Constants.TWITTER_CONSUMER_KEY, Constants.TWITTER_CONSUMER_SECRET);
consumer.setTokenWithSecret(Constants.TWITTER_TOKEN, Constants.TWITTER_TOKEN_SECRET);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new SigningInterceptor(consumer))
.build();
HttpUrl.Builder urlBuilder = HttpUrl.parse(Constants.TWITTER_BASE_URL).newBuilder();
String url = urlBuilder.build().toString() + "%20" + search;
Request request= new Request.Builder()
.url(url)
.build();
Call call = client.newCall(request);
call.enqueue(callback);
}
public ArrayList<Tweet> processResults(Response response){
ArrayList<Tweet> tweets = new ArrayList<>();
try {
String jsonData = response.body().string();
if (response.isSuccessful()) {
JSONObject twitterJSON = new JSONObject(jsonData);
JSONArray tweetJSON = twitterJSON.getJSONArray("statuses");
for (int i = 0; i < tweetJSON.length(); i++){
JSONObject statusJSON = tweetJSON.getJSONObject(i);
String time = statusJSON.getString("created_at");
String text = statusJSON.getString("text");
String url = "";
if (statusJSON.getJSONObject("entities").getJSONArray("urls").length() == 0){
url = "";
} else {
url = statusJSON.getJSONObject("entities").getJSONArray("urls").getJSONObject(0).getString("url");
}
Tweet newTweet = new Tweet(text, time, url);
tweets.add(newTweet);
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return tweets;
}
}
<file_sep>package com.example.guest.socialnetworking.ui;
import android.content.Intent;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.guest.socialnetworking.R;
import butterknife.Bind;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
@Bind(R.id.bannerText) TextView mBannerText;
@Bind(R.id.bannerText2) TextView mBannerText2;
@Bind(R.id.joinButton) Button mjoinButton;
@Bind(R.id.signInButton) Button msigntInButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
Typeface crash = Typeface.createFromAsset(getAssets(), "fonts/crash.ttf");
mBannerText.setTypeface(crash);
mBannerText2.setTypeface(crash);
mjoinButton.setOnClickListener(this);
msigntInButton.setOnClickListener(this);
}
public void onClick(View v) {
if(v == mjoinButton) {
Intent intent = new Intent(MainActivity.this, JoinActivity.class);
startActivity(intent);
}
if(v == msigntInButton) {
Intent intent = new Intent(MainActivity.this, Login.class);
startActivity(intent);
}
}
}
<file_sep>package com.example.guest.socialnetworking.ui;
import android.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import com.example.guest.socialnetworking.BounceInterpolator;
import com.example.guest.socialnetworking.R;
import com.example.guest.socialnetworking.adapters.FirebaseMessageViewHolder;
import com.example.guest.socialnetworking.models.Message;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import butterknife.Bind;
import butterknife.ButterKnife;
public class MessagesActivity extends AppCompatActivity implements View.OnClickListener{
@Bind(R.id.addMessaButton)Button mAddMessageButton;
@Bind(R.id.messagessRecyclerView)RecyclerView mRecyclerView;
private DatabaseReference mMessageReference;
private FirebaseRecyclerAdapter mFirebaseAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messages);
ButterKnife.bind(this);
BounceInterpolator interpolator = new BounceInterpolator(0.2, 20);
final Animation bounceAnim = AnimationUtils.loadAnimation(this,R.anim.bounce);
mAddMessageButton.startAnimation(bounceAnim);
bounceAnim.setInterpolator(interpolator);
mAddMessageButton.setOnClickListener(this);
mMessageReference = FirebaseDatabase.getInstance().getReference().child("messages");
setUpFirebaseAdapter();
}
@Override
public void onClick(View v) {
if(v == mAddMessageButton) {
FragmentManager fm = getFragmentManager();
NewMessageFragment newMessageFragment = new NewMessageFragment();
newMessageFragment.show(fm, "Message Fragment");
BounceInterpolator interpolator = new BounceInterpolator(0.2, 20);
final Animation bounceAnim = AnimationUtils.loadAnimation(this,R.anim.bounce);
mAddMessageButton.startAnimation(bounceAnim);
bounceAnim.setInterpolator(interpolator);
mAddMessageButton.setOnClickListener(this);
mMessageReference = FirebaseDatabase.getInstance().getReference().child("messages");
setUpFirebaseAdapter();
}
}
private void setUpFirebaseAdapter() {
mFirebaseAdapter = new FirebaseRecyclerAdapter<Message, FirebaseMessageViewHolder>
(Message.class, R.layout.message_list_item, FirebaseMessageViewHolder.class, mMessageReference) {
@Override
public void populateViewHolder(FirebaseMessageViewHolder viewHolder, Message model, int position) {
viewHolder.bindTopic(model);
}
};
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mFirebaseAdapter);
Log.d("reference", mMessageReference.getKey());
}
}
| c6d04b5a86df98d9c212d5c05fe500a8c139f053 | [
"Markdown",
"Java"
] | 6 | Java | stormihoebe/VR-Hub | 66ec31739c00fc641b27cd57355adc3ef28c55b9 | 8e5658632d64e2c196bf137869f317f4d55e340f |
refs/heads/main | <file_sep>import React from "react";
const DummyText = () => {
return (
<section>
<article>
<h2 id="paragraph1">Paragraph 1</h2>
<p>
Annoy the old grumpy cat, start a fight and then retreat to wash when
i lose make meme, make cute face, and if human is on laptop sit on the
keyboard for asdflkjaertvlkjasntvkjn (sits on keyboard). Plan your
travel kitty scratches couch bad kitty i will ruin the couch with my
claws. Nyan nyan goes the cat, scraaaaape scraaaape goes the walls
when the cat murders them with its claws love you, then bite you push
your water glass on the floor poop on grasses poop in the plant pot
lay on arms while you're using the keyboard yet allways wanting food.
Destroy house in 5 seconds damn that dog , for lick butt and make a
weird face poop in the plant pot for poop on the floor, break a
planter, sprint, eat own hair, vomit hair, hiss, chirp at birds, eat a
squirrel, hide from fireworks, lick toe beans, attack christmas tree
for play time, but chew on cable. Meow in empty rooms love pee in the
shoe cry louder at reflection yet russian blue. Cats are cute missing
until dinner time, or bathe private parts with tongue then lick
owner's face so under the bed, bird bird bird bird bird bird human why
take bird out i could have eaten that and pet me pet me pet me pet me,
bite, scratch, why are you petting me so eat and than sleep on your
face.
</p>
</article>
<article>
<h2 id="paragraph2">Paragraph 2</h2>
<p>
Annoy the old grumpy cat, start a fight and then retreat to wash when
i lose make meme, make cute face, and if human is on laptop sit on the
keyboard for asdflkjaertvlkjasntvkjn (sits on keyboard). Plan your
travel kitty scratches couch bad kitty i will ruin the couch with my
claws. <NAME> goes the cat, scraaaaape scraaaape goes the walls
when the cat murders them with its claws love you, then bite you push
your water glass on the floor poop on grasses poop in the plant pot
lay on arms while you're using the keyboard yet allways wanting food.
Destroy house in 5 seconds damn that dog , for lick butt and make a
weird face poop in the plant pot for poop on the floor, break a
planter, sprint, eat own hair, vomit hair, hiss, chirp at birds, eat a
squirrel, hide from fireworks, lick toe beans, attack christmas tree
for play time, but chew on cable. Meow in empty rooms love pee in the
shoe cry louder at reflection yet russian blue. Cats are cute missing
until dinner time, or bathe private parts with tongue then lick
owner's face so under the bed, bird bird bird bird bird bird human why
take bird out i could have eaten that and pet me pet me pet me pet me,
bite, scratch, why are you petting me so eat and than sleep on your
face.
</p>
</article>
<article>
<h2 id="paragraph3">Paragraph 3</h2>
<p>
Annoy the old grumpy cat, start a fight and then retreat to wash when
i lose make meme, make cute face, and if human is on laptop sit on the
keyboard for asdflkjaertvlkjasntvkjn (sits on keyboard). Plan your
travel kitty scratches couch bad kitty i will ruin the couch with my
claws. <NAME> goes the cat, scraaaaape scraaaape goes the walls
when the cat murders them with its claws love you, then bite you push
your water glass on the floor poop on grasses poop in the plant pot
lay on arms while you're using the keyboard yet allways wanting food.
Destroy house in 5 seconds damn that dog , for lick butt and make a
weird face poop in the plant pot for poop on the floor, break a
planter, sprint, eat own hair, vomit hair, hiss, chirp at birds, eat a
squirrel, hide from fireworks, lick toe beans, attack christmas tree
for play time, but chew on cable. Meow in empty rooms love pee in the
shoe cry louder at reflection yet russian blue. Cats are cute missing
until dinner time, or bathe private parts with tongue then lick
owner's face so under the bed, bird bird bird bird bird bird human why
take bird out i could have eaten that and pet me pet me pet me pet me,
bite, scratch, why are you petting me so eat and than sleep on your
face.
</p>
</article>
</section>
);
};
export default DummyText;
<file_sep>import React from 'react';
import Kazakhstan from './src/Kazakhstan';
// import Live from './src/Live';
// import CV from './src/CV';
// import LinkedIn from './src/LinkedIn';
const Map = props => {
switch (props.name) {
case 'Kazakhstan':
return <Kazakhstan {...props} />;
// case 'Live':
// return <Live {...props} />;
// case 'CV':
// return <CV {...props} />;
// case 'LinkedIn':
// return <LinkedIn {...props} />;
default:
return;
}
};
export default Map;<file_sep>import React, { useRef, useEffect } from "react";
const TestInReact = () => {
const componentRef = useRef(null);
useEffect(() => {
const path = componentRef.current.querySelector("#star-path");
if (path) {
// Get length of path...
const pathLength = path.getTotalLength();
console.log("pathLength", pathLength);
// Make very long dashes (the length of the path itself)
path.style.strokeDasharray = pathLength + " " + pathLength;
// Offset the dashes so the it appears hidden entirely
path.style.strokeDashoffset = pathLength;
// Jake Archibald says so
// https://jakearchibald.com/2013/animated-line-drawing-svg/
path.getBoundingClientRect();
// When the page scrolls...
window.addEventListener("scroll", function (e) {
// What % down is it?
// https://stackoverflow.com/questions/2387136/cross-browser-method-to-determine-vertical-scroll-percentage-in-javascript/2387222#2387222
// Had to try three or four differnet methods here. Kind of a cross-browser nightmare.
const scrollPercentage =
(document.documentElement.scrollTop + document.body.scrollTop) /
(document.documentElement.scrollHeight -
document.documentElement.clientHeight);
// Length to offset the dashes
const drawLength = pathLength * scrollPercentage;
// Draw in reverse
path.style.strokeDashoffset = pathLength - drawLength;
// When complete, remove the dash array, otherwise shape isn't quite sharp
// Accounts for fuzzy math
if (scrollPercentage >= 0.99) {
path.style.strokeDasharray = "none";
} else {
path.style.strokeDasharray = pathLength + " " + pathLength;
}
});
}
}, []);
return (
<div>
TeST
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 100.6 107.6"
className="star-svg"
ref={componentRef}
>
<path
fill="none"
stroke="black"
stroke-width="2"
id="star-path"
d="M43.7,65.8L19.9,83.3c-2.9,1.9-5.1,3.2-7.9,3.2c-5.7,0-10.5-5.1-10.5-10.8
c0-4.8,3.8-8.2,7.3-9.8l27.9-12L8.8,41.4c-3.8-1.6-7.3-5.1-7.3-9.8c0-5.7,5.1-10.5,10.8-10.5c2.9,0,4.8,1,7.6,3.2l23.8,17.4
l-3.2-28.2c-1-6.7,3.5-12,9.8-12c6.3,0,10.8,5.1,9.8,11.7L57,41.8l23.8-17.4c2.9-2.2,5.1-3.2,7.9-3.2c5.7,0,10.5,4.8,10.5,10.5
c0,5.1-3.5,8.2-7.3,9.8L63.9,53.8l27.9,12c3.8,1.6,7.3,5.1,7.3,10.1c0,5.7-5.1,10.5-10.8,10.5c-2.5,0-4.8-1.3-7.6-3.2L57,65.8
l3.2,28.2c1,6.7-3.5,12-9.8,12c-6.3,0-10.8-5.1-9.8-11.7L43.7,65.8z"
/>
</svg>
</div>
);
};
export default TestInReact;
<file_sep>import './App.css';
// import Country from './components/Country';
import DummyCountry from './components/dummy-country/DummyCountry';
function App() {
return (
<>
<DummyCountry/>
</>
);
}
export default App;
| 5596eb2c0cddc9b42b0270ebaeba3df302355806 | [
"JavaScript"
] | 4 | JavaScript | w-gluza/svg-test | 23117cfd373f2e1a9bd340498ce7d960ac68b198 | f968e92d68d0e64a640cd5cebbae497463139f52 |
refs/heads/main | <repo_name>bkdevart/SwiftUIProject12Challenge<file_sep>/CoreDataProject2/Singer+CoreDataClass.swift
//
// Singer+CoreDataClass.swift
// CoreDataProject2
//
// Created by <NAME> on 4/26/21.
//
//
import Foundation
import CoreData
@objc(Singer)
public class Singer: NSManagedObject {
}
| 117387799dff68b25438a3cc9b113ecdb57c0864 | [
"Swift"
] | 1 | Swift | bkdevart/SwiftUIProject12Challenge | e42aff228890bcc528a6c9b367882f857e4788be | f3949d50068c0115a98f5b63dac9230651888cda |
refs/heads/master | <file_sep>const mongoose = require("mongoose")
const http = require("http")
const socketio = require("socket.io")
const server = http.createServer()
const io = socketio(server)
mongoose.connect("mongodb+srv://dan:<EMAIL>/test?retryWrites=true&w=majority", { useNewUrlParser: true, useUnifiedTopology: true })
const db = mongoose.connection
const userSchema = new mongoose.Schema({
username: {
type: String,
require: true,
trim: true,
validate: (input) => {
return (input.length > 0)
},
unique: true
},
first: {
type: String
},
last: {
type: String
}
})
io.on("connection", (socket) => {
console.log("Someone connected to me")
})
const User = mongoose.model("User", userSchema, "Users")
db.once("open", () => {
console.log("Connected to database")
// const dan = new User({
// username: "dan",
// first: "Dan",
// last: "Goodman"
// })
// dan.save()
const collection = db.collection("Users")
const stream = collection.watch()
stream.on("change", (event) => {
console.log(event)
switch (event.operationType) {
case "replace":
console.log(`Replaced: ${event.fullDocument}`)
break
case "insert":
// console.log(`Inserted: ${event.fullDocument}`)
io.emit("inserted", event.fullDocument)
break
case "delete":
// console.log(`Deleted: ${event.documentKey._id}`)
io.emit("deleted", event.documentKey._id)
break
default:
console.log("what")
break
}
})
})
server.listen(8080, () => {
console.log("listneing")
})
| 488afc69609cca6a9dfdb60992b3b58042d49d7d | [
"JavaScript"
] | 1 | JavaScript | danthegoodman1/mongoLecture | aa6cc12b190df8a87dcf19074318905603f691fe | 7a087a7bac82100ce596054e28ed33e89a0b2d5b |
refs/heads/master | <repo_name>PriyeshGangrade26/Multiple-Object-Detection<file_sep>/README.md
Multiple Object Detection:-
- OpenCV
OpenCV (Open Source Computer Vision Library) is an open source computer vision and machine learning software library.
OpenCV was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in the commercial products. Being a BSD-licensed product, OpenCV makes it easy for businesses to utilize and modify the code.
- Numpy
NumPy is the fundamental package for scientific computing with Python. It contains among other things:
- A powerful N-dimensional array object
- Sphisticated (broadcasting) functions
- Tools for integrating C/C++ and Fortran code
- Useful linear algebra, Fourier transform, and random number capabilities Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional
container of generic data.
- Arbitrary data-types can be defined. this allows NumPy to seamlessly and speedily integrate with a wide variety of databases.
Requirements:-
- OpenCV
- Numpy
- COCO Model
<file_sep>/main.py
import cv2
thres = 0.45 # Threshold to detect object
cap = cv2.VideoCapture(0)
cap.set(3, 1280)
cap.set(4, 720)
cap.set(10, 70)
classNames= []
classFile = 'coco.names'
with open(classFile, 'rt') as f:
classNames = f.read().rstrip('n').split('n')
configPath = 'ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt'
weightsPath = 'frozen_inference_graph.pb'
net = cv2.dnn_DetectionModel(weightsPath, configPath)
net.setInputSize(320, 320)
net.setInputScale(1.0/127.5)
net.setInputMean((127.5, 127.5, 127.5))
net.setInputSwapRB(True)
while True:
success, img = cap.read()
classIds, confs, bbox = net.detect(img, confThreshold=thres)
print(classIds, bbox)
if len(classIds) != 0:
for classId, confidence, box in zip(classIds.flatten(), confs.flatten(), bbox):
cv2.rectangle(img, box, color=(0, 255, 0), thickness=2)
# cv2.putText(img, classNames[classId-1].upper(), (box[0]+10, box[1]+30),
# cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 2)
# cv2.putText(img, str(round(confidence*100, 2)), (box[0]+200, box[1]+30),
# cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 2)
cv2.imshow("Output", img)
cv2.waitKey(1) | 782d68840c9e75a4ad957937c51c7533a1eaafc0 | [
"Markdown",
"Python"
] | 2 | Markdown | PriyeshGangrade26/Multiple-Object-Detection | 4827f2b5d781f7dc7a64616cea407b3c81ba67a3 | 428f28906e5db52b38ade3b7a6c48b77ed423755 |
refs/heads/master | <repo_name>djwong23/pa2<file_sep>/src/estimate.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define debug 0
double *transpose(double *x1, double *x1t, int numHouses, int numAtt) {
int i = 0;
int j = 0;
double num = 0;
for (i = 0; i < numAtt + 1; i++) {
for (j = 0; j < numHouses; j++) {
num = *(x1 + j * (numAtt + 1) + i);
*(x1t + i * (numHouses) + j) = num;
////printf("%f ", *(x1t + i * (numHouses) + j));
}
////printf("\n");
}
return x1t;
}
double *multiply(double *x1t, double *x1, double *product, int rows1, int cols1, int rows2, int cols2) {
int j = 0;
int k = 0;
for (j = 0; j < rows1; j++) {
for (k = 0; k < cols2; k++) {
int h = 0;
double sum = 0;
while (h < cols1) {
sum += (*(x1t + j * cols1 + h) * *(x1 + h * cols2 + k));
h++;
}
*(product + j * cols2 + k) = sum;
////printf("%f ", sum);
}
////printf("\n");
}
for (j = 0; j < rows1; j++) {
for (k = 0; k < cols2; k++) {
//printf("%f ", *(product + j * cols2 + k));
}
//printf("\n");
}
return product;
}
double *invert(double *M, double *N, int cols) {
int p = 0;
int i = 0;
double f = 0;
int j = 0;
for (p = 0; p < cols; p++) {
f = *(M + p * cols + p);
int j = 0;
for (j = 0; j < cols; j++) {
*(M + p * cols + j) /= f;
*(N + p * cols + j) /= f;
}
i = p + 1;
for (i = p + 1; i < cols; i++) {
f = *(M + i * cols + p);
j = 0;
for (j = 0; j < cols; j++) {
*(M + i * cols + j) -= (*(M + p * cols + j) * f);
*(N + i * cols + j) -= (*(N + p * cols + j) * f);
}
}
}
for (p = cols - 1; p >= 0; p--) {
for (i = p - 1; i >= 0; i--) {
f = *(M + i * cols + p);
int j = 0;
for (j = 0; j < cols; j++) {
*(M + i * cols + j) -= (*(M + p * cols + j) * f);
*(N + i * cols + j) -= (*(N + p * cols + j) * f);
}
}
}
i = 0;
j = 0;
for (j = 0; j < cols; j++) {
for (i = 0; i < cols; i++) {
//printf("%f ", *(M + j * cols + i));
}
//printf("\n");
}
for (j = 0; j < cols; j++) {
for (i = 0; i < cols; i++) {
//printf("%f ", *(N + j * cols + i));
}
//printf("\n");
}
return N;
}
int main(int argc, char *argv[]) {
FILE *f1 = NULL;
FILE *f2 = NULL;
if (!debug) {
f1 = fopen(argv[1], "r");
f2 = fopen(argv[2], "r");
} else {
f1 = fopen("C:\\Users\\djwon\\CLionProjects\\pa2\\train.00.txt", "r");
f2 = fopen("C:\\Users\\djwon\\CLionProjects\\pa2\\data.00.txt", "r");
}
//printf("File loaded \n");
char word1[20];
char word2[20];
fscanf(f1, "%s", word1);
fscanf(f2, "%s", word2);
FILE *train = NULL;
FILE *data = NULL;
if (!strcmp(word1, "train")) {
train = f1;
data = f2;
} else {
train = f2;
data = f1;
}
//printf("Words scanned\n");
int numAtt = 0;
fscanf(train, "%d", &numAtt);
int numHouses = 0;
fscanf(train, "%d", &numHouses);
int cols = numAtt + 1;
double *x1 = (double *) (malloc(sizeof(double) * (cols) * numHouses));
double *y1 = (double *) (malloc(sizeof(double) * numHouses));
double *x1t = (double *) (malloc(sizeof(double) * (cols) * numHouses));
int i = 0;
int j = 0;
double number = 0;
//making X matrix
for (i = 0; i < numHouses; i++) {
for (j = 0; j < (cols); j++) {
if (j == 0) {
*(x1 + i * (cols) + j) = 1;
} else {
fscanf(train, "%lf", &number);
*(x1 + i * (cols) + j) = number;
}
//printf("%f ", *(x1 + i * (cols) + j));
}
//printf("\n");
fscanf(train, "%lf", &number);
*(y1 + i) = number;
}
//printf("Matrix made\n");
x1t = transpose(x1, x1t, numHouses, numAtt);
double *product = (double *) (malloc(sizeof(double) * (cols) * (cols)));
product = multiply(x1t, x1, product, cols, numHouses, numHouses, cols);
//printf("Multiplied\n");
free(x1);
x1 = NULL;
double *identity = (double *) (malloc(sizeof(double) * cols * cols));
for (i = 0; i < cols; i++) {
for (j = 0; j < cols; j++) {
if (i == j)
*(identity + i * cols + j) = 1;
else
*(identity + i * cols + j) = 0;
}
}
identity = invert(product, identity, cols);
//printf("Inverted\n");
free(product);
product = (double *) (malloc(sizeof(double) * cols * numHouses));
//printf("Malloced product\n");
product = multiply(identity, x1t, product, cols, cols, cols, numHouses);
//printf("Producted\n");
free(x1t);
x1t = NULL;
double *W = (double *) (malloc(sizeof(double) * cols));
W = multiply(product, y1, W, cols, numHouses, numHouses, 1);
//printf("Found W\n");
free(x1);
free(y1);
free(x1t);
free(product);
free(identity);
fscanf(data, "%d", &numAtt);
fscanf(data, "%d", &numHouses);
double *x2 = (double *) (malloc(sizeof(double) * (numAtt+1) * numHouses));
for (i = 0; i < numHouses; i++) {
for (j = 0; j < (numAtt + 1); j++) {
if (j == 0) {
*(x2 + i * (numAtt+1) + j) = 1;
} else {
fscanf(data, "%lf", &number);
*(x2 + i * (numAtt+1) + j) = number;
}
//printf("%f ", *(x2 + i * (numAtt+1) + j));
}
//printf("\n");
}
//printf("x prime made\n");
double *y2 = (double *) (malloc(sizeof(double) * numHouses));
y2 = multiply(x2, W, y2, numHouses, numAtt + 1, cols, 1);
for (j = 0; j < numHouses; j++) {
printf("%.0f\n", *(y2 + j));
}
free(x2);
free(W);
free(y2);
return 0;
}
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.10.2)
project(untitled C)
set(CMAKE_C_STANDARD 99)
add_executable(untitled src/estimate.c) | 82bfa889dbeb4b42b2eadf18fed1c9ded9da43f6 | [
"C",
"CMake"
] | 2 | C | djwong23/pa2 | 392abba31a7f01395735663cd182eb78bf0b4a6d | 7a2188af96f5c11d7beffabecbc9fa19e2408881 |
refs/heads/master | <repo_name>MasanoriIwakura/django-todo<file_sep>/todo/app/views.py
from django.http import HttpResponse
from django.template import loader
from django.shortcuts import get_object_or_404, render
from .models import Todo
def index(request):
todo_list = Todo.objects.order_by('-updated_at')[:5]
template = loader.get_template('todo/index.html')
context = {
'todo_list': todo_list,
}
return HttpResponse(template.render(context, request))
def detail(request, id):
try:
todo = Todo.objects.get(pk=id)
template = loader.get_template('todo/detail.html')
context = {
'todo': todo,
}
return HttpResponse(template.render(context, request))
except Exception as e:
context = {
'msg': 'Error.'
}
return HttpResponse(template.render(context, request))
<file_sep>/todo/app/models.py
from django.db import models
class Todo(models.Model):
body = models.CharField(max_length=100)
updated_at = models.DateTimeField(auto_now=True)
| 617579767868a4fa6a0ef566b41e8554033d4aca | [
"Python"
] | 2 | Python | MasanoriIwakura/django-todo | 5999fbe9837772af3b4b9d52b74a3a1e622b0c7c | f273e203abb9acdcaa4a1f276970fbe331f91d47 |
refs/heads/master | <repo_name>techunits/rate-exchange-chrome<file_sep>/README.md
rate-exchange-chrome
====================
Techunits Currency Exchange Service for Chome is a FREE chrome extension with which customers can do currency convertions from Chrome browsers itself. It's build using Techunits Rate Exchange API https://rate-exchange.herokuapp.com/ which provides extremely accurate & real-time exchange rates.
The source code can help developers to build there on Currency Convertion Widgets based on javascript as well. We will be waiting for any suggestions and improvements and requirements.
Website:
* http://www.techunits.com
* http://www.euphern.com
<file_sep>/js/init.js
function fetchExchangeRate(src, target, sourceAmount) {
$.ajax({
url: 'http://rate-exchange.herokuapp.com/fetchRate',
cache: true,
async: true,
data: {
from: src,
to: target
},
beforeSend: function() {
$('#final_amount').text('Loading...');
},
success: function(responseObj) {
if(undefined != responseObj.Rate) {
var targetAmount = parseFloat(sourceAmount) * parseFloat(responseObj.Rate);
$('#final_amount').text(targetAmount + ' ' + target);
}
else {
$('#final_amount').text('Try again...');
}
},
error: function() {
alert('Sorry! Server Busy...');
}
});
}
$(document).ready(function() {
fetchExchangeRate('USD', 'EUR', 1.00);
$('form[name="currency_convert"]').submit(function() {
var src = $(this).find('select[name="source_currency"]').val();
var target = $(this).find('select[name="target_currency"]').val();
if(src != target) {
var sourceAmount = $(this).find('input[name="source_amount"]').val();
fetchExchangeRate(src, target, sourceAmount);
}
else {
alert('Source & Target Currency can\'t be same.');
}
return false;
});
});
| da788173e610b3b9114ac9187a3717d69cb673c1 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | techunits/rate-exchange-chrome | 4cfebbdb47ef137cb7891339c6616c7d348e06dd | 3a8cdffc5083ae872f5a4d4361da22cddf30a9da |
refs/heads/master | <file_sep>import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import AppNavigator from './navigator';
export default class App extends Component {
render() {
return (
<AppNavigator
ref={(nav) => {
this.navigator = nav;
global.NAVIGATOR = nav;
}}
onNavigationStateChange={(prevState, currentState) => {
console.log('-------------Navigation Params----------');
console.log(`routeName: ${currentState.routes[currentState.index].routeName}`);
console.log(currentState.routes[currentState.index].params);
console.log('----------------------------------------');
global.CURRENT_ROUTE_NAME = currentState.routes[currentState.index].routeName;
}}
/>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
<file_sep># chatapp
A chat app demo
<file_sep>module.exports = {
"extends": "airbnb",
"parser": "babel-eslint",
"globals": {
"__DEV__": true,
"alert": true,
},
"env": {
"jest": true,
},
"rules": {
"no-case-declarations": 1,
"no-await-in-loop": 1,
"no-console": 0,
"quotes": 0,
"quote-props": 0,
"no-alert": 0,
"class-methods-use-this": 0,
"prefer-destructuring": ["error", {"object": false, "array": false}],
"react/prop-types": [2, { ignore: ["navigation"], customValidators: [] }],
"react/forbid-prop-types": [2, { "forbid": ["any"] }],
"react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }],
"react/no-multi-comp":1,
"max-len": 1,
"arrow-body-style": 0,
"no-plusplus": 0,
"react/sort-comp": 0,
"no-lonely-if": 0,
"spaced-comment": 1,
"react/jsx-indent": 1,
"no-param-reassign": 1,
}
};
<file_sep>export default {
ic_menu_back: require('./ic_menu_back.png'),
}
| d07f077f3607d668bd61c75e002031e9fbe96f70 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | happy-daily/chat-app | 2ecab2c3d41a1ac045f77526dc6d75a96cce1a77 | 40c04d41a0983c1c1f38c0c4d8288eb8b7419815 |
refs/heads/master | <repo_name>cleitondias/projects_ui5<file_sep>/appdozero/webapp/controller/App.controller.js
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/m/MessageToast",
"sap/ui/model/json/JSONModel"
], function(
Controller,
MessageToast,
JSONModel
) {
"use strict";
return Controller.extend("cgutech.template.controller.App", {
//Begin - Implement Custom Methods
onInit: function(){
//define data object
var oMsg = {
MsgInicial : "Welcome!!!",
Msg2 : "Good Night!!"
};
//define json model
var oMsgModel = new JSONModel();
oMsgModel.setData(oMsg);
//data binding
//
this.getView().setModel(oMsgModel,"messages");
//New model 2
var oPessoaModel = new JSONModel({
nome: "Steven",
sobrenome: "Job",
habilitado: true,
endereco: {
rua: "Av. Antero de Quental, 54",
cidade: "Lisbon",
cep: "2580-604",
pais: "Portugal"
}
});
//set model in the view
this.getView().setModel(oPessoaModel, "pessoa");
//Array
var oFuncionarios = {
Funcionarios: [
{
nome: "Steven",
sobrenome: "Job",
habilitado: true
},
{
nome: "Burt",
sobrenome: "Preynolds",
habilitado: false
},
{
nome: "Maiqe",
sobrenome: "Taison",
habilitado: true
},
{
nome: "Jubileu",
sobrenome: "Machado",
habilitado: true
}
]
};
var oFunModel = new JSONModel(oFuncionarios);
this.getView().setModel(oFunModel, "empregados");
},
//Similar - MODULE PBO - AT SELECTION SCREEN OUTPUT
onBeforeRendering: function(){
},
//Similar - MODULE PAI - AT SELECTION SCREEN
onAfterRendering: function(){
//alert("onAfterRendering");
//uso comum: validar dados e alterar UI de acordo com dados
},
//Similar - AT EXIT COMMAND
onExit: function(){
alert("on Exit");
//uso comum: limpar variaveis ao sair dessa view
},
onClick: function(){
// MessageToast.show("Test Clicked button");
//get model on view
var oModel = this.getView().getModel("messages");
//get model data
var oDados = oModel.getData();
//Display model data as message
MessageToast.show(oDados.MsgInicial);
},
onFuncionarioSelected: function(oEvent) {
var oSource = oEvent.getSource();
var oContext = oSource.getBindingContext("empregados");
var sPath = oContext.getPath();
var oPanel = this.byId("detalhePanel");
oPanel.bindElement({
path: sPath,
model: "empregados"
});
},
onClientSelected: function(oEvent){
var oSource = oEvent.getSource();
var oContext = oSource.getBindingContext();
var sPath = oContext.getPath();
var oPanel = this.byId("clientePanel");
oPanel.bindElement({
path: sPath
});
}
//End - Implement Custom Methods
});
});<file_sep>/customer/webapp/controller/Home.controller.js
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/ui/core/routing/History",
"sap/ui/core/UIComponent",
"sap/m/MessageToast",
"sap/m/MessageBox"
], function(Controller,
History,
UIComponent,
MessageToast,
MessageBox) {
"use strict";
return Controller.extend("customer.controller.Home", {
/**
* @override
*/
onInit: function() {
this.Initialize();
},
Initialize: function (){
this.byId("customer").setValue("");
this.byId("name").setValue("");
this.byId("address").setValue("");
this.byId("country").setValue("");
},
onClick: function(oEvent) {
var oEntry = {};
oEntry.CustomerId = this.byId("customer").getValue();
oEntry.Name = this.byId("name").getValue();
oEntry.Address = this.byId("address").getValue();
oEntry.Country = this.byId("country").getValue();
if (oEntry.CustomerId == null ){
MessageBox.alert("Cannot be save, data missing in the container!");
return;
}
var oModel = new sap.ui.model.odata.ODataModel("/sap/opu/odata/SAP/ZCUSTOMER_INFO_SRV/", true);
sap.ui.getCore().setModel(oModel);
oModel.setSizeLimit(150);
/* oModel.read("/ZCUST_DATASet", {
success: function(oData, oResponse){
MessageToast.show("Connected oData successfully");
}
}); */
//Disable Batch Request
oModel.setUseBatch(true);
oModel.create("/ZCUST_DATASet", oEntry, {
success: function (oData, oResponse){
var message = "Customer : " + oEntry.CustomerId + " created successfully on database";
jQuery.sap.require("sap.m.MessageBox");
sap.m.MessageBox.show(message, {
closeOnBrowserNavigation: false,
duration: 2000,
icon: sap.m.MessageBox.Icon.SUCCESS,
width: "20rem"
});
},
error: function (oError) {
MessageToast.show("Failure to create entry in oData service");
}
});
this.Initialize();
}
});
});<file_sep>/cliente/webapp/controller/Create.controller.js
sap.ui.define([
"./BaseController",
"sap/ui/model/json/JSONModel",
"sap/ui/core/routing/History",
"../model/formatter",
"sap/m/MessageToast",
"sap/ui/core/UIComponent"
], function(
BaseController,
JSONModel,
History,
formatter,
MessageToast,
UIComponent) {
"use strict";
return BaseController.extend("cliente.controller.Create", {
formatter: formatter,
/**
* @override
*/
onInit: function() {
var oViewModel = new JSONModel({
copies: 0
});
this.getView().setModel(oViewModel, "view");
var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
oRouter.getRoute("create").attachPatternMatched(this._onCreateMatched, this);
},
_onCreateMatched: function(oEvent){
this.getView().getModel("view").setProperty("/copies", 0);
var m = this.getView().getModel();
m.metadataLoaded().then(function() {
var oContext = m.createEntry("/ClientSet",
{
properties: {
Name: "",
Telephone: "",
District: "",
Email: "",
Status: "1"
}
});
this.getView().bindElement({
path: oContext.getPath()
});
}.bind(this))
},
onNavBack: function() {
var m = this.getView().getModel();
m.resetChanges();
var oHistory = History.getInstance();
var sPreviousHash = oHistory.getPreviousHash();
if (sPreviousHash !== undefined) {
window.history.go(-1);
} else {
var oRouter = UIComponent.getRouterFor(this);
oRouter.navTo("worklist", {}, true)
}
},
onGravar: function(oEvent){
var oModel = this.getView().getModel();
var data = {
Name: this.byId("InpName").getValue(),
Telephone: this.byId("InpTelephone").getValue(),
District: this.byId("InpUF").getValue(),
Email: this.byId("InpEmail").getValue(),
Status: "1"
};
oModel.create("/ClientSet", data, {
success: function(data, oResponse){
MessageToast.show('Client create successfully');
var mensagem = JSON.parse(oResponse.headers["sap-message"]);
}.bind(this),
error: function(e){
console.error(e)
}.bind(this)
});
},
onGravar2: function(){
var m = this.getView().getModel();
this.getView().setBusy(true);
var iCopies = this.getView().getModel("view").getProperty("/copies");
var oNewClient = this.getView().getBindingContext().getObject();
for (var i=0; i<iCopies; i++){
m.createEntry("/ClientSet", {
properties: {
Name: oNewClient.Name + " (Copia "+(i+1)+")",
Telephone: oNewClient.Telephone,
District: oNewClient.District,
Email: oNewClient.Email,
Status: "1"
}
});
}
m.submitChanges({
success: function (oData) {
this.getView().setBusy(false);
MessageToast.show("Cliente criado com sucesso.");
//var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
//var sId = this.getView().getBindingContext().getObject().ClientID;
//oRouter.navTo("object", { objectId: sId }, true);
}.bind(this),
error: function (oData) {
MessageToast.show("Aconteceu um erro.");
console.error(oData);
this.getView().setBusy(false);
}.bind(this),
});
},
});
});<file_sep>/cliente01/webapp/controller/Worklist.controller.js
sap.ui.define([
"sap/ui/core/mvc/Controller"
],
/**
* @param {typeof sap.ui.core.mvc.Controller} Controller
*/
function (Controller) {
"use strict";
return Controller.extend("cliente01.controller.Worklist", {
onInit: function () {
}
,
onClientePress: function (oEvent) {
var oRouter = this.getOwnerComponent().getRouter();
//oRouter.navTo("detailPage");
var oSource = oEvent.getSource();
var oContext = oSource.getBindingContext();
var sPath = oContext.getPath();
var obj = oContext.getObject();
oRouter.navTo("detailPage", {
idPath: obj.ClientID
});
}
});
});
| d1929afbe486134568c476c8db2fd883896d59ee | [
"JavaScript"
] | 4 | JavaScript | cleitondias/projects_ui5 | 69b8708536e570a929f4f453c915fddafa5d0ee2 | b1a899e0e775e5d80dcfdab12615f5a7c1b46722 |
refs/heads/master | <file_sep># 108153066 資應二 林育琳
109-1 資料結構作業:
1. role(struct結構)
2. array(陣列實作)
3. linked_01(class結構)
4. linked_02(鏈結串列實作)
5. stack(堆疊實作)
6. queue(佇列實作)
7. tree(樹實作)
8. binary tree(二元樹實作)
9. hash(雜湊表實作)
<file_sep>
#include <iostream>
#include "linked.h"
#include "test_linked.h"
/**
* 錯誤訊息函式。
*
* @param string: 要印出的錯誤訊息
* @return none.
**/
void TestLinked::error(const std::string err) {
std::cout << "ERROR!" << std::endl;
std::cout << " ==> " << err << std::endl;
exit(-1);
}
/**
* 測試函式。測試 append_data()。
*
* @param none.
* @return none.
**/
void TestLinked::test_append_data() {
Linked linked{0};
std::cout
<< "Testing function: append_data()..."
<< std::endl;
linked.dump_list();
for (int i = 0; i < 10; i += 1) {
std::cout
<< " Append node with node.data == "
<< i << std::endl;
linked.append_data(i);
linked.dump_list();
if (!linked.contain_data(i)) {
error("append_data() failed!!!");
};
}
} // test_append_data()
/**
* 測試函式。測試 contain_data()。
*
* @param none.
* @return none.
**/
void TestLinked::test_contain_data() {
Linked linked{10};
std::cout
<< "Testing function: contain_data()..."
<< std::endl;
linked.dump_list();
for (int i = 0; i < 10; i += 1) {
std::cout
<< " Contain node with node.data == "
<< i << std::endl;
if (!linked.contain_data(i)) {
error("contain_data() failed!!!");
};
}
} // test_contain_data()
/**
* 測試函式。測試 remove_data()。
*
* @param none.
* @return none.
**/
void TestLinked::test_remove_data() {
Linked linked{10};
std::cout
<< "Testing function: remove_data()..."
<< std::endl;
linked.dump_list();
for (int i = 1; i < 10; i += 2) {
std::cout
<< " Delete node with node.data == "
<< i << std::endl;
linked.remove_data(i);
linked.dump_list();
if (linked.contain_data(i)) {
error("remove_data() failed!!!");
};
}
} // test_remove_data()
void TestLinked::test_reverse_data() {
Linked linked{10};
linked.dump_list();
std::cout
<< "Testing function: reverse_data()..."
<< std::endl;
linked.reverse_data(0);
linked.dump_list();
if (!linked.contain_data(0)) {
error("reverse_data() failed!!!");
}
} // test_reverse_data()
void TestLinked::test_merge_data() {
Linked linkedL{9};
Linked linkedM{11};
std::cout
<< "Testing function: merge_data()..."
<< std::endl;
linkedL.dump_list();
linkedM.dump_list();
for (int i = 0; i < 10; i += 1) {
std::cout
<< " Merge node with node.data == "
<< i << std::endl;
linkedL.merge_data(i);
linkedL.dump_list();
linkedM.dump_list();
if (!linkedL.contain_data(i)) {
error("merge_data() failed!!!");
};
}
} // test_merge_data*/
// test_linked.cpp
<file_sep>class Node {
public:
Node *root();
void addChild(Node *, Node *);
void cut(Node *);
void paste(Node *, Node *);
void search_breadth(Node *);
void search_preorder(Node *);
void search_inorder(Node *);
void search_postorder(Node *);
public:
int data;
Node *left;
Node *right;
};
<file_sep>#include <iostream>
using namespace std;
const int i=3;
const int j=2;
int x,y;
int array[]={1,2,3,4,5,6};
int *p=array;
get(int i,int j)
{
return *(p+y*i+x);
}
set(int i,int j,int v)
{
*(p+y*i+x)=v;
}
void dump()
{
for(y=0;y<j;y++)
{
for(x=0;x<i;x++)
{
cout<<"array["<<y<<"]"<<"["<<x<<"]"<<"="<<get(i,j)<<" ";
}
cout<<endl;
}
}
int main()
{
dump();
}
<file_sep>#include <iostream>
#include "node.h"
int main(int argc, char *argv[]) {
Node tree;
Node *n1 = new Node();
Node *n2 = new Node();
Node *n3 = new Node();
Node *n4 = new Node();
Node *n5 = new Node();
Node *n6 = new Node();
Node *n7 = new Node();
std::cout << "Please input node data: " << std::endl;
std::cin >> n1->data >> n2->data >> n3->data >> n4->data >> n5->data >> n6->data >> n7->data;
Node *root_ = n1;
n1->left = n2;
n1->right = n3;
n2->left = n4;
n2->right = n5;
n3->left = n6;
n3->right = n7;
n4->left = NULL;
n4->right = NULL;
n5->left = NULL;
n5->right = NULL;
n6->left = NULL;
n6->right = NULL;
n7->left = NULL;
n7->right = NULL;
/* n1
/ \
n2 n3
/ \ / \
n4 n5 n6 n7 */
std::cout << "search_breadth: " << std::endl;
tree.search_breadth(root_);
std::cout << std::endl;
std::cout << "search_preorder: " << std::endl;
tree.search_preorder(root_);
std::cout << std::endl;
std::cout << "search_inorder: " << std::endl;
tree.search_inorder(root_);
std::cout << std::endl;
std::cout << "search_postorder: " << std::endl;
tree.search_postorder(root_);
} // main()
<file_sep>#include <iostream>
using namespace std;
#define CAPACITY 128
int top_ = -1;
int cache_[CAPACITY];
void push(int d) {
top_++;
cache_[top_] = d;
cout << "Push a number: " << cache_[top_] << endl;
}
int pop() {
cout << "Delete a top number: " << cache_[top_] << endl;
top_--;
return cache_[top_];
}
int top() {
cout << "cache_[top_] = " << cache_[top_] << endl;
return cache_[top_];
}
int peep(int i) {
if(i <= CAPACITY)
cout << "cache_[ith] = " << cache_[top_-i+1] << endl;
}
void empty() {
for(int i = top_ ; i >= top_ ; top_--) {
cout << "top_ = " << top_ << " cache_[top_] = " << cache_[top_] << endl;
if(top_ == 0)
break;
}
}
bool isEmpty() {
if(top_ == 0)
{
cout<< "Stack is empty." <<endl;
return true;
}
else
return false;
}
int main() {
push(1);
push(2);
push(3);
push(4);
push(5);
push(6);
top();
peep(2);
empty();
isEmpty();
}
<file_sep>#include <iostream>
#include <queue>
#include "node.h"
Node *Node::root(){
Node *root_ = new Node();
return root_;
}
void Node::addChild(Node *p, Node *n){
if(n->data > p->data)
p->right = n;
else
p->left = n;
}
void Node::cut(Node *t){
Node *root_1 = new Node();
root_1 = t;
}
void Node::paste(Node *n, Node *t){
Node *root_1 = new Node();
root_1 = t;
if(t->data > n->data)
n->right = t;
else
n->left = t;
}
void Node::search_breadth(Node *p){
std::queue <Node*> que;
que.push(p);
while (!que.empty()){
std::cout << que.front()->data << " ";
if (que.front()->left != NULL)
que.push(que.front()->left);
if (que.front()->right != NULL)
que.push(que.front()->right);
que.pop();
}
}
void Node::search_preorder(Node *p){
if(p != NULL){
std::cout << p->data << " ";
search_preorder(p->left);
search_preorder(p->right);
}
}
void Node::search_inorder(Node *p){
if(p != NULL){
search_inorder(p->left);
std::cout << p->data << " ";
search_inorder(p->right);
}
}
void Node::search_postorder(Node *p){
if(p != NULL){
search_postorder(p->left);
search_postorder(p->right);
std::cout << p->data << " ";
}
}
<file_sep>#include <iostream>
using namespace std;
#define BUFFER_SIZE 128
int head_ = 0;
int tail_ = -1;
int cache_[BUFFER_SIZE];
void enqueue(int d) {
tail_ = (tail_+1) % BUFFER_SIZE;
cache_[tail_] = d;
}
int dequeue() {
int d = cache_[head_];
head_ = (head_ +1) % BUFFER_SIZE;
return d;
}
void head() {
cout << "cache_[head_] = " << cache_[head_] << endl;
}
void tail() {
cout << "cache_[tail_] = " << cache_[tail_] << endl;
}
void peep(int i) {
cout << "cache_[ith] = " << cache_[i] << endl;
}
void empty() {
for(int i = head_ ; i <= tail_ ; head_++) {
cout << cache_[head_] << endl;
if(head_ == tail_)
break;
}
}
bool isEmpty() {
if(head_ == tail_)
{
cout << "Queue is empty." << endl;
return true;
}
else
return false;
}
int main() {
enqueue(1);
enqueue(2);
enqueue(3);
enqueue(4);
enqueue(5);
enqueue(6);
head();
tail();
peep(2);
empty();
isEmpty();
}
<file_sep>#include <iostream>
using namespace std;
struct Node{
int data;
Node *parent;
Node *children;
};
Node *root_, *root_1, *n1, *n2, *n3, *n4, *n5;
Node root() {
cout << "root = " << root_->data << endl;
return *root_;
}
void addChild(Node *p, Node *n) {
p->children = n;
cout << p->data << " add a new child node: " << n->data <<endl;
}
void cut(Node *t) {
root_1 = t;
cout << "Cut a new child tree: " << t->data << endl;
}
void paste(Node *n, Node *t) {
root_1 = t;
n->children = root_1;
cout << "Paste a child tree "<< t->data << " in " << n->data << endl;
}
int main() {
/*設定樹的節點、賦值。*/
n1 = new Node;
n1->data = 1;
root_ = n1;
n2 = new Node;
n2->data = 2;
n3 = new Node;
n3->data = 3;
n4 = new Node;
n4->data = 4;
n5 = new Node;
n5->data = 5;
/*設定中間節點的親節點、子節點:
n1
/ \
n2 n3
/\
n4 n5 */
n1->children = n2;
n1->children = n3;
n2->parent = n1;
n3->parent = n1;
n2->children = n4;
n2->children = n5;
n4->parent = n2;
n5->parent = n2;
n3->children = NULL;
n4->children = NULL;
n5->children = NULL;
root(); //回傳根節點
addChild(n3,n5); //設定 n5 為 n3 的子節點
cut(n2); //把 n2 設為子樹的根節點
paste(n1, n2); //把 n2 的子樹貼到 n1 上面
}
<file_sep>
#ifndef __LINKED_H__
#define __LINKED_H__
class Node {
friend class Linked;
Node *next; // 指向下一個 node
int data; // 實際資料
};
// node.h
class Linked {
public:
Linked(int);
~Linked();
public:
void append_data(int);
bool contain_data(int);
void remove_data(int);
void reverse_data(int);
void merge_data(int);
public:
void dump_list();
private:
Node *head;
};
#endif
// linked.h
| 1fe83473a80036db8b789b450c30840b17bf8bfb | [
"Markdown",
"C++"
] | 10 | Markdown | Irene314/DSPractice | 6f7134f6bd940d75b3a4fef8b3f79e06ce45c708 | 809bfece42ad6750e7080e0053dd547334df73d9 |
refs/heads/master | <file_sep>#add-project-to-repo
Easiest way to add existing project or files into repository
##Install
`npm i -g add-project-to-repo`
###Features
Get lazy and use
`atr link_to_your_repo`
instead of using list of commands
- git init
- git add .
- git commit -m "init"
- git remote add origin link_to_your_repo
- git remote -v
- git push origin master
it will run all these commands for you.
###Enjoy)
<file_sep>'use strict';
const exec = require('child_process').exec;
/**
* Builds command
* @return {string}
*/
exports.buildCommand = () => {
const args = process.argv.slice();
//get repository name
const repoName = args[2];
if (!repoName) {
console.log('Repository wasn\'t specified \n');
console.log('Please run "atr link_to_your_repo"');
process.exit(0);
}
return [
'git init',
'git add .',
'git commit -m "init"',
`git remote add origin ${repoName}`,
'git remote -v',
'git push origin master'
].join('&&');
};
/**
* Runs command
* @param {string} command
* @return {Object}
*/
exports.runCommand = (command) => {
return exec(command,
(error, stdout, stderr) => {
console.log(stdout);
if (error !== null) {
console.log(`exec error: ${error}`);
//remove git from current folder
this.runCommand('rm -rf .git');
}
});
};<file_sep>'use strict';
const helpers = require('./helpers');
/**
* Runs CLI
*/
exports.run = () => {
const command = helpers.buildCommand();
helpers.runCommand(command);
}; | 4b2bd2d919c7ec8781a13d9dc64b9c046adfebe1 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | denar90/add-project-to-repo | 05e22cbcf96fccb3d25943ea93f5eb284ef7743e | 00e484ba6177d82af24f0f19805b0ff4a5259343 |
refs/heads/master | <repo_name>BenMiddleton/Demo<file_sep>/game.js
function StartGame(boardElement) {
// game variables //
var nextPeiceId = 1;
var selectedPeice = null;
// constructor functions //
// a game peice
function Peice(isPlayer) {
this.isPlayer = isPlayer;
this.id = "p" + nextPeiceId++;
this.isKing = false;
this.x = null;
this.y = null;
this.element = document.createElement("span");
this.element.id = this.id;
this.element.classList.add("peice");
if (isPlayer)
this.element.classList.add("player");
else
this.element.classList.add("computer");
}
// helper functions //
function getPeiceFromElement(element) {
return playerPeices.find(function (p) {
if (p.id == peice.id)
return true;
else
return false;
});
}
// create the board
var board = [];
var rows = boardElement.getElementsByTagName("tr");
for (let i = 0; i < 8; i++) {
board[i] = [];
var row = rows[i].getElementsByTagName("td");
for (let j = 0; j < 8; j++) {
board[i][j] = row[j];
}
}
// create game peices
var computerPeices = [],
playerPeices = [];
for (let i = 0; i < 12; i++) {
computerPeices[i] = new Peice(false);
playerPeices[i] = new Peice(true);
}
// add peices to board
for (let i = 0; i < 12; i++) {
// er...
let x2 = x1 = i%4*2;
let y1 = (i-i%4)/4;
let y2 = y1 + 5;
// um...
if (y1%2 == 0)
x1 += 1;
else
x2 += 1;
// step three: profit!
computerPeices[i].x = x1;
computerPeices[i].y = y1;
board[y1][x1].appendChild(computerPeices[i].element);
playerPeices[i].x = x2;
playerPeices[i].y = y2;
board[y2][x2].appendChild(playerPeices[i].element);
}
// attach event listners
boardElement.onclick = function (e) {
var peice = e.target;
var cList = peice.classList;
if (cList.contains("player")) {
if (selectedPeice == null) {
cList.add("selected");
selectedPeice = peice;
} else if (selectedPeice == peice) {
cList.remove("selected");
selectedPeice = null;
} else {
selectedPeice.classList.remove("selected");
selectedPeice = peice;
cList.add("selected");
}
}
var x =
console.log(x.x+", "+x.y);
};
} | 2bc1f761ce11695107e7fd36282f17ff30c1bd94 | [
"JavaScript"
] | 1 | JavaScript | BenMiddleton/Demo | b9a1438d1f7ce09ea31135a0b8d896d6b7857bf1 | b28e039f6381e82691118b91692adb1db2bbd2e2 |
refs/heads/master | <repo_name>Toged/APPDomusG3<file_sep>/Energia/M1_question_1/Test_question_1.ino
#define LED1 2
#define LED2 34
#define LED3 35
#define LED4 36
#define LED5 37
#define POT 28
void setup() {
Serial.begin(9600);
Serial.println("Yo");
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
pinMode(LED4, OUTPUT);
pinMode(LED5, OUTPUT);
}
void loop() {
int potentiometre = analogRead(POT);
Serial.print("Valeur du convertisseur : ");
Serial.println(potentiometre);
Serial.print("Tension en volt correspondante : ");
Serial.println(potentiometre*3.3/4096);
if (potentiometre>4096*4/5)
{
digitalWrite(LED5, HIGH);
delay(100);
digitalWrite(LED5, LOW);
}
else if (potentiometre<4096*4/5 && potentiometre>4096*3/5)
{
digitalWrite(LED4, HIGH);
delay(100);
digitalWrite(LED4, LOW);
}
else if (potentiometre<4096*4/5 && potentiometre>4096*2/5)
{
digitalWrite(LED3, HIGH);
delay(100);
digitalWrite(LED3, LOW);
}
else if (potentiometre<4096*4/5 && potentiometre>4096*1/5)
{
digitalWrite(LED2, HIGH);
delay(100);
digitalWrite(LED2, LOW);
}
else if (potentiometre<4096/5)
{
digitalWrite(LED1, HIGH);
delay(100);
digitalWrite(LED1, LOW);
}
}
| e2134324447ecd98b11efe834b4d770976ea08d1 | [
"C++"
] | 1 | C++ | Toged/APPDomusG3 | 4ef8ea245a0c1f82260f7fb123a2e936923ee4fe | c5544335f51f515bd1823c01594f7cc19f5708cb |
refs/heads/master | <file_sep>import requests
from django.http import HttpResponse
from django.shortcuts import render
from django.shortcuts import redirect
def create_list():
import glob
all_html_files = glob.glob("templates/*.html")
pages = []
import os
for entry in all_html_files:
file_path = entry
file_name = os.path.basename(file_path)
name_only, extension = os.path.splitext(file_name)
if name_only != 'base':
pages.append({
"filename": "content/" + name_only + extension,
"title": name_only,
"output": "docs/" + name_only + extension,
"link_location": name_only + extension,
"link_box": '{{' + name_only + '_ph}}',
})
return pages
def create_links():
from jinja2 import Template
links_template_string = '''
{% for page in pages %}
<a href="{{page.link_location}}">
<span class="link {{page.link_box}}"> {{ page.title }}</span>
</a>
{% endfor %}
'''
links_template = Template(links_template_string)
links = links_template.render(
pages=create_list(),
)
return links
def index(request):
print('called index')
links = create_links()
index_links = links.replace("{{index_ph}}", 'box')
context = {
"links_ph": index_links,
}
return render(request, 'index.html', context)
def bio(request):
print('called bio')
links = create_links()
bio_links = links.replace("{{bio_ph}}", 'box')
context = {
"links_ph": bio_links,
}
return render(request, 'bio.html', context)
def contact(request):
print('called contact')
links = create_links()
contact_links = links.replace("{{contact_ph}}", 'box')
context = {
"links_ph": contact_links,
}
return render(request, 'contact.html', context)
def github(request):
print('called github')
links = create_links()
github_links = links.replace("{{github_ph}}", 'box')
response = requests.get('https://api.github.com/users/MichaelBMoss/repos')
repos = response.json()
context = {
"links_ph": github_links,
'github_repos': repos,
}
return render(request, 'github.html', context)
| 112555a8973174ea7311363743ec7b339acc670c | [
"Python"
] | 1 | Python | MichaelBMoss/Django-Homepage | a50ba6568aa73d6a82f86e9756c62cc7d705e43e | e9cdfe19ddf1bf3f04b830e23e10e4dd770fa326 |
refs/heads/main | <file_sep>from flask import Flask, render_template, request
from numpy.lib.type_check import imag
import pandas as pd
import numpy as np
import tensorflow as tf
from keras.preprocessing.image import load_img, img_to_array
from keras.models import load_model
import os
#create flask instance
app = Flask(__name__)
#set max size of file as 10MB
# app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024
#allow file with .png, .jpg and .jpeg
ALLOWED_EXTENSIONS = ['png','jpg','jpeg']
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.',1)[1].lower() in ALLOWED_EXTENSIONS
def init():
global graph
graph = tf.compat.v1.get_default_graph()
def read_image(filename):
img = load_img(filename,color_mode = "grayscale",target_size=(250,250))
img = img_to_array(img)
img = img.reshape(1,250,250,1)
img = imag.astype('float32')
img = img / 255.0
return img
#get - request data from the web server, post- send data to the web server
@app.route("/", methods = ['GET','POST'])
def home():
return render_template('home.html')
@app.route("/predict", methods = ['GET','POST'])
def predict():
if request.method == 'POST':
file = request.files['file']
# try:
if file and allowed_file(file.filename):
filename = file.filename
file_path = os.path.join('C:/Users/mavis/Documents/ana4/static/images',filename)
file.save(file_path)
img = read_image(file_path)
with graph.as_default():
model1 = load_model('C:/Users/mavis/Documents/ana4/trained_VGG_model.h5')
print(model1.head())
class_prediction = model1.predict(img)
print(class_prediction)
if class_prediction[0] == 0:
product = "BEANS"
elif class_prediction[0] == 1:
product = "CAKE"
elif class_prediction[0] == 2:
product = "CANDY"
elif class_prediction[0] == 3:
product = "CEREAL"
elif class_prediction[0] == 4:
product = "CHIPS"
elif class_prediction[0] == 5:
product = "CHOCOLATE"
elif class_prediction[0] == 6:
product = "COFFEE"
elif class_prediction[0] == 7:
product = "CORN"
elif class_prediction[0] == 8:
product = "FISH"
elif class_prediction[0] == 9:
product = "FLOUR"
elif class_prediction[0] == 10:
product = "HONEY"
elif class_prediction[0] == 11:
product = "JAM"
elif class_prediction[0] == 12:
product = "JUICE"
elif class_prediction[0] == 13:
product = "MILK"
elif class_prediction[0] == 14:
product = "NUTS"
elif class_prediction[0] == 15:
product = "OIL"
elif class_prediction[0] == 16:
product = "PASTA"
elif class_prediction[0] == 17:
product = "RICE"
elif class_prediction[0] == 18:
product = "SODA"
elif class_prediction[0] == 19:
product = "SPICES"
elif class_prediction[0] == 20:
product = "SUGAR"
elif class_prediction[0] == 21:
product = "TEA"
elif class_prediction[0] == 22:
product = "TOMATO_SAUCE"
elif class_prediction[0] == 23:
product = "VINEGAR"
else:
product = "WATER"
return render_template('predict.html', product = product, user_image = file_path)
# except Exception as e:
# return "Unable t read the file, please check file extension."
return render_template('predict.html')
if __name__ == "__main__":
init()
app.run() | 879ab2c1615344c5a30605027be39a47b5e0ea21 | [
"Python"
] | 1 | Python | mavismonica/analytics4 | 4bf18e810d1f97bd5c6ef812325fddcbb3e22892 | 8a242e53a4207f9bc500b240dc859fa671617b2a |
refs/heads/master | <repo_name>studiomohawk/QOF<file_sep>/test/app/app.js
module( 'Getting familiar with QUnit' );
test('Namespace should be qof', function() {
expect(1);
ok( window.qof, 'Namespace is qof and public' );
});
test('init method is woking', function() {
expect(1);
ok( window.qof.init, 'init method is revving up for refactoring' );
});
module( 'Input values', {
setup: function() {
$('#quote-text').val('quote');
$('#author').val('author');
$('#source').val('url');
},
teardown: function() {
$('#quote-text').val('');
$('#author').val('');
$('#source').val('');
}
} );
test('User input values are good to go', function() {
expect(3);
qof.init();
equal( qof.getData().quote, 'quote', 'quote is in #quote-text' );
equal( qof.getData().author, 'author', 'author is in #author' );
equal( qof.getData().url, 'url', 'url is in #source' );
});
module( 'Templating', {
setup: function() {
$('#quote-text').val('quote');
$('#author').val('author');
$('#source').val('url');
},
teardown: function() {
$('#quote-text').val('');
$('#author').val('');
$('#source').val('');
}
} );
test('Generate HTML from input data', function() {
expect(1);
var html = qof.template();
var dummy = '<li>' +
'<div class="quote">' +
'<p class="text">' +
'quote'+
'</p>' +
'<p class="meta">' +
'<span class="author">' +
'—' + 'author' +
'</span>' + ' / ' + '<span class="source"><a href="url">参照元</a></span>' +
'</p>' +
'</div>' +
'</li>';
equal( html, dummy, 'Templating is working' );
});
<file_sep>/readme.md
# Q.O.F - Quotes on Front-end
Q.O.Fはフロントエンドにまつわるクオートを集積するウェブアプリケーションです。
本アプリケーションは **テストしやすいJavaScript** のデモ用に作成されました。
## ブランチモデル
### not_good
このバージョンでは、大きく分けて以下の4つのアクションが混在しています。
1. jQueryの`domready`イベント / ページイベント
2. 保存ボタン(`#form-send-mock`)のクリックイベント / ユーザイベント
3. フォーム(`#send-quote`)内のデータ / ユーザインプット
4. `.append()`内でのHTML生成 / HTMLテンプレート
このバージョンではサーバとのデータの送受信を行うロジックは **組み込まれていません。**
jQueryの`$.ajax()`メソッドを使ってデータの送信を行うとしたら、上記に加えて:
- ネットワーク書き込み
- `success`や`error`などのネットワークイベント
の2つのアクションが追加されることになります。
併せて6つのアクションがそれぞれ複雑に関連しあって、本アプリケーションに必要なロジックを実行しています。
### master
このバージョンでは、`not_goodブランチ`のソースコードをテストしやすいコードへとリファクタしています。
実際にJavaScriptのテストツールである[mocha](http://visionmedia.github.com/mocha/)を使ったテストも行っています。
`not_goodブランチ`で実装したロジックそのものには変更はありません。
このバージョンでもサーバとのデータの送受信を行うロジックは **組み込まれていません。**
### firebase (未実装)
このバージョンは[Firebase](https://www.firebase.com)というJavaScriptから簡単にデータの生成、保存、取得などを行えるサービスを利用し、実際にきちんと動作するアプリケーションにしています。
テストしやすいJavaScriptとは一切関係がありませんが、手軽にデータのIOに関連するバックエンド環境を利用できるので、サンプルアプリケーションなどを構築するのに非常に便利です。
プログラミングに限りませんが、何かを学ぶ上でもっとも効率的な方法は実際にやってみることです。
JavaScriptを書きたいと長らく思っているけど、まだ書けない。
と感じている方は是非、このアプリ、Q.O.F、に新しい機能を追加するなどから初めてみてはいかがでしょうか。
新機能を追加した際にはぜひPull
Requestを送って下さい。1人で開発するよりも多くの人と一緒に開発したほうが楽しいですし、勉強にもなりますので。
## ライセンス
Anything I wrote is public domain: [http://unlicense.org/](http://unlicense.org/]).
Other than that, please refer and respect thier licence.
- [jQuery](http://jquery.com/) / MIT license by jQuery Foundation
- [Font Awesome](https://github.com/FortAwesome/Font-Awesome) / SIL Open Font License、MIT license、CC BY 3.0 License by <NAME>
- [SubtlePatterns](https://github.com/subtlepatterns/SubtlePatterns) / CC BY 3.0 License by Atle Mo
- [Grunt](https://github.com/gruntjs/grunt) / MIT license by "Cowboy" <NAME>, contributors
Initially build by <NAME> <<EMAIL>>
Made Proudly in Tokyo.
<file_sep>/app/app.js
var qof = {
init: function() {
$('#form-send-mock').on('click', function(e) {
qof.render();
});
},
getData: function() {
return {
'quote': $('#quote-text').val(),
'author': $('#author').val(),
'url': $('#source').val()
};
},
clearInput: function() {
$('#quote-text').val('');
$('#author').val('');
$('#source').val('');
},
template: function() {
var data = qof.getData();
var html = '<li>' +
'<div class="quote">' +
'<p class="text">' +
data.quote +
'</p>' +
'<p class="meta">' +
'<span class="author">' +
'—' + data.author +
'</span>' + ' / ' + '<span class="source"><a href="' + data.url + '">参照元</a></span>' +
'</p>' +
'</div>' +
'</li>';
return html;
},
render: function() {
var html = qof.template();
$('#quotes').append(html);
}
};
(function() {
qof.init();
})();
// Toggle form
$(document).on('click', '#toggle-form', function(e){
var $this = $(this);
var $icon = $this.find('.icon');
var $sendQuote = $('#send-quote');
if ($sendQuote.hasClass('is-close')) {
$($icon).removeClass('icon-chevron-right').addClass('icon-chevron-up');
$($sendQuote).removeClass('is-close').addClass('is-open');
} else {
$($icon).removeClass('icon-chevron-up').addClass('icon-chevron-right');
$($sendQuote).removeClass('is-open').addClass('is-close');
}
});
<file_sep>/app/app-done.js
var qof = {
init: function() {
this.cacheElements();
this.bindEvents();
},
cacheElements: function() {
this.$button = $('#form-send-mock');
this.$toggle = $('#toggle-form');
this.$text = $('#quote-text');
this.$author = $('#author');
this.$source = $('#source');
},
bindEvents: function() {
this.$button.on( 'click', this.template );
this.$toggle.on( 'click', this.toggle );
},
getData: function() {
return {
'quote' : this.$text.val(),
'author': this.$author.val(),
'url' : this.$source.val()
};
},
clearInput: function() {
this.$text.val('');
this.$author.val('');
this.$source.val('');
},
template: function() {
var data = qof.getData();
html = '<li>' +
'<div class="quote">' +
'<p class="text">' +
data.quote +
'</p>' +
'<p class="meta">' +
'<span class="author">' +
'— ' + data.author +
'</span>' + ' / ' + '<span class="source"><a href="' + data.url + '">参照元</a></span>' +
'</p>' +
'</div>' +
'</li>';
qof.render(html);
},
render: function(html) {
$('#quotes').append(html);
this.clearInput();
},
toggle: function(e) {
var $this = $(this);
var $icon = $this.find('.icon');
var $sendQuote = $('#send-quote');
if ($sendQuote.hasClass('is-close')) {
$($icon).removeClass('icon-chevron-right').addClass('icon-chevron-up');
$($sendQuote).removeClass('is-close').addClass('is-open');
} else {
$($icon).removeClass('icon-chevron-up').addClass('icon-chevron-right');
$($sendQuote).removeClass('is-open').addClass('is-close');
}
}
};
(function() {
qof.init();
})();
| 0f161f0a74f059ab7e4053463abafee74096a6fa | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | studiomohawk/QOF | 577bd8136c478cea3b5b265f2cb2d64c50976404 | 9a7fb5c4e77d970795e34ae9da8ef74e8bd8db43 |
refs/heads/master | <repo_name>logan-ihi/jekyll-testing<file_sep>/Gemfile
# frozen_string_literal: true
source "https://rubygems.org"
gemspec
# local testing for ruby 3.0.0+
gem "webrick", "~> 1.7"
<file_sep>/index.md
---
layout: default
title: "Happy Jekylling!"
---
## This is a test!
Start developing your Jekyll website.
<file_sep>/jekyll-testing.gemspec
# frozen_string_literal: true
Gem::Specification.new do |spec|
spec.name = "jekyll-gamedev"
spec.version = "0.1.0"
spec.authors = ["<NAME>"]
spec.email = ["<EMAIL>"]
spec.summary = "Theme for Github Pages site."
spec.homepage = "http://www.example.com"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").select { |f| f.match(%r!^(assets|_layouts|_includes|_sass|LICENSE|README|_config\.yml)!i) }
spec.add_runtime_dependency 'github-pages', '>= 217'
end
| e00517731c1b3bf53b386d53861e766475de71e1 | [
"Markdown",
"Ruby"
] | 3 | Ruby | logan-ihi/jekyll-testing | ab1e70059d21fa2f22d5d39f724ce9a58483863a | 8246b23968b8904f10774a2d904fd2ee40ceca38 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class TicketPurchasingGUI : Form
{
public TicketPurchasingGUI()
{
InitializeComponent();
}
private int unitPrice = 30;
string CoustomerName;
int TotalPrice;
private void TotalPriceButton_Click(object sender, EventArgs e)
{
Populate();
string MessageOutput = CoustomerName + ", You have to pay " + TotalPrice + " Taka";
MessageBox.Show(MessageOutput);
}
private void Populate()
{
CoustomerName = CoustomerNameTextBox.Text;
int NumberOfTickets = Convert.ToInt32(NumberOfTicketsTextBox.Text);
TotalPrice = NumberOfTickets * unitPrice;
}
private void DetailsButton_Click(object sender, EventArgs e)
{
Populate();
string messageoutput = "Coustomer Name : " + CoustomerName + Environment.NewLine + "Total Price : " + TotalPrice;
MessageBox.Show(messageoutput);
}
}
}
| 18f5173eff353d565e1fa906500d6de8057186f3 | [
"C#"
] | 1 | C# | Nazirul13044/code | c6b41236f4501f205e8fe23d3508d94645527a19 | a6875d20aebe5c709e94e765a9ce4a9207ad1d71 |
refs/heads/master | <repo_name>docvinum/vivino-export<file_sep>/winescrape.js
(function(){
var removeVarietal = function(title){
var wine_types = ['port', 'shiraz','merlot', 'sauvignon blanc', 'rosť', 'rose', 'cabernet sauvignon', 'red', 'zinfandel', 'syrah', 'malbec', 'riesling', 'pinot noir', 'cabernet franc', 'bordeaux', 'chardonnay'];
var wine_prefix = ['late harvest', 'old vine'];
var process_title = {};
$(wine_types).each(function(i,val){
if (title.indexOf(val) !== -1){
process_title['title'] = title.replace(val,'');
process_title['varietal'] = val;
}
});
return process_title;
}
console.log('title,year,type,rating');
$('.wine_list_item').each(function(i,ele){
var title = $(ele).find('.description a').html();
var rating = $(ele).find('.mw_buttons input').val();
if (title && rating && rating > 0){
title = title.toLowerCase();
var process_title = removeVarietal(title);
console.log(title.replace(/\d+/, '').trim() + ','
+ title.replace(/[^\d]+/, '')+','
+rating );
}
});
})();<file_sep>/README.md
How to use:
login and open your wines page in vivino (http://www.vivino.com/myvivino/my-wines/1/)
switch wines per page to 100
open javascript console, copy+paste contents of winescrape.js
console will output CSV, copy+paste into notepad and save as .csv | 3b7b3dc71468a27fb7804a40c0743615b834ac28 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | docvinum/vivino-export | 28af912ab8eaa9fb9a5cc1b4c27b5212eafa9822 | e702b022b42e3631dd72440b68d360fe317eec2c |
refs/heads/master | <file_sep><?php
/*
FAQ Endpoints for WP REST API
*/
function faq_add_posts_endpoints() {
register_rest_route( 'api/v2', 'faq', array(
'methods' => 'POST',
'callback' => 'post_faq_callback'
));
}
function post_faq_callback( $data ) {
$params = $data->get_json_params();
$api_response = wp_remote_post( get_rest_url( null, 'wp/v2/faq' ), array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( FAQ_USER . ':' . FAQ_PASSWORD )
),
'body' => array(
'title' => $params['title'],
'content' => $params['content']
)
));
return json_decode( $api_response['body'] );
}
add_action( 'rest_api_init', 'faq_add_posts_endpoints' );<file_sep># Guardiões FAQ
Plugin que adiciona o FAQ ao site do Guardiões da Saúde e permite ser utilizado por endpoints.
## Instalação
### Instalando dependências
1. Clone o repositório [Basic-Auth](https://github.com/WP-API/Basic-Auth) e depois copie-o para a pasta *plugins* (/wp-content/plugins):
```
git clone https://github.com/WP-API/Basic-Auth.git
```
2. Ative o plugin no painel do WordPress
### Configurando Usuário permitido
1. Crie um usuário no painel com função de Colaborador.
2. Acrescente as seguintes linhas ao arquivo *wp-config.php*, localizado na raiz do site:
```
define( 'FAQ_USER', 'username' );
define( 'FAQ_PASSWORD', '<PASSWORD>' );
```
3. Substitua o username e senha pelos do usuário que criou no passo 1.
## Solucionando problemas
### Mensagem "Sem permissão para criar posts com este usuário."
1. Verifique se plugin Basic-Auth está instalado e ativo no painel.
2. Verifique se os dados do usuário estão corretos no arquivo *wp-config.php*.
2. Adicione a seguinte linha ao arquivo .htaccess, localizado na raiz do site:
Após a linha RewriteEngine On, adicionar:
```
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
```
----
## Copyright
ProEpi, Associação Brasileira de Profissionais de Epidemiologia de Campo<file_sep><?php
/*
Plugin Name: Guardiões FAQ
Plugin URI: https://github.com/alvesitalo/guardioes-faq
Description: Adiciona o FAQ ao Guardiões da Saúde, permite ser usado pelo site e pela REST API.
Version: 1.0
Author: <NAME>
Author URI: https://github.com/alvesitalo
License: GPL2
*/
function create_post_type_faq() {
$labels = array(
'name' => 'FAQ',
'singular_name' => 'FAQ',
'add_new' => 'Adicionar nova',
'add_new_item' => 'Adicionar nova pergunta',
'edit_item' => 'Editar pergunta',
'new_item' => 'Nova pergunta',
'all_items' => 'Todas as perguntas',
'view_item' => 'Ver pergunta',
'search_items' => 'Pesquisar perguntas'
);
$args = array(
'labels' => $labels,
'description' => 'Permite adicionar perguntas ao site',
'public' => true,
'menu_position' => 5,
'menu_icon' => 'dashicons-format-status',
'supports' => array( 'title', 'editor', 'excerpt' ),
'has_archive' => true,
'show_in_rest' => true,
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'query_var' => true,
);
// Register FAQ post type
register_post_type( 'faq', $args );
}
include_once('endpoints.php');
add_action( 'init', 'create_post_type_faq' ); | 2d5fd30f26dc39116474b607f7986532eac45987 | [
"Markdown",
"PHP"
] | 3 | PHP | alvesitalo/guardioes-faq | 3de34edb6f31a7cb0205b54602f59ba0bd34d22e | 74e88e08872c00d1ea74970e390fc6db483c5ce0 |
refs/heads/master | <repo_name>badhbh/isr<file_sep>/oop_test.py
import unittest
import oop
class TestSum(unittest.TestCase):
def test_oop(self):
#song_j = "jjj"
#subg_j = "jj"
#sog = oop.Song(song_j, subg_j)
# self.assertEqual()
self.alb_c = oop.Album_collection()
print("ok")
if __name__ == '__main__':
unittest.main()
<file_sep>/oop.py
class Song:
def __init__(self, name, subgenre):
self.name = name
self.subgenre = subgenre
class Album:
def __init__(self, name):
self.name = name
self.songs = []
def add_song(self, song):
self.songs.append(song)
def get_size_of_album(self):
return len(self.songs)
class Artist:
def __init__(self, name):
self.name = name
self. creatures = []
def add_album(self, album):
self.creatures.append(album)
def number_of_albums(self):
return len(self.creatures)
class Album_collection:
def __init__(self):
self.albums = []
def add_album(self, album):
self.albums.append(album)
def size_of_album_coll(self):
return len(self.albums)
class Genre:
def __init__(self, name):
self.collection_genres = []
self.name = name
def add_subgenre(self, subgenre):
self.collection_genres.append(subgenre)
class Genre_collection:
def __init__(self):
self.genre_collections = []
def add_genre(self, genre):
self.genre_collections.append(genre)
def add_subgenre(self, genre):
self.collection_genres.append(genre)
class Playlist:
def __init__(self, name):
self.playlist = []
self.name = name
class Playlist_collection:
def __init__(self):
self.playlists = []
def add_playlist(self, playlist):
self.playlists.append(playlist)
def get_size_of_playlist_collection(self):
return len(self.playlists)
name_s1 = "jojo"
subg1 = "jo"
song = Song(name_s1, subg1)
name_a1 = "hhh"
album = Album(name_a1)
album.add_song(song.name)
name_ar1 = "Reno"
artist = Artist(name_ar1)
album_collection = Album_collection()
album_collection.add_album(album)
print(song.name, album.name, album.songs[0], artist.name,
album_collection.albums[0].name)
<file_sep>/README.md
# лабораторная работа №2
## коллекция музыки
### код на python
### классы: song, album, artist album_collection etc.
### функции: добавление песен, авторов, создание плейлистов и т.д
| f70d90fec38be654e4988e1f6078fca262d216a6 | [
"Markdown",
"Python"
] | 3 | Python | badhbh/isr | e6a27506a9974f523664a134d89b5eaeaf240bd3 | 6d01703c8aec710f015261db003a0d714aedb748 |
refs/heads/master | <repo_name>SamuelRousseaux/PSU_lemipc_2017<file_sep>/inc/lemipc.h
/*
** EPITECH PROJECT, 2018
** lemipc
** File description:
** lemipc.h
*/
#ifndef LEMIPC_H_
# define LEMIPC_H_
# define SUCCESS 0
# define FAIL 84
# define MAP_X 10
# define MAP_Y 10
# define MAP_SIZE (MAP_X * MAP_Y * sizeof(int *))
# define RED "\e[41m\e[97m"
# define GRN "\e[42m\e[97m"
# define YEL "\e[43m\e[97m"
# define BLU "\e[44m\e[97m"
# define MAG "\e[45m\e[97m"
# define CYN "\e[46m\e[97m"
# define RST "\e[0m"
# define LEADER_DEAD -1
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include <sys/msg.h>
typedef enum { false, true } bool;
typedef struct s_my_msg
{
long mtype;
char str[32];
} t_my_msg;
typedef struct s_soldier
{
int team_number;
char *path;
key_t f_key;
int pos_x;
int pos_y;
bool is_alive;
int semid;
int shmid;
int msgid;
bool host;
int **field;
int leader;
} soldier_t;
int check_if_alive(soldier_t *);
int check_nb_team(soldier_t *);
int fill_map(soldier_t *);
int get_map(soldier_t *);
int get_msg(soldier_t *);
int get_sem(soldier_t *);
int init_battle(char **, soldier_t *);
void lock_sem(soldier_t *);
void move(soldier_t *);
int nb_player(soldier_t *);
int place_soldier(soldier_t *);
void print_map(soldier_t *);
void unlock_sem(soldier_t *);
void send_msg(soldier_t *, char *);
void rcv_msg(soldier_t *);
void rand_mov(soldier_t *);
void right_left(soldier_t *);
void down_up(soldier_t *);
void try_move(int, int, soldier_t *);
#endif /*!LEMIPC_H_*/
<file_sep>/src/main.c
/*
** EPITECH PROJECT, 2018
** lemipc
** File description:
** main
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include "lemipc.h"
void help(void)
{
printf("USAGE\n");
printf("\t./lemipc PATH TEAM_NUMBER\n\n");
printf("DESCRIPTION\n");
printf("\tPATH\t\tpath you'll give to ftok\n");
printf("\tTEAM_NUMBER\tteam number of the current champion");
printf(" (greater than 0)\n");
}
void kill_soldier(soldier_t *soldier)
{
lock_sem(soldier);
soldier->is_alive = false;
soldier->field[soldier->pos_y][soldier->pos_x] = 0;
send_msg(soldier, "ARGUE");
unlock_sem(soldier);
}
int end(soldier_t *soldier)
{
if (shmget(soldier->f_key, MAP_SIZE, SHM_R | SHM_W) == -1)
return (1);
return (0);
}
int game_loop(soldier_t *soldier)
{
while (!check_nb_team(soldier)) {
if (soldier->host)
print_map(soldier);
move(soldier);
usleep(100000);
}
while ((soldier->is_alive && check_nb_team(soldier) && !end(soldier))
|| soldier->host) {
if (soldier->host) {
print_map(soldier);
if (!check_nb_team(soldier))
return (1);
}
if (check_if_alive(soldier))
move(soldier);
else
kill_soldier(soldier);
usleep(100000);
}
return (1);
}
int main(int argc, char **argv)
{
soldier_t soldier;
srand(getpid());
if (argc == 1 || !strcmp(argv[1], "--help") || argc != 3) {
help();
return (0);
}
if (!init_battle(argv, &soldier)) {
if (soldier.host) {
shmctl(soldier.shmid, IPC_RMID, 0);
semctl(soldier.shmid, IPC_RMID, 0);
}
return (84);
}
game_loop(&soldier);
if (soldier.host) {
shmctl(soldier.shmid, IPC_RMID, 0);
semctl(soldier.shmid, IPC_RMID, 0);
}
return (0);
}
<file_sep>/Makefile
##
## EPITECH PROJECT, 2018
## lemipc
## File description:
## Makefile
##
NAME = lemipc
SRC = src/init.c \
src/main.c \
src/map.c \
src/sem.c \
src/sem_msgq.c \
src/soldier.c \
src/msg_func.c \
src/move_func.c
OBJ = $(SRC:.c=.o)
CC = gcc
CFLAGS += -W -Wall -Wextra -I./inc -lpthread -fno-stack-protector
all: $(NAME)
$(NAME): $(OBJ)
$(CC) $(OBJ) -o $(NAME) $(CFLAGS)
clean:
$(RM) $(OBJ)
fclean: clean
$(RM) $(NAME)
re: fclean all
.PHONY: all clean fclean re
<file_sep>/src/soldier.c
/*
** EPITECH PROJECT, 2018
** *
** File description:
** *
*/
#include <stdlib.h>
#include <stdio.h>
#include "lemipc.h"
void try_move(int x, int y, soldier_t *soldier)
{
int nx = soldier->pos_x + x;
int ny = soldier->pos_y + y;
lock_sem(soldier);
if (nx < MAP_X && nx >= 0 && ny < MAP_Y && ny >= 0
&& soldier->field[ny][nx] == 0) {
soldier->field[soldier->pos_y][soldier->pos_x] = 0;
soldier->field[ny][nx] = soldier->team_number;
soldier->pos_y = ny;
soldier->pos_x = nx;
}
unlock_sem(soldier);
}
void move(soldier_t *soldier)
{
int rdm = rand() % 3;
send_msg(soldier, "ALIVE");
rcv_msg(soldier);
if (rdm == 0)
down_up(soldier);
else if (rdm == 1)
right_left(soldier);
else
rand_mov(soldier);
}
int check_array_enemies(int *enemies)
{
int save1 = 0;
int save2;
for (int j = 0 ; j < 8 ; j++) {
save2 = 0;
if (enemies[j] == 0)
continue;
for (int z = 0 ; z < 8 ; z++)
if (enemies[z] == enemies[j])
save2++;
save1 = (save2 > save1) ? save2 : save1;
}
if (save1 >= 2)
return (1);
return (0);
}
int check_if_alive(soldier_t *soldier)
{
int xpos = soldier->pos_x;
int ypos = soldier->pos_y;
int enemies[8] = { 0 };
int i = -1;
lock_sem(soldier);
for (int x = xpos - 1 ; x <= xpos + 1 ; x++)
for (int y = ypos - 1 ; y <= ypos + 1 ; y++) {
if (y == ypos && x == xpos)
continue;
if (x >= 0 && x < MAP_X && y >= 0 && y < MAP_Y &&
soldier->field[y][x] != soldier->team_number)
enemies[++i] = soldier->field[y][x];
}
if (check_array_enemies(enemies)) {
unlock_sem(soldier);
return (0);
}
unlock_sem(soldier);
return (1);
}
int place_soldier(soldier_t *soldier)
{
int x = 0;
int y = 0;
lock_sem(soldier);
if (nb_player(soldier) != (MAP_X * MAP_Y)) {
while (soldier->field[y][x] != 0) {
x = rand() % MAP_X;
y = rand() % MAP_Y;
}
soldier->pos_x = x;
soldier->pos_y = y;
soldier->field[y][x] = soldier->team_number;
} else {
printf("There's no room left on this battlefield!\n");
unlock_sem(soldier);
return (0);
}
unlock_sem(soldier);
return (1);
}
<file_sep>/src/init.c
/*
** EPITECH PROJECT, 2018
** *
** File description:
** *
*/
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "lemipc.h"
int is_num(char *nb)
{
for (int i = 0 ; nb[i] != '\0' ; i++)
if (nb[i] < '0' || nb[i] > '9')
return (0);
return (1);
}
int set_soldier(char **argv, soldier_t *soldier)
{
if (is_num(argv[2]) && atoi(argv[2])) {
soldier->team_number = atoi(argv[2]);
soldier->path = argv[1];
soldier->f_key = ftok(soldier->path, 0);
if (soldier->f_key == -1) {
fprintf(stderr, "Error while getting key: %s\n",
strerror(errno));
return (0);
}
return (1);
} else {
fprintf(stderr, "Error: team isn't a positive number\n");
return (0);
}
}
int init_battle(char **argv, soldier_t *soldier)
{
if (!set_soldier(argv, soldier))
return (0);
if (!get_map(soldier))
return (0);
if (!get_sem(soldier))
return (0);
if (!get_msg(soldier))
return (0);
if (!place_soldier(soldier))
return (0);
soldier->is_alive = true;
return (1);
}
<file_sep>/src/move_func.c
/*
** EPITECH PROJECT, 2018
** lemipc
** File description:
** move_func.c
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "lemipc.h"
void down_up(soldier_t *soldier)
{
if (soldier->pos_y < MAP_Y / 2)
try_move(0, 1, soldier);
else if (soldier->pos_y > MAP_Y / 2)
try_move(0, -1, soldier);
}
void right_left(soldier_t *soldier)
{
if (soldier->pos_x < MAP_X / 2)
try_move(1, 0, soldier);
else if (soldier->pos_x > MAP_X / 2)
try_move(-1, 0, soldier);
}
void rand_mov(soldier_t *soldier)
{
int x_rdn = rand() % 2;
int y_rdn = rand() % 2;
try_move(x_rdn, y_rdn, soldier);
}
<file_sep>/src/map.c
/*
** EPITECH PROJECT, 2018
** *
** File description:
** *
*/
#include <stdlib.h>
#include <stdio.h>
#include "lemipc.h"
static char *colors[] = { RST, RED, GRN, YEL, BLU, MAG, CYN };
int check_nb_team(soldier_t *soldier)
{
int nb1 = 0;
for (int i = 0 ; i < MAP_Y ; i++)
for (int j = 0 ; j < MAP_X ; j++) {
if (soldier->field[i][j] != 0 && nb1 == 0)
nb1 = soldier->field[i][j];
else if (soldier->field[i][j] != 0 &&
soldier->field[i][j] != nb1)
return (1);
}
return (0);
}
int nb_player(soldier_t *soldier)
{
int nb = 0;
for (int i = 0 ; i < MAP_Y ; i++)
for (int j = 0 ; j < MAP_X ; j++)
if (soldier->field[i][j] != 0)
nb++;
return (nb);
}
void print_map(soldier_t *soldier)
{
printf("\nmap: %dx%d\n", MAP_X, MAP_Y);
for (int i = 0 ; i < MAP_Y ; i++) {
for (int j = 0 ; j < MAP_X ; j++) {
if (soldier->field[i][j] != 0)
printf("%s%d" RST,
colors[soldier->field[i][j] % 7],
soldier->field[i][j]);
else
printf("%d", soldier->field[i][j]);
printf(" ");
}
printf("\n");
}
}
int fill_map(soldier_t *soldier)
{
void *data;
data = shmat(soldier->shmid, NULL, SHM_R | SHM_W);
if (data == (void *)(-1))
return (0);
soldier->field = malloc(MAP_SIZE);
if (!soldier->field)
return (0);
for (int i = 0 ; i < MAP_Y ; i++)
soldier->field[i] = &((int *)data)[MAP_X * i];
if (soldier->host) {
for (int i = 0 ; i < MAP_Y ; i++) {
for (int j = 0 ; j < MAP_X ; j++)
soldier->field[i][j] = 0;
}
}
return (1);
}
int get_map(soldier_t *soldier)
{
soldier->shmid = shmget(soldier->f_key, MAP_SIZE, SHM_R | SHM_W);
if (soldier->shmid == -1) {
printf("create\n");
soldier->shmid = shmget(soldier->f_key, MAP_SIZE,
IPC_CREAT | SHM_R | SHM_W);
soldier->host = true;
if (!fill_map(soldier))
return (0);
} else {
printf("join\n");
soldier->host = false;
if (!fill_map(soldier))
return (0);
}
return (1);
}
<file_sep>/src/sem_msgq.c
/*
** EPITECH PROJECT, 2018
** *
** File description:
** *
*/
#include "lemipc.h"
int get_msg(soldier_t *soldier)
{
soldier->msgid = msgget(soldier->f_key, SHM_R | SHM_W);
if (soldier->msgid == -1) {
soldier->msgid = msgget(soldier->f_key, IPC_CREAT |
SHM_R | SHM_W);
if (soldier->msgid == -1)
return (0);
}
return (1);
}
int get_sem(soldier_t *soldier)
{
soldier->semid = semget(soldier->f_key, 1, SHM_R | SHM_W);
if (soldier->semid == -1) {
soldier->semid = semget(soldier->f_key, 1,
IPC_CREAT | SHM_R | SHM_W);
if (soldier->semid == -1)
return (0);
if (semctl(soldier->semid, 0, SETVAL, 1) == -1)
return (0);
}
else if (soldier->host)
if (semctl(soldier->semid, 0, SETVAL, 1) == -1)
return (0);
return (1);
}
<file_sep>/src/msg_func.c
/*
** EPITECH PROJECT, 2018
** lemipc
** File description:
** msg_func.c
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "lemipc.h"
void rcv_msg(soldier_t *soldier)
{
t_my_msg buff;
msgrcv(soldier->msgid, &buff, sizeof(buff),
soldier->team_number, IPC_NOWAIT);
}
void send_msg(soldier_t *soldier, char *str)
{
t_my_msg buff;
bzero(&buff, sizeof(buff));
buff.mtype = soldier->team_number;
sprintf(buff.str, "%s", str);
msgsnd(soldier->msgid, &buff, sizeof(buff), 0);
}
<file_sep>/src/sem.c
/*
** EPITECH PROJECT, 2018
** *
** File description:
** *
*/
#include "lemipc.h"
void lock_sem(soldier_t *soldier)
{
struct sembuf buff;
buff.sem_num = 0;
buff.sem_flg = 0;
buff.sem_op = -1;
semop(soldier->semid, &buff, 1);
}
void unlock_sem(soldier_t *soldier)
{
struct sembuf buff;
buff.sem_num = 0;
buff.sem_flg = 0;
buff.sem_op = 1;
semop(soldier->semid, &buff, 1);
}
| 67900a7c0e9c43e73d1ef75bc329bff587a7b9b4 | [
"C",
"Makefile"
] | 10 | C | SamuelRousseaux/PSU_lemipc_2017 | af83693326fe139c7ab6b457d57f2b09f77e8ab7 | 97021401c47de398ba0165ee773dca993a5b59f0 |
refs/heads/master | <repo_name>DanielCumino/DanielCumino.github.io<file_sep>/javascripts/main.js
$(document).ready(function(evt){
// $("h1.title").arctext({radius: 2});
// $(".profile h1.title").arctext({radius: 100, dir: -1});
// $(".profile h1.subtitle").arctext({radius: 100, dir: -1});
// $("body").stop(true).animate({
// scrollTop: $("#skills").offset().top-50
// }, 500, function(){});
$(window).on('scroll.progress-bar', function(){
if ( ($(this).scrollTop() + $(this).height()) >= ($('.progress-bar').parent().parent().position().top+$('.progress-bar').parent().parent().offset().top+$('.progress-bar').parent().parent().outerHeight(true)) ) {
$(".progress-bar").each(function(){
var newWidth = $(this).data('percentage');
$(this).stop(true).animate({width: newWidth+'%'});
});
$(window).off("scroll.progress-bar");
}
});
$(".profile .flip").flip({
trigger: 'manual',
axis: 'y',
speed: '800',
reverse: true
});
var isFlipped = true;
var intervalID = setInterval(function(){
if(isFlipped){
isFlipped = false;
$('.flip').flip(false);
}
else{
isFlipped = true;
$('.flip').flip(true);
}
}, 5000);
// clearInterval(intervalID);
// $(".container .text ul li").find(".exp_text").slideDown();
$(".container .text ul li").click(function(){
var element = $(this).find(".exp_text");
var details = $(this).find(".details");
if(element.css("display") == 'none'){
element.slideDown(100);
details.html("details -");
$("body").stop(true).animate({
scrollTop: $(this).offset().top-50
}, 1000);
}
else{
element.slideUp(100);
details.html("details +");
}
});
var dt = new Date();
// var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
var greeting = '';
if((dt.getHours() >= 0 && dt.getHours() < 5)||(dt.getHours() >= 18 && dt.getHours() < 24)){
greeting = 'Good evening!';
}
else if(dt.getHours() >= 5 && dt.getHours() < 12){
greeting = 'Good morning!';
}
else if(dt.getHours() >= 12 && dt.getHours() < 18){
greeting = 'Good afternoon!';
}
$(function(){
$("h1.greeting").slideDown(function(){
$(this).typed({
strings: ['Hi!','Hello!<br>'+greeting],
typeSpeed: 50,
backSpeed: 50,
showCursor: false,
startDelay: 100,
callback: function() {
$("h3.bubble-speech.bubble-left.ballon").slideDown();
$("h3.bubble-speech.bubble-left.ballon").typed({
strings: ["My name is <span><NAME></span> and this is my <span>Résumé</span>.<br>Checkout! 😊"],
typeSpeed: 25,
showCursor: false,
startDelay: 500
});
}
});
});
});
}); | 838e10e8e9422049b47f503bb397d0f4552db28d | [
"JavaScript"
] | 1 | JavaScript | DanielCumino/DanielCumino.github.io | c7795ef8e004dfca10d415e6de6434c27d42d04d | fcfcf872ef7fb0d051c7c5eae0093a2a8b3a0341 |
refs/heads/master | <file_sep>package com.carstenscholz.robospicemoa;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
/**
* Created by Carsten on 9/10/2015.
*/
public class MoaAdapter extends BaseAdapter {
Context context;
LayoutInflater inflater;
MoaObject moaObject;
public MoaAdapter(Context _context, LayoutInflater _inflater){
context = _context;
inflater = _inflater;
moaObject = new MoaObject();
}
@Override
public int getCount() {
//Only one object is returned by this API
return 1;
}
@Override
public Object getItem(int position) {
return moaObject;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
// check if the view already exists
// if so, no need to inflate and findViewById again!
if (convertView == null) {
// Inflate the custom row layout from your XML.
convertView = inflater.inflate(R.layout.list_row, null);
// create a new "Holder" with subviews
holder = new ViewHolder();
holder.nameTextView = (TextView) convertView.findViewById(R.id.param_name);
holder.valueTextView = (TextView) convertView.findViewById(R.id.param_value);
// hang onto this holder for future recyclage
convertView.setTag(holder);
} else {
// skip all the expensive inflation/findViewById
// and just get the holder you already made
holder = (ViewHolder) convertView.getTag();
}
holder.nameTextView.setText(moaObject.getParamName());
holder.valueTextView.setText(moaObject.getParamValue());
return convertView;
}
public void updateData(MoaObject _moaObject) {
// update the adapter's dataset
moaObject = _moaObject;
//Refreshes the list
notifyDataSetChanged();
}
// this is used so you only ever have to do
// inflation and finding by ID once ever per View
private static class ViewHolder {
public TextView nameTextView;
public TextView valueTextView;
}
}
<file_sep>package com.carstenscholz.robospicemoa;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.json.jackson.JacksonFactory;
import com.octo.android.robospice.request.googlehttpclient.GoogleHttpClientSpiceRequest;
/**
* Created by Carsten on 9/10/2015.
*/
public class MoaRequest extends GoogleHttpClientSpiceRequest<MoaObject>{
private String baseUrl = "http://testing.moacreative.com/job_interview/event.php";
public MoaRequest() {
super(MoaObject.class);
}
@Override
public MoaObject loadDataFromNetwork() throws Exception {
//Using the Get Method
HttpRequest request = getHttpRequestFactory().buildGetRequest(new GenericUrl(baseUrl));
//Using the Post Method
/*MoaObject moa = new MoaObject();
JsonHttpContent content = new JsonHttpContent(new JacksonFactory(),moa);
HttpRequest request = getHttpRequestFactory().buildPostRequest(new GenericUrl(baseUrl),content);*/
//Setting headers
HttpHeaders headers = new HttpHeaders();
headers.setUserAgent("MyTestClient : X-Signiture=1Uhi8g9A91");
headers.set("X-Key", "<KEY>");
headers.setContentType("application/json");
//Adding Headers to the HTTP Request
request.setHeaders(headers);
request.setParser(new JacksonFactory().createJsonObjectParser());
return request.execute().parseAs(getResultType());
}
}
<file_sep>package com.carstenscholz.robospicemoa;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.octo.android.robospice.persistence.DurationInMillis;
import com.octo.android.robospice.persistence.exception.SpiceException;
import com.octo.android.robospice.request.listener.RequestListener;
/**
* Created by Carsten on 9/10/2015.
*/
public class MoaActivity extends BaseMoaActivity implements AdapterView.OnItemClickListener {
private MoaRequest moaRequest;
ListView listView;
MoaAdapter moaAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Tell the activity which XML layout is right
setContentView(R.layout.main);
// Setup a RoboSpice Request where the object you expect to receive is a MoaObject
moaRequest = new MoaRequest();
}
@Override
protected void onStart(){
super.onStart();
//Get the RoboSpice Manager and store the request result for one minute in the Cache
//Return the request results to the Listener; MoaRequestListener
getSpiceManager().execute(moaRequest, "json", DurationInMillis.ONE_MINUTE, new MoaRequestListener());
//ListView to display the data
listView = (ListView) findViewById(R.id.listView);
listView.setOnItemClickListener(this);
//Set the adapter which directly handles the data for the listview
moaAdapter = new MoaAdapter(this, getLayoutInflater());
listView.setAdapter(moaAdapter);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Now that the user has chosen a MoaObject Object, get it's data.
MoaObject moaObject = (MoaObject) moaAdapter.getItem(position);
// User has clicked on the list item now grab the data for the item
String method = moaObject.getMethod();
String error = moaObject.getError();
String paramName = moaObject.getParamName();
String paramValue = moaObject.getParamValue();
// create an Intent to take you over to a new DetailActivity
Intent detailIntent = new Intent(this, MoaDetailActivity.class);
// pack away the data about the Moa Object
// into your intent before you start the activity
detailIntent.putExtra("error",error);
detailIntent.putExtra("method",method);
detailIntent.putExtra("paramName",paramName);
detailIntent.putExtra("paramValue",paramValue);
// start the next Activity using your prepared Intent
startActivity(detailIntent);
}
public final class MoaRequestListener implements RequestListener<MoaObject>{
@Override
public void onRequestFailure( SpiceException spiceException ){
// Display a "Toast" message
// to announce the failure
Toast.makeText( MoaActivity.this,"failure", Toast.LENGTH_SHORT).show();
}
@Override
public void onRequestSuccess(final MoaObject result) {
// Display a "Toast" message
// to announce your success
Toast.makeText( MoaActivity.this,"success", Toast.LENGTH_SHORT).show();
// update the data in custom method moaAdapter
moaAdapter.updateData(result);
}
}
}
| 08104f207330136114965d6801361f74f2261e5f | [
"Java"
] | 3 | Java | DrBiologicals/RoboSpice-Example-android | ead264929b30bda9be73d8f59faa39d62ea57df1 | f36ff5f9dbbfa987690730b0f3e9cd660164babf |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.