branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<repo_name>yuvraj-coditas/login<file_sep>/src/main/webapp/WEB-INF/resources/data.properties
user.pincode=411213
user.street=User Street<file_sep>/src/main/webapp/WEB-INF/classes/labels_zh_CN.properties
test.label=Hello World Chinese<file_sep>/src/main/webapp/WEB-INF/classes/labels_en_US.properties
test.label=Hello World English<file_sep>/src/main/java/com/dao/MainDao.java
package com.dao;
import com.beans.AbstractDao;
import com.beans.UserBean;
public class MainDao extends AbstractDao{
public void insertUser(final UserBean bean)
{
StringBuilder sb= new StringBuilder()
.append("insert into user values (?, ?)");
getJdbcTemplate().update(sb.toString(), new Object[] {bean.getName(),"12345678"});
}
}
<file_sep>/src/main/webapp/WEB-INF/classes/labels.properties
test.label=Hello World Default<file_sep>/src/main/java/com/beans/UserBean.java
package com.beans;
public class UserBean {
private Address address;
private String _strName;
private int _contactNo;
//private String _strAddress;
UserBean(){
System.out.println("In Constructor");
}
public void init()
{
System.out.println("In Init");
}
public String getName() {
return _strName;
}
public void setName(String name) {
this._strName = name;
}
public int getContactNo() {
return _contactNo;
}
public void setContactNo(int contactNo) {
this._contactNo = contactNo;
}
/*public String getAddress() {
return _strAddress;
}
public void setAddress(String address) {
this._strAddress = address;
}*/
public Address getAddress() {
return address;
}
public void setAddress(Address _strAddress) {
this.address = _strAddress;
}
}
<file_sep>/src/main/java/com/beans/Address.java
package com.beans;
public class Address {
private String _strPinCode;
private String _strStreet;
public String getPinCode() {
return _strPinCode;
}
public void setPinCode(String pinCode) {
this._strPinCode = pinCode;
}
public String getStreet() {
return _strStreet;
}
public void setStreet(String street) {
this._strStreet = street;
}
}
|
dae66a7b62c98fbefe8481d8b851693af4af3b7d
|
[
"Java",
"INI"
] | 7 |
INI
|
yuvraj-coditas/login
|
f72b1cfc018f04997f51619d934128454b9712f7
|
5288f4f8dc138b1182f2399bc5bf49033f83de29
|
refs/heads/main
|
<file_sep>const express = require('express')
const http = require('http')
const path = require('path')
const socketio = require('socket.io')
const {generateMessage , generateLocationMessage} = require('./utils/messages.js')
const {addUser ,removeUser , getUser , getUsersInRoom} = require('./utils/users')
const app = express()
const server = http.createServer(app)
const io = socketio(server)
const publicPath = path.join(__dirname , '../public')
const port = process.env.PORT || 3000
app.use(express.static(publicPath))
io.on('connection' , (socket)=>{
console.log('New connection established')
socket.on('join' , ({username , roomname},callback)=>{
const {error , user} = addUser({id:socket.id,username,roomname})
if(error){
callback(error)
}
socket.join(roomname)
socket.emit('message' , generateMessage(`Welcome to chat app ${user.username}`))
socket.broadcast.to(user.roomname).emit('message' , generateMessage(`${user.username} has connected`))
io.to(user.roomname).emit('RoomData' , {
room : user.roomname,
users : getUsersInRoom(user.roomname)
})
})
socket.on('sendMessage' , (message ,callback)=>{
const user = getUser(socket.id)
io.to(user.roomname).emit('message' , generateMessage(user.username,message))
callback('Delivered!')
})
socket.on('sendLocation',(location , callback)=>{
const user = getUser(socket.id)
io.to(user.roomname).emit('locationMessage', generateLocationMessage(user.username,location.latitude , location.longitude))
callback('Location shared')
})
socket.on('disconnect' , ()=>{
const user = removeUser(socket.id)
console.log(user)
if(user){
io.to(user.roomname).emit('message' , generateMessage(`${user.username} has left`))
io.to(user.roomname).emit('RoomData' , {
room : user.roomname,
users : getUsersInRoom(user.roomname)
})
}
})
})
server.listen(port , ()=>{
console.log('Chat app')
} )<file_sep>const socket = io()
const form = document.getElementById("message-form")
const formButton = form.querySelector("button")
const formInput = document.querySelector("input")
const locationButton = document.getElementById('location-button')
const messages = document.querySelector('#messages')
//templates
const messageTemplate = document.querySelector('#message-template').innerHTML
const locationTemplate = document.querySelector('#location-template').innerHTML
const sidebarTemplate = document.querySelector('#sidebar-template').innerHTML
const options = location.search.split("=");
const username = options[1].split("&")[0];
const roomname = options[2];
const autoscroll = ()=>{
const lastMessage = messages.lastElementChild
const lastMessageStyles = getComputedStyle(lastMessage)
const margin = parseInt(lastMessageStyles.marginBottom)
const height = margin + lastMessage.offsetHeight
const visibleHeight = messages.offsetHeight
const containerHeight = messages.scrollHeight
const scrollOffset = messages.scrollTop + visibleHeight
if(containerHeight - height <= scrollOffset){
messages.scrollTop = messages.scrollHeight
}
}
socket.on('message' , (message)=>{
console.log(message)
const html = Mustache.render(messageTemplate , {
username : message.username,
message : message.text,
createdAt : moment(message.createdAt).format('HH:mm')
})
messages.insertAdjacentHTML("beforeend" ,html)
autoscroll()
})
socket.on('locationMessage' , (url)=>{
console.log(url)
const locationURL = Mustache.render(locationTemplate , {
username : url.username,
location : url.url ,
createdAt : moment(url.createdAt).format('HH:mm')
})
messages.insertAdjacentHTML('beforeend',locationURL)
autoscroll()
})
socket.on('RoomData' , (data)=>{
const list = Mustache.render(sidebarTemplate ,{
room : data.room ,
users : data.users
} )
document.getElementById('sidebar').innerHTML = list
})
form.addEventListener('submit' , (e)=>{
e.preventDefault()
formButton.setAttribute('disabled' , 'disabled')
const message = formInput.value
socket.emit('sendMessage' , message , (msg)=>{
formButton.removeAttribute('disabled')
formInput.value = ''
formInput.focus()
console.log("The message was delivered" , msg)
})
})
locationButton.addEventListener('click' , ()=>{
if (!navigator.geolocation){
return alert('Geolocation is not supported by your browser')
}
locationButton.setAttribute('disbled' , 'disabled')
navigator.geolocation.getCurrentPosition((position)=>{
const location = {
latitude : position.coords.latitude,
longitude : position.coords.longitude
}
socket.emit('sendLocation' , location , (msg)=>{
locationButton.removeAttribute('disabled')
console.log(msg)
})
})
})
socket.emit('join' , {username,roomname} , (error)=>{
if(error)
{ window.alert(error)
location.href = '/'
}
})
|
19319aa262d6aeb61c5f60df1e3899185408ac45
|
[
"JavaScript"
] | 2 |
JavaScript
|
Drigger91/Chat-app
|
511d90e005c0a47213f9d5fffffd900441dbb28b
|
d09fb4337624ab0d359c272508fcec3629231c28
|
refs/heads/main
|
<file_sep>var sum = function (acc, x) { return acc + x; };
var updateTotProductCosts = function (ele) {
var quantity = parseFloat($(ele).children('.ucost').text().slice(1));
var unitCost = parseFloat($(ele).find('.qty input').val());
var totCost = quantity * unitCost;
$(ele).children('.tcost').html("$" + totCost.toFixed(2));
return totCost;
}
var updateCostsAndCartTotal = function () {
var productCosts = [];
$('tbody tr').each(function (index, element) {
var prodCost = updateTotProductCosts(element);
productCosts.push(prodCost);
});
var cartCost = productCosts.reduce(sum);
$('#cartCost').html("$" + cartCost.toFixed(2));
}
$(document).ready(function () {
updateCostsAndCartTotal();
$(document).on('click', '.btn.remove', function (event) {
$(this).closest('tr').remove();
updateCostsAndCartTotal();
});
var timeout;
$(document).on('input', 'tr input', function () {
clearTimeout(timeout);
timeout = setTimeout(function () {
updateCostsAndCartTotal();
}, 600);
});
$('#addProduct').on('submit', function (event) {
event.preventDefault();
var name = $(this).children('[name=name]').val();
var cost = $(this).children('[name=ucost]').val();
$('tbody').append(
'<tr>' +
'<td class="name">' + name + '</td>' +
'<td class="ucost">$' + Number(cost).toFixed(2) + '</td>' +
'<td class="qty"><input type="number" min="0" value="0" /></td>' +
'<td class="tcost">$--.--</th>' +
'<td><button class="btn btn-sm remove">remove</button></td>' +
'</tr>');
updateCostsAndCartTotal();
$(this).children('[name=name]').val('');
$(this).children('[name=ucost]').val('');
});
});
|
711032d0df45941b00660be4fb4544b5fd974c33
|
[
"JavaScript"
] | 1 |
JavaScript
|
DrDraenor/SimpleShoppingCart
|
d3c52d96bc77f731d690238db5488016a696c7f3
|
5396b5be1861247994d6bfb9cfc00822b375eb8c
|
refs/heads/master
|
<repo_name>hrs2203/news_backend<file_sep>/util/dataTypeCheck.js
class TypeValidator{
isString(input_var){
return (typeof(input_var) == String);
}
isInteger(input_var){
return (typeof(input_var) == Number);
}
isBoolean(input_var){
return (typeof(input_var) == Boolean);
}
isMap(input_var){
return (typeof(input_var) == Map);
}
}
module.exports = TypeValidator;<file_sep>/database/models/news.js
const mongoose = require('mongoose');
const NewsSchema = new mongoose.Schema({
news_title: {
type: String,
required: true
},
news_category_id: {
type: String,
required: true
},
news_author: {
type: String,
required: true
},
news_description: {
type: String,
required: true
},
news_url: {
type: String,
required: true
},
news_urlToImage: {
type: String,
required: true
},
news_publishedAt: {
type: String,
required: true
},
news_content: {
type: String,
required: true
},
});
module.exports = mongoose.model("News", NewsSchema);<file_sep>/database/db/new_news_module.js
const news_key = require("../../config/enc_data.json")['news_api_key']
const NewsAPI = require('newsapi');
const newsapi = new NewsAPI(news_key);
class CollectNewNews {
/**
* Collect Data about that topic and save to db.
*
* @param {String} topic
* @param {String} startData
* @param {String} endDate
* @param {String} destincation
*/
static getdata(topic, startData, endDate) {
return newsapi.v2.everything({
q: topic,
from: startData,
to: endDate,
language: 'en',
sortBy: 'relevancy',
page: 3
}).then(resp => {
return resp["articles"].map(unit => {
return {
author: unit["author"],
title: unit["title"],
description: unit["description"],
url: unit["url"],
urlToImage: unit["urlToImage"],
publishedAt: unit["publishedAt"],
content: unit["content"],
}
})
})
}
}
module.exports = CollectNewNews;
<file_sep>/app.js
const express = require('express');
const mongoose = require("mongoose");
const serverPort = require("./config/staticVals.json")
// ============ Router Connection ================
const server_router = require("./router/server_router");
const app = express();
var cors = require('cors');
app.use(cors({ origin: true, credentials: true }));
app.use("/api", server_router);
app.use("/static", express.static('./static'));
app.use("*", (req, res) => {
return res.json({
"status": 404,
"message": "No page found"
})
})
// ============ DB Connection ==============
mongoose.connect(
serverPort["db_port"], {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
},
() => console.log('Connection to db: OK :)...........')
)
// ============== Server Connection ============
app.listen(
serverPort['server_port'],
() => console.log(`server running at port ${serverPort["server_port"]}`)
)<file_sep>/router/user.js
const router = require('express').Router();
const parseJsonInput = require("body-parser").json();
const UserDB = require("../database/db/user_module.js");
const UserDetailDB = require("../database/db/user_detail_module.js");
/**
* @example
* {
* "email": "<EMAIL>",
* "password": "<PASSWORD>"
* }
*/
router.post("/auth/login", parseJsonInput,
(req, res, next) => {
return UserDB.validateUser(req.body.email, req.body.password)
.then(validationResp => {
return res.json({
"statusCode": 200,
"data": validationResp
});
}).catch(err => {
return res.json({
"statusCode": 400,
"data": null
});
});
});
/**
* @example
* {
* "username": "username",
* "email": "<EMAIL>",
* "password": "<PASSWORD>"
* }
*/
router.post("/auth/registration", parseJsonInput, (req, res, next) => {
return UserDB.createNewUser(
req.body.username, req.body.email, req.body.password
).then(creationResp => {
return UserDetailDB.createNewUserDetail(creationResp._id)
.then(detObj => {
return res.json({
"statusCode": 200,
"data": {
"user": creationResp,
"user_detail": detObj
}
});
})
.catch(err => {
console.log(err);
return res.json({
"statusCode": 400,
"data": err
});
});
}).catch(err => {
console.log(err);
return res.json({
"statusCode": 400,
"data": err
});
})
});
/**
* {{url}}/api/user?userEmail=<EMAIL>
*/
router.get("/", (req, res, next) => {
// const userEmail = req.query.email;
return UserDB.checkUserPresence(req.query.userEmail)
.then(userData => {
if (userData === false) {
return res.json({
"statusCode": 400,
"data": null
});
}
return UserDetailDB.checkUserDetailPresence(userData._id)
.then(detailObj => {
return res.json({
"statusCode": 200,
"data": {
"user": userData,
"user_detail": detailObj
}
});
})
})
.catch(err => {
return res.json({
"statusCode": 400,
"data": null
});
})
});
/**
* Update User history after reading a new news
* @example
* input format:
* {
* "user_email": String
* "news_token": {
* "news_title": String,
* "news_link": String,
* "news_time": String,
* "news_category": String
* }
* }
* }
*/
router.post("/update", parseJsonInput, (req, res, next) => {
return UserDB.checkUserPresence(req.body.user_email)
.then(userObject => {
if (userObject === false) {
return res.json({
"statusCode": 200,
"data": null
})
}
return UserDetailDB.updateUserDetail(userObject._id, req.body.news_token)
.then(userUpdateDetail => {
return res.json({
"statusCode": 200,
"updateStatus": true
});
})
.catch(err => {
return res.json({
"statusCode": 400,
"data": false
});
})
})
.catch(err => {
return res.json({
"statusCode": 400,
"data": false
});
})
})
/**
* clean User history
* @example
* input format:
* {
* "user_email": String
* }
* }
*/
router.post("/clean_history", parseJsonInput, (req, res, next) => {
return UserDB.checkUserPresence(req.body.user_email)
.then(userObject => {
if (userObject === false) {
return res.json({
"statusCode": 200,
"data": null
})
}
return UserDetailDB.cleanUserHistory(userObject._id)
.then(userUpdateDetail => {
return res.json({
"statusCode": 200,
"updateStatus": true
});
})
.catch(err => {
return res.json({
"statusCode": 400,
"data": false
});
})
})
.catch(err => {
return res.json({
"statusCode": 400,
"data": false
});
})
})
module.exports = router;<file_sep>/database/db/news_search_module.js
const News = require("../models/news.js");
class NewsSearchDB {
/**
* entire search space
* @returns List[News]
*/
static getEntireSearch() {
return News.find()
.select("news_title news_url news_publishedAt news_category_id news_author")
.then(data => data).catch(err => [])
}
/**
* filter news from news_module itself
*
* @param {String} news_title
* @returns List[News]
*/
static searchNews(news_title) { }
}
module.exports = NewsSearchDB;<file_sep>/database/models/news_search.js
const mongoose = require('mongoose');
const NewsSearchSchema = new mongoose.Schema({
news_title: {
type: String,
required: true
},
news_link: {
type: String,
required: true
},
news_time: {
type: String,
required: true
},
news_category: {
type: String,
required: true
}
});
module.exports = mongoose.model("NewsSearch", NewsSearchSchema);<file_sep>/database/db/news_category_module.js
const NewsCategory = require("../models/news_category.js");
/** Static Function Class For News Category Model */
class NewsCategoryDB {
/**
* @returns List[NewsCategoryObject]
*/
static getAllNewsCategory() {
return NewsCategory.find().select("news_category_name")
.then(data => data).catch(err => []);
}
/**
* @param {String} nc_name
* @returns new_category instance || false || null
*/
static checkNewsCategoryPresence(nc_name) {
return NewsCategory.findOne({ "news_category_name": nc_name })
.then(ncData => (ncData === null) ? false : ncData)
.catch(err => null)
}
/**
* @param {String} nc_id
* @returns new_category instance || false || null
*/
static checkNewsCategoryPresenceById(nc_id) {
return NewsCategory.findOne({ "_id": nc_id })
.then(ncData => (ncData === null) ? false : ncData)
.catch(err => null)
}
/**
* @param {String} nc_name
* @returns new news_category instance with name = nc_name || existing news category.
*/
static createNewNewsCategory(nc_name) {
return NewsCategoryDB.checkNewsCategoryPresence(nc_name)
.then(ncObj => {
if (ncObj === false) {
const newNewsCategoryObj = new NewsCategory({
"news_category_name": nc_name
});
return newNewsCategoryObj.save()
.then(newObj => newObj).catch(err => err);
}
return ncObj;
}).catch(err => null)
}
}
module.exports = NewsCategoryDB;<file_sep>/README.md
# News Backend
## About
<NAME> is a one stop news website serving its customers
digestable short news personalized to there taste.
As a backend service build on MERN Stack ( NodeJs, ExpressJs, MongoDB ),
this module provides the server side support for the react js app.
The Backend handels:
1. Routing different url using express js
2. Handelling route methods and api data type, parsin using express js
3. Database layer schema creation using mongoose package
4. databse data collection layer using mongoose
5. User verfication and data enctryption using native nodejs
6. Collection of unseen queries and data collection on them using third party API's such as
1. News API
2. New Youk time API
## API Served
<table>
<tr>
<th>No</th>
<th>Services Provided</th>
<th>API</th>
</tr>
<tr>
<td>1.</td>
<td>User Login</td>
<td>{{url}}/api/user/auth/login</td>
</tr>
<tr>
<td>2.</td>
<td>User Registration</td>
<td>{{url}}/api/user/auth/registration</td>
</tr>
<tr>
<td>3.</td>
<td>Update User History</td>
<td>{{url}}/api/user/update</td>
</tr>
<tr>
<td>4.</td>
<td>Clean User History</td>
<td>{{url}}/api/user/clean_history</td>
</tr>
<tr>
<td>5.</td>
<td>Fetch News</td>
<td>{{url}}/api/news?nid=news_id</td>
</tr>
<tr>
<td>6.</td>
<td>Fetch News by News_Category</td>
<td>{{url}}/api/news/category?ncname=gov</td>
</tr>
<tr>
<td>7.</td>
<td>Collect Unseen queries</td>
<td>{{url}}/api/search/unseenquery?q=stock market</td>
</tr>
<tr>
<td>8.</td>
<td>serve data on unseen queries</td>
<td>{{url}}/api/search/get?q=new news</td>
</tr>
</table>
<file_sep>/database/models/user_details.js
const mongoose = require('mongoose');
const UserDetailSchema = new mongoose.Schema({
user_id: {
type: String,
required: true
},
user_visit_history: {
type: [],
default: []
}
});
module.exports = mongoose.model("UserDetail", UserDetailSchema);<file_sep>/router/search.js
const router = require('express').Router();
const parseJsonInput = require("body-parser").json();
const UnseenQueryDB = require("../database/db/query_module");
const NewsSearchDB = require('../database/db/news_search_module.js');
const NewsCategory = require("../database/models/news_category.js");
/**
* this module deals with
* 1. Global Searches.
* 2. Unseen queries.
*/
/**
* get all search result possible
*/
router.get("/all", (req, res, next) => {
return NewsSearchDB.getEntireSearch()
.then(seq => {
return NewsCategory.find().then(database => {
var lst = [];
var data = {};
for (let index = 0; index < database.length; index++) {
data[database[index]["_id"]] = database[index]["news_category_name"];
}
for (var i = 0; i < seq.length; i++) {
lst.push({
"_id": seq[i]["_id"],
"news_title": seq[i]["news_title"],
"news_category": data[seq[i]["news_category_id"]] || "othe",
"news_url": seq[i]["news_url"],
"news_publishedAt": seq[i]["news_publishedAt"],
"news_author": seq[i]["news_author"]
})
}
return res.json({
"status": 200,
"data": lst
})
}).catch(err => {
return res.json({
"status": 400,
"data": null
})
})
})
.catch(err => {
return res.json({
"status": 400,
"data": null
})
})
})
/**
* {{url}}/api/search/unseenquery?q=delhi covid
*/
router.get("/get", (req, res, next) => {
return UnseenQueryDB.getNewQuery(req.query.q)
.then(data => {
return res.json({
"status": 200,
"data": data
})
})
.catch(err => {
return res.json({
"status": 400,
"data": false
})
})
})
/**
* {{url}}/api/search/unseenquery?q=delhi covid
*/
router.get("/unseenquery", (req, res, next) => {
return UnseenQueryDB.addNewQuery(req.query.q)
.then(data => {
return res.json({
"status": 200,
"data": data
})
})
.catch(err => {
return res.json({
"status": 400,
"data": false
})
})
})
/**
* {{url}}/api/search/unseenquery/all
*/
router.get("/unseenquery/all", (req, res, next) => {
return UnseenQueryDB.getAllQuery()
.then(data => {
return res.json({
"status": 200,
"data": data
})
})
.catch(err => {
return res.json({
"status": 400,
"data": false
})
})
})
router.get("/unseenquery/fill_db", (req, res, next) => {
return UnseenQueryDB.fillDatabase()
.then(data => {
return res.json({
"status": 200,
"data": data
})
})
.catch(err => {
return res.json({
"status": 400,
"data": null
})
})
})
module.exports = router;<file_sep>/router/allUrl.js
const router = require("express").Router();
router.get("/all", (req, res) => {
return res.json({
"urlList": {
"/user?userEmail=userEmail": "get user by email",
"/news?nid=newId": "get news by id",
"/news/bycategory?category=categoryname": "get news by category",
"/news/category?ncid=new_cat_id": "get news by its",
"/news/category/all": "get all news category"
}
})
})
module.exports = router;
|
14d3014302b6cd61161b912dc545c5e8094fe924
|
[
"JavaScript",
"Markdown"
] | 12 |
JavaScript
|
hrs2203/news_backend
|
62781e5fdd5306b46465aa67cf6895033e0e8bef
|
3f843e95fa5d15d3fa30cec87f2dd8688502d4a4
|
refs/heads/master
|
<repo_name>ERICKLEO-ING/DESA<file_sep>/ERICK/Infomatica/Restaurante/Model/ProductoModel.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Infomatica.Restaurante.Model
{
public class ProductoModel
{
string Codigo { get; set; }
string Descripcion { get; set; }
string DescripcionResumido { get; set; }
}
}
<file_sep>/ERICK/Infomatica/Util/Sql.cs
using Infomatica.Restaurante.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
namespace Infomatica.Util
{
class Sql
{
public static IDataReader ConsultaQuery(string _SqlQuery)
{
try
{
ConnectionState originalState = VG.CnRest.State;
if (originalState != ConnectionState.Open)
VG.CnRest.Open();
IDbCommand command = VG.CnRest.CreateCommand();
command.CommandText = _SqlQuery;
IDataReader Resp = command.ExecuteReader();
command.Dispose();
return Resp;
}
catch (Exception)
{
throw;
}
}
}
}
<file_sep>/ERICK/Infomatica/Restaurante/Controller/GrupoController.cs
namespace Infomatica.Restaurante.Controller
{
using System;
using Infomatica.Restaurante.Model;
using Infomatica.Util;
public class GrupoController
{
public void GetGrupo()
{
try
{
VG.Grupo = Util.DataReaderMapToList<GrupoModel>(Sql.ConsultaQuery("select * from vGrupo "));
}
catch (Exception)
{
throw;
}
}
}
}
<file_sep>/ERICK/KDS.Rest/Views/PrincipalView.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace KDS.Rest.Views
{
public partial class PrincipalView : Form
{
public PrincipalView()
{
InitializeComponent();
}
}
}
<file_sep>/ERICK/Infomatica/Util/CorreoUtil.cs
namespace Infomatica.Util
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
public class CorreoUtil
{
private readonly SmtpClient Cliente = new SmtpClient("smtp.gmail.com", 587)
{
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("<EMAIL>", "2810921@")
};
private MailMessage email;
/// <summary>
/// Envio de correo especificando los valores de envio
/// </summary>
public void EnviarCorreo(string destinatario, string asunto, string mensaje, bool esHtlm = false)
{
email = new MailMessage("<EMAIL>", destinatario, asunto, mensaje)
{
IsBodyHtml = esHtlm
};
Cliente.Send(email);
}
/// <summary>
/// Envio de correo de una clase MailMessage
/// </summary>
public void EnviarCorreo(MailMessage message)
{
Cliente.Send(message);
}
/// <summary>
/// Envio de correo Asincrono de una clase MailMessage
/// </summary>
public async Task EnviarCorreoAsync(MailMessage message) //Ola muundo
{
await Cliente.SendMailAsync(message);
}
}
}
<file_sep>/ERICK/Infomatica/Restaurante/Controller/SubGrupoController.cs
namespace Infomatica.Restaurante.Controller
{
using System;
using Infomatica.Restaurante.Model;
using Infomatica.Util;
public class SubGrupoController
{
public void GetSubGrupo()
{
try
{
VG.SubGrupo = Util.DataReaderMapToList<SubGrupoModel>(Sql.ConsultaQuery("select * from vSubGrupo "));
}
catch (Exception)
{
throw;
}
}
}
}
<file_sep>/ERICK/Infomatica/Util/ImpresionUtil.cs
namespace Infomatica.Util
{
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Printing;
public class ImpresionUtil
{
private Font printFont;
private StreamReader streamToPrint;
private String textImp;
/// <summary>
/// Captura la linea de impresion
/// </summary>
public String Print
{
get { return textImp; }
set { textImp += value + Environment.NewLine; }
}
/// <summary>
/// El evento PrintPage se genera para cada página que se va a imprimir.
/// </summary>
private void Pd_PrintPage(object sender, PrintPageEventArgs ev)
{
int count = 0;
float leftMargin = 10;//ev.MarginBounds.Left;
float topMargin = 10;//ev.MarginBounds.Top;
String line = null;
// Calculate the number of lines per page.
float linesPerPage = ev.MarginBounds.Height /
printFont.GetHeight(ev.Graphics);
// Iterate over the file, printing each line.
while (count < linesPerPage &&
((line = streamToPrint.ReadLine()) != null))
{
float yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
ev.Graphics.DrawString(line, printFont, Brushes.Black,
leftMargin, yPos, new StringFormat());
count++;
}
// If more lines exist, print another page.
if (line != null)
ev.HasMorePages = true;
else
ev.HasMorePages = false;
}
/// <summary>
/// Imprime texto en impresoras configuradas
/// </summary>
public void Imprimir(string Impresora)
{
try
{
streamToPrint = new StreamReader(GenerateStreamFromString(Print));
try
{
printFont = new Font("Courier New", 10);
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(Pd_PrintPage);
pd.PrinterSettings.PrinterName = "FinePrint";
pd.Print();
}
finally
{
streamToPrint.Close();
}
}
catch (Exception)
{
//MessageBox.Show(ex.Message);
}
}
/// <summary>
/// Convierte de un string a un Stream
/// </summary>
static Stream GenerateStreamFromString(string s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
}
}
<file_sep>/ERICK/Infomatica/Util/Util.cs
namespace Infomatica.Util
{
using Infomatica.Restaurante.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
class Util
{
public static List<T> DataReaderMapToList<T>(IDataReader dr)
{
List<T> list = new List<T>();
T obj = default(T);
while (dr.Read())
{
obj = Activator.CreateInstance<T>();
foreach (PropertyInfo prop in obj.GetType().GetProperties())
{
if (!object.Equals(dr[prop.Name], DBNull.Value))
{
prop.SetValue(obj, dr[prop.Name], null);
}
}
list.Add(obj);
}
dr.Close();
return list;
}
public string LeerIni(string Ruta, string Principal, string _Clave, string _Default)
{
string IniData = "";
try
{
//primero que nada leo el archivo a ver si que datos tiene
StreamReader streamReader = new StreamReader(Ruta);
IniData = "";
string[] VAL = streamReader.ReadToEnd().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
streamReader.Close();
bool EncontroPrincipal = false;
bool FinalizaBusqueda = false;
for (int i = 0; i < VAL.Count(); i++)
{
if (!FinalizaBusqueda)
{
if (!EncontroPrincipal)
{
if (VAL[i].ToUpper().Contains("[" + Principal.ToUpper() + "]")) { EncontroPrincipal = true; }
}
else
{
if (VAL[i].Contains(_Clave))
{
IniData = VAL[i].Replace(_Clave, "").Replace("=", "").Trim();
break;
}
if (VAL[i].Contains("[")) { FinalizaBusqueda = true; }
}
}
else
{
break;
}
}
if (IniData == "")
{
IniData = _Default;
}
return IniData;
}
catch
{
return _Default;
}
}
}
}
<file_sep>/EASYFACT/EasyFactWebService/Controllers/EasyFact/DocumentoController.cs
namespace EasyFactWebService.Controllers.EasyFact
{
using global::EasyFact.Models;
using global::EasyFact.Controller;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Http;
[BasicAuthorize]
//[Authorize]
public class DocumentoController : ApiController
{
public DocumentoController()
{
}
[HttpPost]
public List<string> Post(DocumentoElectronicoModel DocumentoFE)
{
DocumentoElectronicoController Fact = new DocumentoElectronicoController();
List<string> Respuesta= new List<string>();
try
{
Respuesta = Fact.RecibeDocumentoElectronio(DocumentoFE);
//Respuesta[0]="0";
//Respuesta.Add("Operacion Existosa");
//Respuesta.Add("dahnsjdkasdbjkabdkjasbdjbajdkbajkdbajkdbasjkbdajkbdjbasjkbjkadbjkasd");
return Respuesta;
}
catch (Exception ex)
{
Respuesta.Add("1");
Respuesta.Add(ex.Message);
return Respuesta;
}
}
}
}<file_sep>/EASYFACT/EasyFactWebService/Controllers/EasyFact/BasicAuthorizeAttribute.cs
namespace EasyFactWebService.Controllers.EasyFact
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
public class BasicAuthorizeAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
var headers = actionContext.Request.Headers;
if (headers.Authorization != null && headers.Authorization.Scheme == "Basic")
{
try
{
var userPwd = Encoding.UTF8.GetString(Convert.FromBase64String(headers.Authorization.Parameter));
var user = userPwd.Substring(0, userPwd.IndexOf(":"));
var password = userPwd.Substring(userPwd.IndexOf(":") + 1);
//var erick = Seguridad.DesEncriptar("123456789")
// Validamos user y password (aquí asumimos que siempre son ok)
if (user == "erick" && password == "<PASSWORD>")
{
}
else
{
PutUnauthorizedResult(actionContext, "Invalid Authorization");
}
}
catch (Exception)
{
PutUnauthorizedResult(actionContext, "Invalid Authorization header");
}
}
else
{
// No hay el header Authorization
PutUnauthorizedResult(actionContext, "Auhtorization needed");
}
}
private void PutUnauthorizedResult(HttpActionContext actionContext, string msg)
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
Content = new StringContent(msg)
};
}
}
}<file_sep>/ERICK/Infomatica/Restaurante/Model/VG.cs
namespace Infomatica.Restaurante.Model
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
public class VG
{
public static IDbConnection CnRest { get; set; }
public static List<GrupoModel> Grupo { get; set; }
public static List<SubGrupoModel> SubGrupo { get; set; }
}
}
<file_sep>/ERICK/Infomatica/Restaurante/Model/GrupoModel.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Infomatica.Restaurante.Model
{
public class GrupoModel
{
public string Codigo { get; set; }
public string Descripcion { get; set; }
public int nBoton { get; set; }
}
}
<file_sep>/README.md
# DESA
Desarrollo
|
f6895c0dda225ec90b6d6480df8ff14a087a9962
|
[
"Markdown",
"C#"
] | 13 |
C#
|
ERICKLEO-ING/DESA
|
408ad6aa9dfbcecc8514463e5b8fbc6faa9f98ea
|
2b26e13e78078f461b34a3f1965a89db7fd61359
|
refs/heads/master
|
<repo_name>Adriano-Diogo/primeiro-repositorio<file_sep>/Site-novo/js/page.js
var div_historia = document.getElementById("history");
var historias = ["Soul music ou apenas soul é um gênero musical popular que se originou na comunidade afro-americana dos Estados Unidos nos anos 1950 e no início dos anos 1960. Na década de sessenta o Soul passa a ser a música de protesto dos movimentos em favor dos direitos civis dos negros, tornando-se a black music americana.","N.W.A foi um grupo americano de hip hop de Compton, Califórnia. Ativos de 1987 a 1991, o grupo sofreu controvérsia devido às letras chocantes e explícitas de suas músicas, que muitos viam como misóginas, glorificado as drogas e o crime. O grupo foi posteriormente banido de muitas estações de rádio americanas. Com base em suas próprias experiências de racismo, abuso de autoridade e violência policial, o grupo fez música inerentemente política. Eles eram conhecidos por seu profundo ódio ao sistema policial, o que provocou muita controvérsia ao longo dos anos"]
function aparecer_texto(posisao_historia){
div_historia.innerHTML = `<div class='content'><p>${historias[posisao_historia]}</p></div>`;
}
var div_hip_hop = document.getElementById("box_musica");
var div_nome = document.getElementById("div_nome");
var div_musica = document.getElementById("div_musica");
var div_fotos = document.getElementById("div_fotos");
var musica_hop = [
{
nome:"<NAME>",
foto:"./img/pacMusic.jpg",
audio:"2Pac - Ambitionz Az A Ridah (Legendado).mp3"
},
{
nome:"<NAME>",
foto:"./img/akon2.jpg",
audio:"Akon - Smack That ft. Eminem.mp3"
},
{
nome:"<NAME>",
foto:"./img/snoop2.jpg",
audio:"Snoop Dogg - Thats That Shit feat. <NAME>.mp3"
},
{
nome:"21 Questions",
foto:"./img/cent2.jpg ",
audio:"50 Cent - 21 Questions ft. Nate Dogg.mp3"
},
{
nome:"Mesmerize",
foto:"./img/ja2.jpg",
audio:"mesmerize lyrics ja rule.mp3"
},
{
nome:"My Place",
foto:"./img/nelly2.jpg",
audio:"My Place- Nelly feat. Jaheim.mp3"
},
];
function aparecer_musica(posisao_musica){
div_nome.innerHTML = musica_hop[posisao_musica].nome
div_fotos.style.backgroundImage = `url(${musica_hop[posisao_musica].foto})`
div_musica.src = musica_hop[posisao_musica].audio;
}
|
1904e3e170059e91b2daa91dea8dd561bc8f378e
|
[
"JavaScript"
] | 1 |
JavaScript
|
Adriano-Diogo/primeiro-repositorio
|
ae6a81e8344dfc812d41922db48fc49000d7bdd9
|
8ae168bc326d35a232b9e4fadeb476e5d886c28f
|
refs/heads/master
|
<file_sep>package test;
/**
* Created with IntelliJ IDEA.
* Author: CuiCan
* Date: 2017-9-4
* Time: 10:51
* Description: 发短信测试
*/
public class SmsTest extends BasicTest {
/**
* UserId 东方般若提供的用户名
* Password 东方般若提供的密码
* Mobiles 手机号码(支持多手机号,以英文逗号分隔,
* Get最多不超过1000个手机号;
* Post无限制,建议不超过1万个,手机号越多响应时间越长)
* Content 短信内容
* SenderAddr 扩展尾号(无扩展尾号此参数可为空)V1.3
* ScheduleTime 计划发送开始时间日期格式YYYYMMDDHHMISS V1.6
* 缺省值系统时间
* ExpireTime 发送超期时间日期格式YYYYMMDDHHMISS V1.6
* 缺省值系统时间+1天
* <p>
* 乱码处理说明
* <p>
* 1.发送内容乱码:
* try
* {
* content = URLEncoder.encode("您好","GBK");
* }
* catch(Exception e)
* {
*
* }
* <p>
* 2.接收响应乱码:
* // 定义BufferedReader输入流来读取URL的响应
* in = new BufferedReader(
* new InputStreamReader(conn.getInputStream(),"GBK"));
* 报告匹配说明
* 1.调用方单条消息发送(MsgId)调用SendSMS接口提交成功后,接口返回GatewayId,
* 调用方将MsgId与GatewanyId进行对应,异步调用ReceiveReport接口获取报告,
* 通过报告中返回的GateWayId匹配MsgId,确定消息的发送状态。
* 2.调用方多条消息发送(MsgId1,MsgId2,…MsgIdN)调用SendSMS接口提交成功后,
* 接口返回GatewayId,调用方将MsgId与GatewanyId及手机号码进行对应,异步调用ReceiveReport接口获取报告,
* 通过报告中返回的GateWayId和手机号码匹配MsgId,确定消息的发送状态。
*/
/**
* 乱码处理说明
* <p>
* 1.发送内容乱码:
* try
* {
* content = URLEncoder.encode("您好","GBK");
* }
* catch(Exception e)
* {
*
* }
* <p>
* 2.接收响应乱码:
* // 定义BufferedReader输入流来读取URL的响应
* in = new BufferedReader(
* new InputStreamReader(conn.getInputStream(),"GBK"));
* 报告匹配说明
* 1.调用方单条消息发送(MsgId)调用SendSMS接口提交成功后,接口返回GatewayId,
* 调用方将MsgId与GatewanyId进行对应,异步调用ReceiveReport接口获取报告,
* 通过报告中返回的GateWayId匹配MsgId,确定消息的发送状态。
* 2.调用方多条消息发送(MsgId1,MsgId2,…MsgIdN)调用SendSMS接口提交成功后,
* 接口返回GatewayId,调用方将MsgId与GatewanyId及手机号码进行对应,异步调用ReceiveReport接口获取报告,
* 通过报告中返回的GateWayId和手机号码匹配MsgId,确定消息的发送状态。
*/
/*@Before
public void getHttpTools(){
HttpAPIService httpAPIService = applicationContext.getBean(HttpAPIService.class);
}*/
/*public static void main(String[] args) {
// HttpAPIService httpAPIService = applicationContext.getBean(HttpAPIService.class);
String ip = "192.168.127.12";
String port = "9888";
String userId = "3047";
String Password = "<PASSWORD>";
String mobiles = "18637010312,17612180312";
String content = "尊敬的用户,这是一条测试短信";
String base_url = "http://172.16.31.10:9888/smsservice/SendSMS?UserId=3047&Password=<PASSWORD>&";
String result = "";
try {
content = URLEncoder.encode(content, "GBK");
System.out.println("content = " + content);
String url = base_url + "&Mobiles=" + mobiles + "&Content=" + content;
result = httpAPIService.doGet(url);
System.out.println("url = " + url);
System.out.println("result = " + result);
} catch (IOException e) {
e.printStackTrace();
}
}
*/
}
<file_sep>#----------------------------------------#
#---------QUERY INFOMATION by HR---------#
#----------------------------------------#
##查询条件(可多选 仅姓名支持模糊查询)
# 姓名 证件号 手机号 EMS号 员工ID
##输出字段
#姓名
#身份证号
#手机号
#EMS号
#员工编码
#性别
#年龄
#入职时间
#离职时间
#服务年限
#公司名
#在职状态
#贷款状态
#贷款剩余应还本金
#离职管控方式
##离职管控方式 取值有两种:
#1.暂停办理离职手续,请与互金集团接口人XXX联系,并提醒员工结清贷款,
# 再行办理离职手续可办理离职手续;(适用于有在贷中、已审批未放款、申请中等状态员工贷的员工)
#2.可办理离职手续;(适用于除第1点之外情况的员工)
##离职管控取值判断
#根据进件台账的“所属流程阶段”和贷款台账的“贷款状态”两个字段取值判断,具体如下:
#1.若贷款申请未放款,则在进件台账里,根据“所属流程阶段”取值判断离职管控方式
#---------------------------
#所属流程阶段 | 离职管控方式
#---------------------------
#已取消申请 | 2.可办理离职手续
#已复核阶段 | 1.暂停办理离职手续……
#电话核查 | 1.暂停办理离职手续……
#复核阶段 | 1.暂停办理离职手续……
#人工复核 | 1.暂停办理离职手续……
#人工初审 | 1.暂停办理离职手续……
#已批准 | 1.暂停办理离职手续……
#代付初审 | 1.暂停办理离职手续……
#记账复核 | 1.暂停办理离职手续……
#人工终审 | 1.暂停办理离职手续……
#申请阶段 | 1.暂停办理离职手续……
#已否决 | 2.可办理离职手续
#放款复核 | 1.暂停办理离职手续……
#待处理阶段 | 1.暂停办理离职手续……
#2.若已放款,则进入贷款台账中,根据“贷款状态”取值判断离职管控方式
#-----------------------
#贷款状态 | 离职管控方式
#-----------------------
#正常 | 1.暂停办理离职手续……
#逾期 | 1.暂停办理离职手续……
#正常结清 | 2. 可办理离职手续
#提前结清 | 2. 可办理离职手续
#逾期结清 | 2. 可办理离职手续
#已全部核销/已全部售出 | 2. 可办理离职手续
#已冲销 | 2. 可办理离职手续
select
a.employee_name #姓名
,a.idcard #身份证号
,a.mobile_phone #手机号
,a.ems_id #EMS号
,a.employee_id #员工编码
,a.sex #性别
,a.age #年龄
,a.entry_date #入职时间
,ifnull(a.quit_date,'') as quit_date#离职时间
,a.service_years #服务年限
,a.company_name #公司名
,a.service_status #在职状态
,b.phasename #贷款状态
,b.loan_unfinish_amt#贷款剩余应还本金
,b.leave_control #离职管控方式
from bigdata_ecf_bi.t_evergrande_employee_tmp1 a
join(
select serialno
,customername
,certid
,begintime
,phasename
,loan_unfinish_amt
,case when phasename in (
'已复核阶段'
,'电话核查'
,'复核阶段'
,'人工复核'
,'人工初审'
,'已批准'
,'代付初审'
,'记账复核'
,'人工终审'
,'申请阶段'
,'放款初审'
,'放款复核'
,'待处理阶段'
,'正常'
,'逾期')
then '暂停办理离职手续,请与互金集团接口人XXX联系,并提醒员工结清贷款,再行办理离职手续可办理离职手续;(适用于有在贷中、已审批未放款、申请中等状态员工贷的员工)'
when phasename in (
'已取消申请'
,'已否决'
,'正常结清'
,'提前结清'
,'逾期结清'
,'已全部核销/已全部售出'
,'已冲销')
then '可办理离职手续;(适用于除第1点之外情况的员工)'
else 'Error!'
end as leave_control
from(
select t.serialno
,t.customername
,t.certid
,t.begintime
,t.phasename
,t.loan_unfinish_amt
,@rownum:=@rownum+1
,if(@pdept=t.serialno,@rank:=@rank+1,@rank:=1) as rank
,@pdept:=t.serialno
from(
select t.*
from(
select a.serialno
,a.customername
,c.certid
,b.begintime
#,b.endtime
#,b.flowno
#,b.phaseno
,b.phasename
,0 as loan_unfinish_amt
from ecf_webapp.business_apply a
join ecf_webapp.flow_task b on a.serialno=b.objectno
join ecf_webapp.customer_info c on a.customerid=c.customerid
where b.flowno in ('CreditFlow','PaymentPutOutFlow','TransactionFlow','PutOutFlow')
union all
select a.serialno
,a.customername
,d.certid
,DATE_FORMAT(NOW(),'%Y/%m/%d %H:%i:%s') as begintime
,c.itemname as phasename
,sum(ifnull(e.PAYPRINCIPALAMT,0)-ifnull(e.ACTUALPAYPRINCIPALAMT,0)) as loan_unfinish_amt
from ecf_webapp.business_apply a
join ecf_webapp.acct_loan b on a.serialno=b.applyserialno
join ecf_webapp.code_library c on b.loanstatus=c.itemno
join ecf_webapp.customer_info d on a.customerid=d.customerid
join ecf_webapp.ACCT_PAYMENT_SCHEDULE e on e.objectno=b.serialno
where c.codeno='LoanStatus'
group by a.serialno
,a.customername
,d.certid
,DATE_FORMAT(NOW(),'%Y/%m/%d %H:%i:%s')
,c.itemname
)t
order by serialno, begintime desc
)t,(select @rownum :=0 , @pdept := null ,@rank:=0)a
)t
where rank=1
)b on a.idcard=b.certid
where a.employee_name like '%%'
and a.idcard='' #证件号
and a.mobile_phone='' #手机号
and a.ems_id='' #EMS号
and a.employee_id='' #员工ID
;
#select b.customername,a.*
#from ecf_webapp.LOAN_BATCH_INFO a
#join ecf_webapp.acct_loan b on a.objectno=b.putoutserialno
#join ecf_webapp.business_apply c on b.applyserialno=c.SERIALNO
#where batchtype='10'
# and transstatus in ('11','14','15')
#;
#
#SELECT c.serialno
# ,sum(ifnull(a.PAYPRINCIPALAMT,0)-ifnull(a.ACTUALPAYPRINCIPALAMT,0)) as loan_unfinish_amt
#FROM ecf_webapp.ACCT_PAYMENT_SCHEDULE a
#join ecf_webapp.acct_loan b on a.objectno=b.serialno
#join ecf_webapp.business_apply c on b.applyserialno=c.serialno
#WHERE a.objecttype='jbo.acct.ACCT_LOAN'
#group by c.serialno
#;
#
#
#select
#from ecf_webapp.LOAN_BATCH_INFO a
#join ecf_webapp.acct_loan b on a.objectno=b.putoutserialno
#join ecf_webapp.business_contract c on b.CONTRACTSERIALNO=c.SERIALNO
#where a.batchtype='10'
# and a.objecttype='jbo.app.BUSINESS_PUTOUT'
# and a.transstatus in ('11','14','15')
#;<file_sep>package com.baomidou.springwind.mapper;
import com.baomidou.springwind.entity.EmployeeInfo;
import com.baomidou.mybatisplus.mapper.BaseMapper;
/**
* <p>
* 员工贷款信息表 Mapper 接口
* </p>
*
* @author CuiCan
* @since 2017-07-11
*/
public interface EmployeeInfoMapper extends BaseMapper<EmployeeInfo> {
}<file_sep>#----------------------------------------#
#------QUERY INFOMATION by Markting------#
#----------------------------------------#
##查询条件(可多选,支持模糊查询)
#姓名、证件号、手机号、EMS号、员工ID
##输出
#姓名 身份证号 手机号 员工编码 性别 年龄 入职时间 离职时间 是否VIP 服务年限 公司名 在职状态 特殊名单类型 是否特殊名单
#贷款申请流水号 贷款申请日期 当前贷款状态 剩余未还本金 员工住址 员工收入情况 申请金额 审批完成时间 是否审批拒绝 审批拒绝原因 审批金额
#签约时间 签约金额 放款时间 放款金额 贷款类型(期数) 费率
#drop table bigdata_ecf_bi.wy_temp;
#create table bigdata_ecf_bi.wy_temp as
select
a.employee_name #姓名
,a.idcard #身份证号
,a.mobile_phone #手机号
,a.ems_id #EMS号
,a.employee_id #员工编码
,a.sex #性别
,a.age #年龄
,a.entry_date #入职时间
,coalesce(a.quit_date,'') as quit_date #离职时间
,a.is_vip #是否VIP
,a.grp_service_years #服务年限
,a.company_name #公司名
,a.service_status #在职状态
,a.special_title #特殊名单类型
,a.is_special #是否特殊名单
,b.serialno #贷款申请流水号
,c.inputtime #贷款申请日期
,b.phasename #贷款状态
,b.loan_unfinish_amt #贷款剩余应还本金
,c.familyAddress #员工住址
,c.salary #员工收入情况
,c.businesssum as apply_amt #申请金额
,c.app_endtime #审批完成时间
,c.is_app_reject #是否审批拒绝
,c.app_reject_reason #审批拒绝原因
,coalesce(d.businesssum ,'') as approval_amt #审批金额
,coalesce(d.signdate ,'') as signdate #签约时间
,coalesce(d.businesssum ,'') as sign_amt #签约金额
,coalesce(e.batchdate ,'') as putoutdate #放款时间
,coalesce(e.putoutamt ,'') as putoutamt #放款金额
,coalesce(d.businessterm ,'') as businessterm #贷款类型(期数)
,coalesce(d.businessrate_cut ,'') as businessrate_cut #费率-期初服务费
,coalesce(d.businessrate_rate,'') as businessrate_rate #费率-年利率
,coalesce(d.businessrate_fee ,'') as businessrate_fee #费率-月管理费
,coalesce(d.businessrate_fin ,'') as businessrate_fin #费率-罚息
from bigdata_ecf_bi.t_evergrande_employee_tmp1 a
join(
#贷款状态
#贷款剩余应还本金
select serialno
,customername
,certid
,begintime
,phasename
,loan_unfinish_amt
,case when phasename in (
'已复核阶段'
,'电话核查'
,'复核阶段'
,'人工复核'
,'人工初审'
,'已批准'
,'代付初审'
,'记账复核'
,'人工终审'
,'申请阶段'
,'放款初审'
,'放款复核'
,'待处理阶段'
,'正常'
,'逾期')
then '暂停办理离职手续,请与互金集团接口人XXX联系,并提醒员工结清贷款,再行办理离职手续可办理离职手续;(适用于有在贷中、已审批未放款、申请中等状态员工贷的员工)'
when phasename in (
'已取消申请'
,'已否决'
,'正常结清'
,'提前结清'
,'逾期结清'
,'已全部核销/已全部售出'
,'已冲销')
then '可办理离职手续;(适用于除第1点之外情况的员工)'
else 'Error!'
end as leave_control
from(
select t.serialno
,t.customername
,t.certid
,t.begintime
,t.phasename
,t.loan_unfinish_amt
,@rownum:=@rownum+1
,if(@pdept=t.serialno,@rank:=@rank+1,@rank:=1) as rank
,@pdept:=t.serialno
from(
select t.*
from(
select a.serialno
,a.customername
,c.certid
,b.begintime
#,b.endtime
#,b.flowno
#,b.phaseno
,b.phasename
,0 as loan_unfinish_amt
from ecf_webapp.business_apply a
join ecf_webapp.flow_task b on a.serialno=b.objectno
join ecf_webapp.customer_info c on a.customerid=c.customerid
where b.flowno in ('CreditFlow','PaymentPutOutFlow','TransactionFlow','PutOutFlow')
union all
select a.serialno
,a.customername
,d.certid
,DATE_FORMAT(NOW(),'%Y/%m/%d %H:%i:%s') as begintime
,c.itemname as phasename
,sum(ifnull(e.PAYPRINCIPALAMT,0)-ifnull(e.ACTUALPAYPRINCIPALAMT,0)) as loan_unfinish_amt
from ecf_webapp.business_apply a
join ecf_webapp.acct_loan b on a.serialno=b.applyserialno
join ecf_webapp.code_library c on b.loanstatus=c.itemno
join ecf_webapp.customer_info d on a.customerid=d.customerid
join ecf_webapp.ACCT_PAYMENT_SCHEDULE e on e.objectno=b.serialno
where c.codeno='LoanStatus'
group by a.serialno
,a.customername
,d.certid
,DATE_FORMAT(NOW(),'%Y/%m/%d %H:%i:%s')
,c.itemname
)t
order by serialno, begintime desc
)t,(select @rownum :=0 , @pdept := null ,@rank:=0)a
)t
where rank=1
)b on a.idcard=b.certid
join(
#贷款申请日期
#员工收入情况
#申请金额
#审批完成时间
#是否审批拒绝
#审批拒绝原因
select d.serialno
,d.inputtime
,d.businesssum
,d.customername
,REPLACE(json_extract(b.base_material,'$.familyAddress'),'"','') as familyAddress
,REPLACE(json_extract(b.income_and_assets,'$.salary'),'"','') as salary
,case when e.phaseno='8000' then c.plan_status_reason else '' end as app_reject_reason
,case when e.phaseno='8000' then '是' else '否' end as is_app_reject
,e.endtime as app_endtime
from ecf_ofc.t_ofc_loan_application a
join ecf_ofc.t_ofc_material_entry_img b on a.loan_plan_no=b.loan_plan_no
join ecf_ofc.t_ofc_loan_plan c on a.loan_plan_no=c.loan_plan_no
join ecf_webapp.business_apply d on a.loan_application_no=d.appserialno
join ecf_webapp.flow_task e on d.serialno=e.objectno
where e.objecttype='jbo.app.BUSINESS_APPLY'
and e.phaseno in ('1000','8000')
#ecf_webapp.de_transaction_log where TRANSACTIONid like '%HDJF_13%' and requestmsg like '%王一%'
)c on b.serialno=c.serialno
left outer join(
#审批金额
#签约时间
#签约金额
#贷款类型(期数)
#期初服务费率
#年利率
#月管理费
#罚息
select c.serialno
,a.businesssum
,b.signdate
,a.businessterm
,d.businessrate as businessrate_cut
,e.businessrate as businessrate_rate
,f.businessrate as businessrate_fee
,g.businessrate as businessrate_fin
from ecf_webapp.BUSINESS_CONTRACT a
join ecf_webapp.BUSINESS_CONTRACT_SIGN b on a.SERIALNO=b.OBJECTNO
join ecf_webapp.business_apply c on b.objectno=c.serialno
join(select OBJECTNO, businessrate from ecf_webapp.acct_rate_segment where OBJECTTYPE='jbo.app.BUSINESS_CONTRACT' and TERMID='CUT01')d on c.SERIALNO=d.OBJECTNO
join(select OBJECTNO, businessrate from ecf_webapp.acct_rate_segment where OBJECTTYPE='jbo.app.BUSINESS_CONTRACT' and TERMID='RAT02')e on c.SERIALNO=e.OBJECTNO
join(select OBJECTNO, businessrate from ecf_webapp.acct_rate_segment where OBJECTTYPE='jbo.app.BUSINESS_CONTRACT' and TERMID='FEE01')f on c.SERIALNO=f.OBJECTNO
join(select OBJECTNO, businessrate from ecf_webapp.acct_rate_segment where OBJECTTYPE='jbo.app.BUSINESS_CONTRACT' and TERMID='FIN02')g on c.SERIALNO=g.OBJECTNO
where b.OBJECTTYPE='jbo.app.BUSINESS_CONTRACT'
and b.SIGNDATE is not null
and b.status='03'
)d on b.serialno=d.serialno
left outer join(
#放款时间
#放款金额
select c.serialno
,a.batchdate
,a.putoutamt
,c.customername
from ecf_webapp.LOAN_BATCH_INFO a
join ecf_webapp.acct_loan b on a.objectno=b.putoutserialno
join ecf_webapp.business_apply c on b.applyserialno=c.serialno
where a.batchtype='10'
and a.objecttype='jbo.app.BUSINESS_PUTOUT'
and a.transstatus in ('11','14','15')
)e on b.serialno=e.serialno
where a.employee_name like '%%'
and a.idcard='' #证件号
and a.mobile_phone='' #手机号
and a.ems_id #EMS号
and a.employee_id #员工ID
;
|
94f2a737265acb81bff638f979944acb7eac9ac1
|
[
"Java",
"SQL"
] | 4 |
Java
|
yyccbbz/evergrande-employee
|
29024d9afcfb6c391b6fbae7f1733f0f4829529b
|
5ad0c222275c85859ccd080a72da1b9838d6e09e
|
refs/heads/master
|
<repo_name>ewerton-augusto/frontend-test<file_sep>/src/resources/js/app/models/ExtratoTransacoes.js
export class ExtratoTransacoes{
constructor(){
this._transacoes = JSON.parse(localStorage.getItem('transacoes')) || [];
this._total = (localStorage.getItem('total')*1);
}
adiciona(transacao){
const novaTransacao = {
tipoTransacao: transacao.tipoTransacao,
mercadoria: transacao.mercadoria,
valor: transacao.valor
};
const atualizaTransacoes = [...this._transacoes, novaTransacao];
localStorage.setItem('transacoes', JSON.stringify(atualizaTransacoes));
this._transacoes = JSON.parse(localStorage.getItem('transacoes'));
this._calcularTotal(transacao.tipoTransacao, transacao.valor);
}
_calcularTotal(tipoTransacao, valor){
//tipoTransacao: 1 = compra, 2 = venda
this._total += (tipoTransacao == 1)?-valor:valor;
localStorage.setItem('total', this._total);
}
get transacoes(){
return this._transacoes;
}
get total(){
return this._total;
}
}<file_sep>/src/resources/js/app/models/Transacao.js
export class Transacao {
constructor(tipoTransacao, mercadoria, valor){
this._tipoTransacao = tipoTransacao;
this._mercadoria = mercadoria;
this._valor = valor*1;
Object.freeze(this);
}
get tipoTransacao(){
return this._tipoTransacao;
}
get mercadoria(){
return this._mercadoria;
}
get valor(){
return this._valor;
}
}<file_sep>/src/resources/js/app/helpers/FormataMoeda.js
export class FormataMoeda{
static formatarMoeda(valor){
return "R$" + parseFloat(valor).toFixed(2).replace(".",",");
}
}<file_sep>/src/resources/js/main.js
import {TransacaoController} from "./app/controllers/TransacaoController.js";
//menu
document.querySelector('[data-btn-open-menu]').onclick = function() {
document.documentElement.classList.add('active-menu');
}
document.querySelector('[data-btn-close-menu]').onclick = function(){
document.documentElement.classList.remove('active-menu');
}
document.documentElement.onclick = function(event){
if(event.target === document.documentElement){
document.documentElement.classList.remove('active-menu');
}
}
//transaction
let transacaoController = new TransacaoController();
const formNewTransaction = document.querySelector('[form-new-transaction]');
formNewTransaction.addEventListener('submit', (event) => transacaoController.adicionaTransacao(event));
|
ef5bf527889ba54a19178ceb6e06b24158222141
|
[
"JavaScript"
] | 4 |
JavaScript
|
ewerton-augusto/frontend-test
|
29c2ae2d3779313a31340fa35fd06dd18a1f08d9
|
c08dc5be8d01e73a8a00986b047af8dfb2c0cead
|
refs/heads/master
|
<repo_name>wap300/backuper<file_sep>/README.md
backuper
========
Backup system consisting of a pair of client and server. Working, but not fully finished.
It works in the following way:
- Setup and run your server.
- Enter the ip and port of the backup server:
<br>
- Select the dir to backup
<br>
- Send files to server
<br>
<file_sep>/backuper/src/Communicator.java
import java.util.ArrayList;
public abstract class Communicator {
ArrayList<IListener> listeners = new ArrayList<IListener>();
public void emit(String eventName, Object value) {
for (int i = 0; i < listeners.size(); i++) {
listeners.get(i).notify(eventName, value);
}
}
public void subscribe(IListener subscriber) {
listeners.add(subscriber);
}
}
<file_sep>/backuperServer/src/Server.java
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Random;
import javax.swing.JOptionPane;
public class Server {
private ServerSocket serverSocket;
private Socket socket;
BufferedReader protocolIn;
InputStream fileIn;
private final static int STATE_LISTENING = 0;
private final static int STATE_RECEIVING_FILES = 1;
private int state;
public void initConnection() {
try {
serverSocket = new ServerSocket(555);
socket = serverSocket.accept();
setListeningMode();
} catch (IOException e) {
e.printStackTrace();
}
}
private void setListeningMode() {
state = STATE_LISTENING;
try {
protocolIn = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
String inputLine;
while (state == STATE_LISTENING && (inputLine = protocolIn.readLine()) != null) {
//System.out.println("SERVER GOT: " + inputLine);
handleReceivedQuery(inputLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void setReceivingMode() {
state = STATE_RECEIVING_FILES;
//protocolIn.close();
//System.out.println("Server protocol input closed");
}
private void handleReceivedQuery(String inputLine) {
if (inputLine.split(":").length == 0) {
return;
}
String header = inputLine.split(":")[0];
if (header.equals(Protocol.SENDING_FILE)) {
//System.out.println("Received sending file request: " + inputLine);
setReceivingMode();
receiveFile(inputLine.split(":")[1], Integer.parseInt(inputLine.split(":")[2]));
setListeningMode();
}
}
public void sendFile() {
try {
//System.out.println("Accepted connection : " + socket);
File transferFile = new File("Document.doc");
byte[]bytearray = new byte[(int)transferFile.length()];
FileInputStream fin = new FileInputStream(transferFile);
BufferedInputStream bin = new BufferedInputStream(fin);
bin.read(bytearray, 0, bytearray.length);
OutputStream os = socket.getOutputStream();
//System.out.println("Sending Files...");
os.write(bytearray, 0, bytearray.length);
os.flush();
//System.out.println("File transfer complete");
} catch (Exception e) {}
}
public void receiveFile(String name, int filesize) {
try {
//System.out.println("receiveFile with name " + name + " and size " + filesize);
int bytesRead;
int currentTot = 0;
byte[]bytearray = new byte[filesize];
fileIn = socket.getInputStream();
//System.out.println("Server file input opened");
new File("backup").mkdirs();
FileOutputStream fos = new FileOutputStream("backup/" + name);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = fileIn.read(bytearray, 0, bytearray.length);
currentTot = bytesRead;
do {
bytesRead =
fileIn.read(bytearray, currentTot, (bytearray.length - currentTot));
////System.out.println(currentTot + "/" + filesize);
if (bytesRead >= 0)
currentTot += bytesRead;
} while (currentTot != filesize);
bos.write(bytearray, 0, currentTot);
bos.flush();
//TODO all streams/sockets should close after EOF
//bos.close();
//fileIn.close();
//socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
<file_sep>/backuperServer/src/Protocol.java
public class Protocol {
public static final int WAITING = 0;
public static final int USER_LOGGED = 1;
public static final String END_CONNECTION = "END";
public static final CharSequence RESERVED_SIGN = ":";
public static final String WELCOME_MESSAGE = "HELLO";
public static final String SENDING_FILE = "SENDING_FILE";
}
|
77d11ee37750f82453196f48eebcb9f2c0e464a7
|
[
"Markdown",
"Java"
] | 4 |
Markdown
|
wap300/backuper
|
114ed179cb26a8bf6fb096703f89e95b56740e0d
|
2f2e782d5b20450fd5cf32966d8c0d765d88ba50
|
refs/heads/master
|
<file_sep>
var number = 29;
console.log(number.toString().split('').reduce(function(r, n) {
return r + parseInt(n)
}, 0))
<file_sep>
function candies(n,m){
var c = 0;
c = m/n;
c= parseInt(c) * n;
return c;
}
console.log(candies(3,10));
module.exports=candies;
<file_sep>function checkPalindrome(aux) {
low = aux.toLowerCase();
regExp = low.replace(/[\W_]/g, "");
s = regExp.split("");
r = s.reverse();
j = r.join("");
if (regExp == j)
{return true;}
else {return false;}
}
console.log(checkPalindrome("aabaa"));
console.log(checkPalindrome("abac"));
console.log(checkPalindrome("a"));
|
53e7044899806941407e8038c83c9408426ab777
|
[
"JavaScript"
] | 3 |
JavaScript
|
mairaingrid/laboratorio
|
c4a3cbee3deaa1a83b4f22617af2b52f7a7bc604
|
cf28581c1ee18b5659b1fdb14405e2754515a036
|
refs/heads/master
|
<repo_name>DXBrazil/GetStarted-iText<file_sep>/readme.md
Desafio: Gerar os arquivos XML a partir de PDF
================================================
Exemplo: Documento _p40.pdf_ ([download](ConsoleApp1/samples/p40.pdf))
Nesse documento, existem 6 atos (total de 8 ao somar um incompleto e uma retificação), que são na ordem:
- Portaria No 13
- Ato declaratório executivo No 96
- Ato declaratório executivo No 29
- Ato declaratório executivo No 15
- Ato declaratório executivo No 74
- Ato declaratório executivo No 33
Aparentemente os números (13, 96, 29, 15, 74, 33) estão fora de ordem, mas na verdade eles pertencem a diferentes superintendências:
- Superintendência regional da 6ª região fiscal
- Superintendência regional da 7ª região fiscal
- Superintendência regional da 8ª região fiscal
Há uma hierarquia entre Superintendências, Delegacias e o Atos. Assim, podemos entender melhor a organização:
- Superintendência regional da 6ª região fiscal / Delegacia da receita federal do Brasil em Belo Horizonte / Portaria No 13
- Superintendência regional da 6ª região fiscal / Delegacia da receita federal do Brasil em Poços de Calda / Ato declaratório executivo No 96
- (Superintendência regional da 7ª região fiscal / Delegacia da receita federal do Brasil em Vitória / Retificação)
- Superintendência regional da 8ª região fiscal / Alfândega da receita federal do Brasil em São Paulo / Ato declaratório executivo No 29
- Superintendência regional da 8ª região fiscal / Delegacia da receita federal do Brasil em Campinas / Ato declaratório executivo No 15
- Superintendência regional da 8ª região fiscal / Delegacia da receita federal do Brasil em Piracicaba / Ato declaratório executivo No 74
- Superintendência regional da 8ª região fiscal / Delegacia da receita federal do Brasil em São José dos Campos / Seção de Administração Aduaneira / Ato declaratório executivo No 33
Esses são os 6 atos completos presentes no documento e a retificação.
Cada arquivo XML tem uma hierarquia, título, caput (breve sumário), assinatura com cargo opcional. Então seria algo assim:
```xml
<XML>
<HIERARQUIA>
<H1>SUPERINTENDÊNCIA REGIONAL DA 6ª REGIÃO FISCAL</H1>
<H2>DELEGACIA DA RECEITA FEDERAL DO BRASIL EM BELO HORIZONTE</H2>
</HIERARQUIA>
<TITULO> PORTARIA No- 13, DE 10 DE NOVEMBRO DE 2017 </TITULO>
<CAPUT>Exclui pessoa jurídica do REFIS.</CAPUT>
<CORPO>
A DELEGACIA DA RECEITA FEDERAL DO BRASIL
EM BELO HORIZONTE/MG, tendo em vista a competência delegada
pela Resolução do Comitê Gestor do REFIS nº 37, de 31 de
agosto de 2011, por sua vez constituído pela Portaria Interministerial
MF/MPAS nº 21, de 31 de janeiro de 2000, no uso da competência
estabelecida no § 1º do art. 1º da Lei nº 9.964, de 10 de abril de 2000,
e no inciso IV do art. 2º do Decreto nº 3.431, de 24 de abril de 2000,
tendo em vista o disposto no inciso XIV do art. 79 da Lei nº 11.941,
de 27 de maio de 2009, resolve:
Art. 1o Excluir do Programa de Recuperação Fiscal - REFIS,
a PEDIDO, a pessoa jurídica DEPÓSITO ARAÚJO MATERIAIS DE
CONSTRUÇÃO, CNPJ: 17.345.570/0001-16, conforme registrado no
processo administriativo n° 10695.001452/2017-48
Art. 2o Esta Portaria entra em vigor na data de sua publicação.
</CORPO>
<ASSINATURA>
<NOME><NAME></NOME>
<CARGO>Delegado da Receita Federal do Brasil em Belo Horizonte/MG</CARGO>
</ASSINATURA>
</XML>
```
Obs: Há um diretório com samples do p40, p42 e p44. Com certeza, p44 é o mais fácil!
# Por onde começar?
* Sample: https://github.com/DXBrazil/GetStarted-iText
* Biblioteca: iText (https://itextpdf.com/)
Existem as versões iText 5 e 7, que são bem diferentes entre si. Inicialmente trabalhamos com a versão 5 no repositório privado(https://github.com/DXBrazil/CasaCivil-PDF2XML). Porém, depois trocamos para a versão 7, que suporta .NET Core. Há diferenças significativas na API.
Assim, Podemos escrever nosso primeiro código (simples!):
```csharp
static string ReadTextFromPdf(string filename)
{
using (var pdf = new PdfDocument(new PdfReader(filename)))
{
var page = pdf.GetFirstPage();
return PdfTextExtractor.GetTextFromPage(page);
}
}
````
Entretanto, o resultado não é interessante... compare com o anexo p40.pdf.
```
40
1
ISSN 1677-7042
Nº 218, terça-feira, 14 de novembro de 2017
O montante relativo à atualizaçao monetária e juros con- DELEGACIA DA RECEITA FEDERAL DO BRASIL Parágrafo único O regime especial de substituiçao tributária
tratuais, vinculado à indenizaçao por dano patrimonial, deverá ser nao se aplica ao IPI devido no desembaraço aduaneiro de produtos de
EM POÇOS DE CALDAS
computado na apuraçao da base de cálculo da contribuiçao procedência estrangeira.
...
...
```
Por isso, é necessário customizar a leitura através de Listeners:
```csharp
static void ReadTextFromListener(string filename)
{
using (var pdf = new PdfDocument(new PdfReader(filename)))
{
var page = pdf.GetFirstPage();
var parser = new PdfCanvasProcessor(new UserTextListener());
parser.ProcessPageContent(page);
}
}
```
Tem vários exemplos no código: https://github.com/DXBrazil/GetStarted-iText
<file_sep>/ConsoleApp1/AnalyzeTextListener.cs
using iText.Kernel.Pdf.Canvas.Parser;
using iText.Kernel.Pdf.Canvas.Parser.Data;
using iText.Kernel.Pdf.Canvas.Parser.Listener;
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp1
{
class AnalyzeTextListener : IEventListener
{
public void EventOccurred(IEventData data, EventType type)
{
if(data is TextRenderInfo)
{
var textInfo = (TextRenderInfo)data;
string text = textInfo.GetText();
// Font
var font = textInfo.GetFont();
var fontProgram = font.GetFontProgram();
var fontFamily = fontProgram.GetFontNames().GetFamilyName();
double fontSize = textInfo.GetFontSize();
// Grayscale, RGB, CMYK
var color = textInfo.GetStrokeColor();
var colorSpace = color.GetColorSpace();
float[] colorComponents = color.GetColorValue();
// Ascent, Descent, Baseline
// https://stackoverflow.com/questions/27631736/meaning-of-top-ascent-baseline-descent-bottom-and-leading-in-androids-font
var ascent = textInfo.GetAscentLine();
var descent = textInfo.GetDescentLine();
var baseline = textInfo.GetDescentLine();
var start = baseline.GetStartPoint();
var end = baseline.GetEndPoint();
// Coordinates
float x1 = start.Get(0);
float y1 = start.Get(1);
float x2 = end.Get(0);
float y2 = end.Get(1);
Console.WriteLine($"{font.ToString()} {fontSize}: ({x1},{y1})-({x2},{y2})");
}
}
public ICollection<EventType> GetSupportedEvents()
{
return new[] { EventType.RENDER_TEXT };
}
}
}
<file_sep>/ConsoleApp1/Program.cs
using System;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas.Parser;
using iText.Kernel.Pdf.Canvas.Parser.Listener;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
string filename = "samples/p40.pdf";
string simpleResult = ReadTextFromPdf(filename);
Console.WriteLine("============================================================");
Console.WriteLine("ReadTextFromPdf");
Console.WriteLine("============================================================");
Console.WriteLine(simpleResult.Substring(0, 1000));
Console.WriteLine();
Console.ReadKey();
Console.WriteLine();
Console.WriteLine("============================================================");
Console.WriteLine("ReadTextFromListener");
Console.WriteLine("============================================================");
ReadTextFromListener(filename);
Console.WriteLine();
Console.ReadKey();
Console.WriteLine();
Console.WriteLine("============================================================");
Console.WriteLine("ShowLinesFromListener");
Console.WriteLine("============================================================");
ShowLinesFromListener(filename);
Console.WriteLine();
Console.ReadKey();
Console.WriteLine();
Console.WriteLine("============================================================");
Console.WriteLine("AnalyzeTextFromListener");
Console.WriteLine("============================================================");
AnalyzeTextFromListener(filename);
Console.WriteLine();
}
static string ReadTextFromPdf(string filename)
{
using (var pdf = new PdfDocument(new PdfReader(filename)))
{
var page = pdf.GetFirstPage();
return PdfTextExtractor.GetTextFromPage(page);
}
}
static void ReadTextFromListener(string filename)
{
using (var pdf = new PdfDocument(new PdfReader(filename)))
{
var page = pdf.GetFirstPage();
var parser = new PdfCanvasProcessor(new UserTextListener());
parser.ProcessPageContent(page);
}
}
static void ShowLinesFromListener(string filename)
{
using (var pdf = new PdfDocument(new PdfReader(filename)))
{
var page = pdf.GetFirstPage();
var parser = new PdfCanvasProcessor(new UserPathListener());
parser.ProcessPageContent(page);
}
}
static void AnalyzeTextFromListener(string filename)
{
using (var pdf = new PdfDocument(new PdfReader(filename)))
{
var page = pdf.GetFirstPage();
var parser = new PdfCanvasProcessor(new AnalyzeTextListener());
parser.ProcessPageContent(page);
}
}
}
}
<file_sep>/ConsoleApp1/UserPathListener.cs
using iText.Kernel.Pdf.Canvas.Parser;
using iText.Kernel.Pdf.Canvas.Parser.Data;
using iText.Kernel.Pdf.Canvas.Parser.Listener;
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp1
{
class UserPathListener : IEventListener
{
public void EventOccurred(IEventData data, EventType type)
{
if (data is PathRenderInfo)
{
var path = (PathRenderInfo)data;
var subpaths = path.GetPath().GetSubpaths();
foreach(var subpath in subpaths)
{
var shape = subpath.GetSegments();
foreach(var line in shape)
{
var points = line.GetBasePoints();
foreach(var p in points)
{
double x = p.x;
double y = p.y;
Console.Write(" - ");
Console.Write($"({x.ToString("0.00")},{y.ToString("0.00")})");
}
}
}
Console.WriteLine();
}
}
public ICollection<EventType> GetSupportedEvents()
{
return new[] { EventType.RENDER_PATH };
}
}
}
<file_sep>/ConsoleApp1/UserTextListener.cs
using iText.Kernel.Pdf.Canvas.Parser;
using iText.Kernel.Pdf.Canvas.Parser.Data;
using iText.Kernel.Pdf.Canvas.Parser.Listener;
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp1
{
class UserTextListener : IEventListener
{
public void EventOccurred(IEventData data, EventType type)
{
if(data is TextRenderInfo)
{
var textInfo = (TextRenderInfo)data;
string text = textInfo.GetText();
Console.Write(text);
Console.Write(" ");
}
}
public ICollection<EventType> GetSupportedEvents()
{
return new[] { EventType.RENDER_TEXT };
}
}
}
|
3ea8ea01571c4de131907c71624d773806efbd49
|
[
"Markdown",
"C#"
] | 5 |
Markdown
|
DXBrazil/GetStarted-iText
|
ede09f9609b6dd51bdd0ed9c43c2d5c36cad436f
|
a8263dd8a52bdf055299a8cc693e3104b97eae73
|
refs/heads/master
|
<repo_name>ry-pe/ry-pe.github.io<file_sep>/ad.js
document.getElementById("advertisement").style.display="block"
|
149fb67cc12e8fb8a45b12f72f74d008291f71bc
|
[
"JavaScript"
] | 1 |
JavaScript
|
ry-pe/ry-pe.github.io
|
c93ded59bd5700f23da45d9d885cee76207bf0fa
|
dad06ba2f49797283deed451f82b6da7ae41c798
|
refs/heads/master
|
<file_sep>
#logistic
scl <- function(x){ (x - min(x))/(max(x) - min(x)) }
scl <- function(x){x^2}
cancel<-(dataset_1$cancel)
dataset_1$V7<-dataset_1$tenure/dataset_1$len.at.res
dataset_3<-data.frame(cbind(scl(dataset_1$tenure),scl(dataset_1$n.adults),scl(dataset_1$n.children),scl(dataset_1$len.at.res),scl(dataset_1$premium),scl(dataset_1$ni.age),
class.ind(as.factor(dataset_1$claim.ind)),class.ind(dataset_1$ni.gender),class.ind(as.factor(dataset_1$ni.marital.status))),class.ind(dataset_1$sales.channel)
,class.ind(dataset_1$coverage.type),class.ind(dataset_1$dwelling.type),class.ind(dataset_1$credit),class.ind(dataset_1$house.color),class.ind(dataset_1$year),cancel,
class.ind(dataset_1$State),class.ind(dataset_1$city.risk),class.ind(dataset_1$Zip.cat),V7=scl(dataset_1$V7))
dataset_3[,7:46]<-data.frame(sapply(7:46,function(x) as.factor(dataset_3[,x])))
rownames(dataset_3) <- seq(length=nrow(dataset_3))
iv.mult(dataset_3,"cancel",TRUE)
#convert all variables into categorical variables or standerdised variables
set.seed(123)
indexes = sample(1:nrow(dataset_3), size=0.2*nrow(dataset_3))
test<-dataset_3[indexes,]
train<-dataset_3[-indexes,]
model <- glm(cancel~high+ low+ Broker+ Low.Risk.City+ High.Risk.City+ VA+ PA+ X2014+ V3+ V6+Low.Zip,family=binomial(link='logit'),data=train)
summary(model)
train.results <- predict(model,newdata=train,type='response')
auc(train$cancel,train.results)
fitted.results <- predict(model,newdata=test,type='response')
auc(test$cancel,fitted.results)
<file_sep>setwd("C:/Users/rosha/OneDrive for Business/Travelers")
dataset_2<-read.csv("Train.csv")
dataset_1<-dataset_2[complete.cases(dataset_2),]
dataset_1<-dataset_1[which(!dataset_1$cancel==-1),]
dataset_1<-dataset_1[which(dataset_1$ni.age<76),]
library(woe)
library(car)
require("randomForest")
require("ROCR")
require(neuralnet)
require(nnet)
require(ggplot2)
library(caret)
library(Metrics)
library(gbm)
#preprosessing steps
scl <- function(x){ (x - min(x))/(max(x) - min(x)) }
scl <- function(x){x^2}
cancel<-(dataset_1$cancel)
dataset_3<-data.frame(cbind(scl(dataset_1$tenure),scl(dataset_1$n.adults),scl(dataset_1$n.children),scl(dataset_1$len.at.res),scl(dataset_1$premium),scl(dataset_1$ni.age),
class.ind(as.factor(dataset_1$claim.ind)),class.ind(dataset_1$ni.gender),class.ind(as.factor(dataset_1$ni.marital.status))),class.ind(dataset_1$sales.channel)
,class.ind(dataset_1$coverage.type),class.ind(dataset_1$dwelling.type),class.ind(dataset_1$credit),class.ind(dataset_1$house.color),class.ind(dataset_1$year),cancel,
class.ind(dataset_1$State),class.ind(dataset_1$city.risk))
dataset_3[,7:44]<-data.frame(sapply(7:44,function(x) as.factor(dataset_3[,x])))
#convert all variables into categorical variables or standerdised variables
set.seed(1234)
indexes = sample(1:nrow(dataset_3), size=0.2*nrow(dataset_3))
test<-dataset_3[indexes,]
train<-dataset_3[-indexes,]
str(train)
summary(train)
nums<-sapply(dataset_3,is.numeric)
chars<-sapply(dataset_3,is.factor)
rownames(dataset_3) <- seq(length=nrow(dataset_3))
iv.mult(dataset_3,"cancel",TRUE)
correlation<-data.frame(cor(train[,nums]))
nrow(dataset_1[complete.cases(dataset_1),])
quantile(train$len.at.res,probs=seq(0,1,.1))
quantile(train$n.adults,probs=seq(0,1,.1))
quantile(train$n.children,probs=seq(0,1,.1))
quantile(train$ni.age,probs=seq(0,1,.1))
quantile(train$ni.marital.status,probs=seq(0,1,.1))
quantile(train$premium,probs=seq(0,1,.1))
quantile(train$tenure,probs=seq(0,1,.1))
summary(train[,chars])
rownames(train) <- seq(length=nrow(train))
iv.mult(train,"cancel",TRUE)
str(train)
train$cancel<-as.factor(train$cancel)
str(train)
train$premium_cat<-cut(train$premium, c(645,700,745,800,845,900,945,1000,1045,1100,1165))
prop.table(table(train$coverage.type,train$cancel))
train$V7<-(train$V1)/(train$V4)
test$V7<-(test$V1)/(test$V4)
model <- glm(cancel~high+low+Broker+VA+PA+X2014+V3+V6+X2016+X0+V7,family=binomial(link='logit'),data=train)
model <- glm(cancel ~ ni.marital.status+ credit+ tenure+ claim.ind+ sales.channel+ ni.age
+ n.children,
family=binomial(link='logit'),data=train)
summary(model)
vif(model)
anova(model,"Chisq")
train.results <- predict(model,newdata=train,type='response')
train.results <- ifelse(train.results > 0.50,1,0)
misClasificError <- mean(train.results != train$cancel)
print(paste('Accuracy',1-misClasificError))
model.pred<- prediction(train.results, train$cancel)
model.perf<- performance(model.pred,"tpr","fpr")
auc<- performance(model.pred,"auc")
print([email protected])
plot(model.perf,main="ROC Curve for Random Forest",col=2,lwd=2)
abline(a=0,b=1,lwd=2,lty=2,col="gray")
auc(train$cancel,train.results)
fitted.results <- predict(model,newdata=test,type='response')
fitted.results <- ifelse(fitted.results > 0.25,1,0)
misClasificError <- mean(fitted.results != test$cancel)
print(paste('Accuracy',1-misClasificError))
model.pred<- prediction(fitted.results, test$cancel)
auc(test$cancel,fitted.results)
model.perf<- performance(model.pred,"tpr","fpr")
plot(model.perf,main="ROC Curve for Random Forest",col=2,lwd=2)
abline(a=0,b=1,lwd=2,lty=2,col="gray")
train$prob_glm<-train.results
test$prob_glm<-fitted.results
# random forest
for(i in 1:20)
{
model.rf <- randomForest(as.factor(cancel) ~ ., data=train, importance=TRUE,
proximity=TRUE,ntree=(i*100),nodesize=100)
importance(model.rf)
train$prob_rf<-predict(model.rf,type="prob",newdata = train)[,2]
test$prob_rf<-predict(model.rf,type="prob",newdata = test)[,2]
print(auc(train$cancel,train$prob_rf))
print(auc(test$cancel,test$prob_rf))
fitted.results<-ifelse(test$prob_rf>0.4,1,0)
misClasificError <- mean(fitted.results != test$cancel)
print(paste('Accuracy for',i*100,'tree is',1-misClasificError))
}
model.rf <- randomForest(as.factor(cancel) ~ ., data=train[,-c(17,19)], importance=TRUE,
proximity=TRUE,ntree=300,nodesize=10,mtry=3,
sampsize=100)
importance(model.rf)
train$prob_rf<-predict(model.rf,type="prob",newdata = train)[,2]
test$prob_rf<-predict(model.rf,type="prob",newdata = test)[,2]
print(auc(train$cancel,train$prob_rf))
print(auc(test$cancel,test$prob_rf))
# neural network
train$cancel1<-class.ind(train$cancel)
seedsANN = nnet(cancel1~.,data=train[,-18],size=25)
test$predict_nn<-predict(seedsANN,test[,-18],type = "class")
table(test$predict_nn,test$cancel)
# neural net package
train$outcome1 <- ifelse(train$cancel == 1, "Yes","No")
test$outcome1 <- ifelse(test$cancel == 1, "Yes","No")
train_nn<-cbind(train[,-33],class.ind(train$outcome1))
test_nn<-cbind(test[,-33],class.ind(test$outcome1))
# Set up formula
n <- names(train_nn)
f <- as.formula(paste("No+Yes ~", paste(n[!n %in% c("No","Yes","outcome1")], collapse = " + ")))
n<-n[-c()]
nn <- neuralnet(f,data = train_nn,hidden = c(3, 2, 2),
act.fct = "logistic",linear.output = FALSE,lifesign = "minimal")
plot(nn)
# Compute predictions
pr.nn <- compute(nn, train_nn[1:32])
# Extract results
pr.nn_ <- pr.nn$net.result
head(pr.nn_)
# Accuracy (training set)
original_values <- max.col(train_nn[, 33:34])
pr.nn_2 <- max.col(pr.nn_)
mean(pr.nn_2 == original_values)
# Compute predictions
pr.nn <- compute(nn, test_nn[1:32])
# Extract results
pr.nn_ <- pr.nn$net.result
head(pr.nn_)
# Accuracy (training set)
original_values <- max.col(test_nn[, 33:34])
pr.nn_2 <- max.col(pr.nn_)
mean(pr.nn_2 == original_values)
auc(train$cancel,pr.nn_[,2])
train$prob_nn<-pr.nn_[,2]
test$prob_nn<-pr.nn_[,2]
auc(train$cancel,train$prob_nn)
auc(test$cancel,test$prob_nn)
#gbm
fitControl <- trainControl(method = "repeatedcv", number = 4, repeats = 4)
train$outcome1<-NA
train$outcome1 <- ifelse(train$cancel == 1, "Yes","No")
set.seed(33)
gbmFit1 <- train(as.factor(outcome1) ~ .,
data = train[,-18], method = "gbm", trControl = fitControl,verbose = FALSE)
train$prob_gbm<-predict(gbmFit1, train,type= "prob")[,2]
test$prob_gbm<-predict(gbmFit1, test,type= "prob")[,2]
auc(train$cancel,train$prob_gbm)
auc(test$cancel,test$prob_gbm)
boost.myData<-gbm(cancel~.,data=train,distribution="bernoulli",n.trees=5000,interaction.depth=4)
pred.boost<-predict(boost.myData,newdata=myData[test,],n.trees=5000,type="response")
#knn
library(class)
fitControl <- trainControl(method = "cv",number = 5,savePredictions = 'final',classProbs = T)
model_knn<-train(cancel ~ credit+ sales.channel+ n.children+ ni.marital.status+ year+
claim.ind+ len.at.res+ n.adults,data=train, method='knn')
names(model_knn)
pred_knn<-predict(object=model_knn,data=test)
confusionMatrix(pred_knn,test$outcome1)
train_knn<-data.frame(cbind(scl(train$tenure),class.ind(train$claim.ind),scl(train$n.children),
class.ind(train$sales.channel),scl(train$len.at.res),class.ind(train$credit),
scl(train$ni.age),class.ind(train$year)),train$cancel)
test_knn<-data.frame(cbind(scl(test$tenure),class.ind(test$claim.ind),scl(test$n.children),
class.ind(test$sales.channel),scl(test$len.at.res),class.ind(test$credit),
scl(test$ni.age),class.ind(test$year),test$cancel))
for(i in 1:20)
{
print(paste("k is",i))
pred_knn<-knn(train_knn, test_knn, train[,"cancel"], k = i, l = 0, prob = TRUE, use.all = TRUE)
print(paste("total 1s captured",sum(table(pred_knn,test$cancel)[2,])))
print(paste("Accuracy is",1-(table(pred_knn,test$cancel)[1,2]+table(pred_knn,test$cancel)[2,1])/sum(table(pred_knn,test$cancel))))
}
library(KODAMA)
x<-list(train_knn,test$knn)
knn.dist(x)
#ensembling
for(i in 1:nrow(train))
{
train$prob_all[i]<-max(train$prob_glm[i],train$prob_rf[i],train$prob_nn[i])
}
auc(train$cancel,train$prob_all)
total_prob <- ifelse(train$prob_all > 0.5,1,0)
misClasificError <- mean(total_prob != train$cancel)
print(paste('Accuracy',1-misClasificError))
summary(train$prob_all)
for(i in 1:nrow(test))
{
test$prob_all[i]<-max(test$prob_glm[i],test$prob_rf[i],test$prob_nn[i])
}
auc(test$cancel,test$prob_all)
## model
model_ensemble_glm<-glm(cancel~prob_glm+prob_rf+prob_nn+prob_gbm,family=binomial(link='logit'),data=train)
summary(model_ensemble_glm)
train.results <- predict(model_ensemble_glm,newdata=train,type='response')
auc(train$cancel,train.results)
test.results <- predict(model_ensemble_glm,newdata=test,type='response')
auc(test$cancel,test.results)
model_ensemble_gbm <- train(as.factor(outcome1) ~prob_glm+prob_gbm
, data = train[,-18], method = "gbm", trControl = fitControl,verbose = FALSE)
model_ensemble_gbm_dev <- predict(model_ensemble_gbm, train,type= "prob")[,2]
model_ensemble_gbm_test <- predict(model_ensemble_gbm, test,type= "prob")[,2]
auc(train$cancel,gbm_dev)
auc(test$cancel,gbm_ITV2)
<file_sep>#random forest
x<-train
y<-test
# Create model with default paramters
control <- trainControl(method="repeatedcv", number=10, repeats=3)
seed <- 7
metric <- "Accuracy"
set.seed(seed)
mtry <- sqrt(ncol(x))
tunegrid <- expand.grid(.mtry=mtry)
rf_default <- train(as.factor(cancel) ~ .
, data=train_chai[,chars], method="rf", metric=metric, tuneGrid=tunegrid, trControl=control)
print(rf_default)
# Random Search
control <- trainControl(method="repeatedcv", number=10, repeats=3, search="random")
set.seed(seed)
mtry <- sqrt(ncol(x))
rf_random <- train(Class~., data=dataset, met
print(rf_random)
plot(rf_random)
#grid search
control <- trainControl(method="repeatedcv", number=10, repeats=3, search="grid")
set.seed(seed)
tunegrid <- expand.grid(.mtry=c(1:15))
rf_gridsearch <- train(Class~., data=dataset, method="rf", metric=metric, tuneGrid=tunegrid, trControl=control)
print(rf_gridsearch)
plot(rf_gridsearch)
<file_sep>library("CHAID", lib.loc="~/R/win-library/3.4")
library(e1071)
chaid.control<-chaid_control(alpha2 = 0.05, alpha3 = -1, alpha4 = 0.05,
minsplit = 20, minbucket = 7, minprob = 0.05,
stump = FALSE, maxheight = 4)
dataset_1$cancel<-as.factor(dataset_1$cancel)
data_chaid<-dataset_1[,-c(17,19)]
chars<-sapply(data_chaid,is.factor)
set.seed(123)
indexes = sample(1:nrow(dataset_1), size=0.2*nrow(dataset_1))
test_chaid<-data_chaid[indexes,]
train_chai<-data_chaid[-indexes,]
tree<-chaid(as.factor(cancel)~.,train_chai[,chars],control=chaid.control)
plot(tree)
fitted.results<-predict(tree,newdata = test_chaid,type="prob")[,2]
auc(test_chaid$cancel,fitted.results)
model_nb<-naiveBayes(as.factor(cancel)~.,data=train)
pred<-predict(model_nb,test)
auc(test$cancel,pred)
table(pred,test$cancel)
model_svm<-svm(as.factor(cancel)~high+ low+ Broker+ Low.Risk.City+ High.Risk.City+ VA+ PA+ V3+ V6,data=train,
kernal=rbf,gamma=.2,cost=1000,probability=TRUE)
prob_svm<-predict(model_svm,train,probability=TRUE)
table(pred,train$cancel)
auc(train$cancel,attr(prob_svm,'prob')[,2])
confusionMatrix(train_ensemble$prob_svm,train$cancel)
prob_svm<-predict(model_svm,test,probability=TRUE)
table(pred,test$cancel)
auc(test$cancel,attr(prob_svm,'prob')[,2])
confusionMatrix(test_ensemble$prob_svm,test$cancel)
pred_input <- prediction(test$pred,test$cancel)
|
0f17ff53eedc76d545a8536fc75fd6a958a65833
|
[
"R"
] | 4 |
R
|
roshanzubair/Travelers-claim-prediction
|
672a068ddd2a75eb41ceb1eafaeb28748a7e4c89
|
8c911824dc0715a8492d9983f3229788ad155bc7
|
refs/heads/master
|
<file_sep>import React from "react";
import StripeCheckout from "react-stripe-checkout";
export default function StripeGateway({ amount }) {
const API_URL =
"http://localhost:5001/buy-with-stripe/us-central1/makePayment";
//https://us-central1-buy-with-stripe.cloudfunctions.net/makePayment
//http://localhost:5001/buy-with-stripe/us-central1/makePayment
// capture token returned by stripe gateway and send to server for charging.
function doPayment(token) {
const body = {
token,
amount: amount,
};
stripePayment(body)
.then((res) => {
console.log("Res " + res);
})
.catch((err) => {
console.log("err" + err);
});
}
// this function makes api request to server for charging customer.
function stripePayment(body) {
return fetch(API_URL, {
method: "POST",
mode: "cors",
headers: {
"content-type": "application/json",
accept: "*/*",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "Allow",
},
body: JSON.stringify(body),
})
.then((response) => {
return response.json();
})
.catch((err) => {
console.log(err);
});
}
return (
<StripeCheckout
name="make Payment"
stripeKey={process.env.REACT_APP_STRIPE_PUBLIC_KEY}
token={doPayment}
amount={amount}
shippingAddress
billingAddress
>
<button className="buy-button">Buy Now</button>
</StripeCheckout>
);
}
|
959771b5e53a0a23e0cfcf0f9c1c5d3e1e165f1c
|
[
"JavaScript"
] | 1 |
JavaScript
|
vivekrao007/buy-with-stripe-react
|
d9560d749a91314c69a8f6359d331859d732461b
|
bcb6496e53178b0f8d70f7c57431064352a0b05b
|
refs/heads/master
|
<repo_name>frenchbread/tomatoo-blogging<file_sep>/core/templatetags/filtrs.py
from django import template
register = template.Library()
@register.filter(name='addcss')
def addcss(field, css):
return field.as_widget(attrs={'class': css})
@register.filter(name='ph')
def ph(field, ph):
return field.as_widget(attrs={'placeholder': ph})<file_sep>/core/urls.py
from django.conf import settings
from django.conf.urls.defaults import url, patterns, include
from django.contrib import admin
#from views import newpost, editpost, post
admin.autodiscover()
urlpatterns = patterns('core.views',
url(r'^$', 'hello_world', {}, name='home'),
url(r'^u/(?P<username>\w+)/$', 'profile', name="profile"),
url(r'^feed/$', 'feed', {}, name='feed'),
url(r'^saved/$', 'saved', {}, name='saved'),
url(r'^new/$', 'newpost', {}, name='newpost'),
url(r'^settings/$', 'settings', {}, name='settings'),
url(r'^post/(?P<post_id>\w+)/$', 'post', name='post'),
url(r'^post/(?P<post_id>\w+)/edit/$', 'editpost', name='editpost'),
url(r'^post/(?P<post_id>\w+)/delete/$', 'deletepost', name='deletepost'),
url(r'^post/(?P<target_id>\w+)/save', 'save', name="save"),
url(r'^post/(?P<target_id>\w+)/remove', 'remove', name="remove"),
url(r'^admin/', include(admin.site.urls)),
url(r'^comments/', include('django.contrib.comments.urls')),
)
if settings.DEBUG:
urlpatterns += patterns('django.views.generic.simple',
url(r'^500/$', 'direct_to_template', {'template': '500.html'}),
url(r'^404/$', 'direct_to_template', {'template': '404.html'}),
)
<file_sep>/core/templates/post.html
{% extends "main.html" %}
{% load comments %}
{% block body %}
<div class="row">
<div class="col-md-2">
</div>
<div class="col-md-8 rightpart">
<h1>
{{ p.title|capfirst }}
</h1>
<p>{{ p.body|linebreaks }}</p>
<hr/>
<div>
<a href="/u/{{ p.user }}">{{ p.user }}</a> posted <i class="text-muted"><span data-livestamp="{{ p.timestamp|date:"U" }}" ></span></i>
<span>
{% if p.user.username == user.username %}
|
<a class="btn btn-info btn-xs" href="/post/{{ p.pk }}/edit"><span class="glyphicon glyphicon-edit"></span> Edit</a>
<a class="btn btn-danger btn-xs" href="javascript:void(0);" onclick="deletepost('{{ p.id }}')"><span class="glyphicon glyphicon-trash"></span> Delete</a>
{% endif %}
</span>
<span id="this_p{{ p.pk }}">
{% if not user.is_authenticated %}
<a href="#" class="btn btn-primary btn-xs disabled" style="float:right">
<span class="glyphicon glyphicon-star-empty"></span> Save for later
</a>
{% elif l == 'save' %}
<a href="javascript:void(0);" class="btn btn-primary btn-xs" style="float:right" onclick="savee('{{ p.pk }}')" >
<span class="glyphicon glyphicon-star-empty"></span> Save for later
</a>
{% elif l == 'remove' %}
<a href="javascript:void(0);" class="btn btn-warning btn-xs" style="float:right" onclick="removee('{{ p.pk }}')" >
<span class="glyphicon glyphicon-star"></span> Saved
</a>
{% endif %}
</span>
</div>
<hr/>
<div >
{% if user.is_authenticated %}
{% get_comment_form for p as form %}
<form action="{% comment_form_target %}" method="POST">
<div class="comment_form">
{% csrf_token %}
{{ form.content_type }}
{{ form.object_pk }}
{{ form.timestamp }}
{{ form.security_hash }}
<input type="hidden" name="name" value="{{ user }}" />
<input type="hidden" name="next" value="/post/{{ p.pk }}" />
<div class="form-group">
<input type="text" name="comment" placeholder="Enter your comment here.." class="form-control"/>
</div>
<div class="form-group">
<input class="btn btn-default" type="submit" value="Add comment" id="id_submit" />
</div>
</div>
</form>
<hr/>
{% else %}
<p class="text-center">Please <a href="/accoutns/login">Login</a> to leave a comment.</p>
{% endif %}
{% get_comment_list for p as comment_list%}
{% if comment_list %}
{% for comment in comment_list reversed %}
<div>
<p><a href="/u/{{ comment.user }}"><b>{{ comment.user_name }}</b></a> <i><span class="thistime" data-livestamp="{{ comment.submit_date|date:"U" }}" ></span></i></p>
<p>{{ comment.comment }}</p>
<hr/>
</div>
{% endfor %}
{% else %}
<p class="text-center">No comments yet, be first!</p>
{% endif %}
</div>
<br/><br/>
</div>
<div class="col-md-2">
</div>
</div>
<script>
function deletepost(post_id){
var r = confirm("Are you sure that you want to delete this post?");
if (r == true) {
window.location = "/post/"+post_id+"/delete";
}
}
</script>
{% endblock %}
<file_sep>/core/templatetags/__init__.py
__author__ = 'muze'
<file_sep>/core/admin.py
from django.contrib import admin
from models import Post, Save
class PostAdmin(admin.ModelAdmin):
pass
admin.site.register(Post, PostAdmin)
class LikeAdmin(admin.ModelAdmin):
pass
admin.site.register(Save, LikeAdmin)
<file_sep>/core/forms.py
from models import Post
from django import forms
from django.contrib.auth.models import User
class PostForm(forms.ModelForm):
class Meta:
model = Post
exclude = ("user", "views")
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Title'}),
'body': forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Body'}),
}
class SettingsForm(forms.ModelForm):
class Meta:
model = User
exclude = {'password', 'is_active', 'is_staff', 'is_superuser', 'last_login', 'date_joined', 'groups', 'user_permissions', }
widgets = {
'username': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Username'}),
'first_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'First Name'}),
'last_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '<NAME>'}),
'email': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Email address'}),
}<file_sep>/core/models.py
from django.db import models
from time import time
from django.utils.timezone import now
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db.models import Count
def get_upload_place(instance, filename):
return "posts/%s/%s" % (instance.user, str(time()).replace('.', '_')+filename)
class SavedCount(models.Manager):
def get_query_set(self):
return super(SavedCount, self).get_query_set().annotate(saveThis=Count('save')).order_by('-timestamp')
class Post(models.Model):
user = models.ForeignKey(User)
title = models.CharField("Title", max_length=100)
body = models.TextField("Text", max_length=1000)
views = models.IntegerField(default=0)
timestamp = models.DateTimeField(auto_now_add=True)
with_saved = SavedCount()
objects = models.Manager() # default
def __unicode__(self):
return self.title
def get_absolute_url(self):
return reverse("post", kwargs={"pk": str(self.id)})
class Save(models.Model):
user = models.ForeignKey(User)
post = models.ForeignKey(Post)
def __unicode__(self):
return "%s saved %s" % (self.user.username, self.post.title)
<file_sep>/static/js/save.js
function savee(post_id){
$.get('/post/'+post_id+'/save', function(data) {
$("#this_p"+post_id).html('<a href="javascript:void(0);" class="btn btn-warning btn-xs" style="float:right" onclick="removee('+ post_id +')" ><span class="glyphicon glyphicon-star"></span> Saved </a>');
});
return false
}
function removee(post_id){
$.get('/post/'+post_id+'/remove', function(data) {
$("#this_p"+post_id).html('<a href="javascript:void(0);" class="btn btn-primary btn-xs" style="float:right" onclick="savee('+ post_id +')" ><span class="glyphicon glyphicon-star-empty"></span> Save for later </a>');
/*setTimeout(function(){
ui.notify(data)
.effect('slide');
});*/
});
return false
}<file_sep>/readme.md
Simple and nicely designed blogging platform written on Django.<file_sep>/core/views.py
from django.views.generic import TemplateView
from django.shortcuts import get_object_or_404, RequestContext, render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.core.context_processors import csrf
from models import Post, Save
from django.contrib.auth.models import User
from forms import PostForm, SettingsForm
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib.auth.decorators import login_required
from django.http import Http404
import urllib, hashlib
hello_world = TemplateView.as_view(template_name='hello-world.html')
def givemealinkforpic(email):
email = email
default = "http://www.genengnews.com/app_themes/genconnect/images/default_profile.jpg"
size = 100
gravatar_url = "http://www.gravatar.com/avatar/" + hashlib.md5(email.lower()).hexdigest() + "?"
gravatar_url += urllib.urlencode({'d':default, 's':str(size)})
return gravatar_url
@login_required
def feed(request):
args = {}
args.update(csrf(request))
p = Post.objects.all().order_by('-timestamp')
#pagination----------------------------------------------------------
paginator = Paginator(p, 5)
page = request.GET.get('page')
try:
p = paginator.page(page)
except PageNotAnInteger:
p = paginator.page(1)
except EmptyPage:
p = paginator.page(paginator.num_pages)
args.update({'p': p})
template = 'feed.html'
context = RequestContext(request)
return render_to_response(template, args, context_instance=context)
@login_required
def saved(request):
args = {}
args.update(csrf(request))
u = get_object_or_404(User, username=request.user.username)
p = Post.with_saved.filter(id__in=Save.objects.filter(user=u).values_list('post__id'))
#pagination----------------------------------------------------------
paginator = Paginator(p, 5)
page = request.GET.get('page')
try:
p = paginator.page(page)
except PageNotAnInteger:
p = paginator.page(1)
except EmptyPage:
p = paginator.page(paginator.num_pages)
args.update({'p': p})
template = 'saved.html'
context = RequestContext(request)
return render_to_response(template, args, context_instance=context)
@login_required
def newpost(request):
args = {}
args.update(csrf(request))
#making some fun stuff-----------------------------------------------
if request.POST:
form = PostForm(request.POST, request.FILES)
if form.is_valid():
form = form.save(commit=False)
form.user = request.user
form.save()
return HttpResponseRedirect(reverse('feed'))
else:
form = PostForm()
#packing bags and fly--------------------------------------------------
args.update({'form': form})
template = 'newpost.html'
context = RequestContext(request)
return render_to_response(template, args, context_instance=context)
def post(request, post_id):
args = {}
args.update(csrf(request))
#info gathering------------------------------------------------------
p = get_object_or_404(Post, id=post_id)
if request.user.is_authenticated():
try:
saved = Save.objects.get(user=request.user, post=p)
except:
saved = None
if not saved:
l = 'save'
else:
l = 'remove'
else:
l = None
#packing bags and fly--------------------------------------------------
args.update({'p': p, 'l': l})
template = 'post.html'
context = RequestContext(request)
return render_to_response(template, args, context_instance=context)
@login_required
def editpost(request, post_id):
args = {}
args.update(csrf(request))
#info gathering--------------------------------------------------------
p = get_object_or_404(Post, id=post_id, user=request.user)
#making some fun stuff-----------------------------------------------
if request.user == p.user:
if request.method == 'POST':
form = PostForm(request.POST, instance=p)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('post', kwargs={"post_id": post_id}))
else:
form = PostForm(instance=p)
else:
raise Http404
#packing bags and fly--------------------------------------------------
args.update({'form': form})
template = 'editpost.html'
context = RequestContext(request)
return render_to_response(template, args, context_instance=context)
@login_required
def deletepost(request, post_id):
args = {}
args.update(csrf(request))
p = get_object_or_404(Post, id=post_id, user=request.user)
p.delete()
return HttpResponseRedirect(reverse('feed'))
@login_required
def profile(request, username):
args = {}
args.update(csrf(request))
#info gathering------------------------------------------------------
thisUser = get_object_or_404(User, username=username)
p = Post.objects.filter(user=thisUser).order_by('-timestamp')
#pagination----------------------------------------------------------
paginator = Paginator(p, 5)
page = request.GET.get('page')
try:
p = paginator.page(page)
except PageNotAnInteger:
p = paginator.page(1)
except EmptyPage:
p = paginator.page(paginator.num_pages)
pic = givemealinkforpic(thisUser.email)
#packing bags and fly--------------------------------------------------
args.update({'thisuser': thisUser, 'p': p, 'pic': pic})
context = RequestContext(request)
template = "profile.html"
return render_to_response(template, args, context_instance=context)
@login_required
def save(request, target_id):
target = get_object_or_404(Post, id=target_id)
if target:
u = get_object_or_404(User, username=request.user.username)
prev_saved = Save.objects.filter(user=u, post=target)
has_saved = (len(prev_saved) > 0)
if not has_saved:
Save.objects.create(user=u, post=target)
else:
prev_saved[0].delete()
response = HttpResponse(mimetype="text/html")
response['content-type'] = "text/html; charset=UTF-8"
response.write('You saved post "%s"' % target.title)
return response
@login_required
def remove(request, target_id):
target = get_object_or_404(Post, id=target_id)
if target:
u = get_object_or_404(User, username=request.user.username)
prev_saved = Save.objects.filter(user=u, post=target)
has_saved = (len(prev_saved) > 0)
if not has_saved:
Save.objects.create(user=u, post=target)
else:
prev_saved[0].delete()
response = HttpResponse(mimetype="text/html")
response['content-type'] = "text/html; charset=UTF-8"
response.write('You removed post "%s"' % target.title)
return response
@login_required
def settings(request):
context_vars = {}
context_vars.update(csrf(request))
pic=givemealinkforpic(request.user.email)
if request.method == 'POST':
form = SettingsForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('profile', kwargs={"username": request.user.username}))
else:
form = SettingsForm(instance=request.user)
context_vars.update({'form': form, 'pic': pic})
template = 'settings.html'
context = RequestContext(request)
return render_to_response(template, context_vars, context_instance=context)
|
6b86599cc65df5cf838b3c67a26a3185c09a5960
|
[
"JavaScript",
"Python",
"HTML",
"Markdown"
] | 10 |
Python
|
frenchbread/tomatoo-blogging
|
dd57e52fdd9aa2d64f90fdde6c4ee7fccd8019db
|
14d7fb249925cea03f47e5f59cf28b9539915b04
|
refs/heads/master
|
<file_sep>import sys
user_input1 = input("Enter List1 with space in between numbers: ")
list1 = user_input1.split(" ")
user_input2 = input("Enter List2 with space in between numbers: ")
list2 = user_input2.split(" ")
def diff(l1, l2):
return[x for x in list2 if x not in list1] # Check values in List2 if in List1, returns difference
wholeSet = sorted(list1 + list2)
difSet = diff(list1, list2)
resultSet = diff(difSet, wholeSet)
print(resultSet)
<file_sep>import sys
word1 = str(input("Enter full word: "))
word2 = str(input("Enter partial string: "))
def compare_words(w1, w2):
comp_words = word2 in word1 # Check if the word1 is apart of word2 (case sensitive)
return comp_words
compResults = compare_words(word1, word2)
binaryVal = int(compResults) # Convert boolean function to int
print(f"Boolean is {compResults} and Value is equal of {binaryVal}")
<file_sep>import sys
phrase = str(input("Enter phrase or string to use: "))
insert_var = str(input("Enter variable to add: "))
def rev_function(x):
return x[::-1] # Return last char first
# Reverse phrase and insert A between words
rev_phrase = rev_function(phrase) # Reverse phrase
rev_phrase = rev_phrase.split(" ") # Split strings into list
phrase_A = 'A'.join(rev_phrase) # Join string with A in between
# Insert A to front and end of list
new_A_phrase = phrase_A.split(" ") # Split into list
new_A_phrase.insert(0, insert_var) # Add "A" in the front
new_A_phrase.append(insert_var) # Add "A" at the end
final_phrase = ''.join(new_A_phrase) # Join everything together
print(final_phrase) # Print result
<file_sep>import sys
# First Attempt #
finalList = []
lower = int(input()) # This is the lowest number of the list
upper = int(input()) # This is the highest number of the list
def sort_list(x, y):
for i in range(lower, upper):
if i % 2 == 0 or i % 7 == 0: # Check if the number is even or divisible by 7
finalList.append(i) # Add to list
return finalList # Return list
print(sort_list(lower, upper)) # Print all number in between in array
# Second Attempt #
lower_limit = int(input("enter lower limit: ")) # This is the lowest number of the list
upper_limit = int(input("enter upper limit: ")) # This is the highest number of the list
def sort_list2(ll, ul):
sorted_list = [x for x in range(lower_limit, upper_limit) if (x % 2 == 0 or x % 7 == 0)]
return sorted_list
print(sort_list2(lower_limit, upper_limit))
|
3e638f87521bffa785b371b031cb482546c1dae2
|
[
"Python"
] | 4 |
Python
|
alexandrehuynh/Metis-Challenge-Questions
|
66b9f322c7cda6412d05ddb9dcf810737750514a
|
8eb9c94295f32b7e4653cd3a6dcfe2f8f419a9b4
|
refs/heads/main
|
<file_sep>import { ComponentDisposer } from '../../utils/ComponentDisposer';
import Alert from './Alert';
const targets = Array.from(
document.querySelectorAll<HTMLButtonElement>('.js-alert')
);
const instances = targets.map((target) => new Alert(target));
module.hot.dispose(() => {
ComponentDisposer(instances);
});
export default instances;
<file_sep>import { ComponentDisposer } from '../../utils/ComponentDisposer';
import HelloWorld from './HelloWorld';
const targets = Array.from(
document.querySelectorAll<HTMLDivElement>('.js-hello-world')
);
const instances = targets.map((node) => new HelloWorld(node));
module.hot.dispose(() => {
ComponentDisposer(instances);
});
export default instances;
<file_sep>import { IDispose } from "../../utils/ComponentDisposer";
class Alert implements IDispose {
private _node: HTMLButtonElement;
constructor(node: HTMLButtonElement) {
this._node = node;
node.addEventListener('click', this.handleClick);
}
handleClick() {
alert('Alert! 🎉');
}
dispose() {
this._node.removeEventListener('click', this.handleClick);
}
}
export default Alert;
<file_sep>class Lazy {
constructor() {
console.log('Of toch niet?');
}
}
export default Lazy;
<file_sep>import { IDispose } from "../../utils/ComponentDisposer";
class HelloWorld implements IDispose {
private _rootElement: HTMLDivElement;
constructor(rootElement: HTMLDivElement) {
this._rootElement = rootElement;
this.init();
}
init() {
const name = this._rootElement.dataset.name;
const p = document.createElement('p');
p.textContent = `Goodbye ${name}!`;
this._rootElement.appendChild(p);
}
dispose(): void {
this._rootElement.innerHTML = '';
}
}
export default HelloWorld;
<file_sep>const { merge } = require('webpack-merge');
const { BundleStatsWebpackPlugin } = require('bundle-stats-webpack-plugin');
const common = require('./webpack.common.js');
module.exports = merge(common, {
mode: 'production',
entry: './src/scripts/main.ts',
plugins: [new BundleStatsWebpackPlugin()],
});
<file_sep>const browserSync = require('browser-sync');
const del = require('del');
const { src, dest, series, watch } = require('gulp');
const sass = require('gulp-dart-sass');
const ejs = require('gulp-ejs');
const prettier = require('gulp-prettier');
const sourcemaps = require('gulp-sourcemaps');
const rename = require('gulp-rename');
const webpack = require('webpack');
const webpackStream = require('webpack-stream');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const templateData = require('./src/data');
const ejsHelpers = require('./src/templates/helpers');
const webpackDevConfig = require('./webpack.dev.js');
const webpackProdConfig = require('./webpack.prod.js');
const devServer = browserSync.create();
const isProdMode = process.env.NODE_ENV === 'production';
const webpackConfig = isProdMode ? webpackProdConfig : webpackDevConfig;
const bundler = webpack(webpackConfig);
const paths = {
styles: {
entry: 'src/styles/main.scss',
dest: 'dist/styles/',
files: 'src/styles/**/*.scss',
},
scripts: {
entry: 'src/scripts/main.ts',
dest: 'dist/scripts/',
files: 'src/scripts/**/*.ts',
},
templates: {
entry: 'src/templates/index.ejs',
dest: 'dist/',
files: 'src/templates/**/*.ejs',
},
};
function clean() {
return del(['dist']);
}
function scripts() {
const config = isProdMode ? webpackProdConfig : webpackDevConfig;
return src(paths.scripts.entry)
.pipe(webpackStream(config, webpack))
.pipe(dest(paths.scripts.dest));
}
function styles() {
return src(paths.styles.entry)
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(
sass({
includePaths: ['node_modules'],
})
)
.pipe(sourcemaps.write('.', { addComment: false }))
.pipe(dest(paths.styles.dest))
.pipe(browserSync.stream());
}
// TODO: Make sure that the file is not cached.
function templates() {
return src(paths.templates.entry)
.pipe(ejs({ ...templateData, ...ejsHelpers }))
.pipe(rename({ extname: '.html' }))
.pipe(dest(paths.templates.dest));
}
function formatter() {
return src([paths.scripts.files, paths.styles.files])
.pipe(prettier())
.pipe(dest((file) => file.base));
}
function serve() {
devServer.init({
server: {
baseDir: 'dist'
},
middleware: [
webpackDevMiddleware(bundler, {
stats: { color: true },
writeToDisk: true
}),
webpackHotMiddleware(bundler),
],
});
watch(paths.styles.files, styles).on('change', devServer.reload);
watch(paths.templates.files, templates).on('change', devServer.reload);
}
exports.default = series(clean, scripts, templates, styles, serve);
exports.build = series(clean, formatter, scripts, templates, styles);
<file_sep>module.exports = {
name: 'Baardagaam',
};
<file_sep>import './components/HelloWorld';
import './components/Alert';
import './components/LazyLoaded';
if (module.hot) {
module.hot.accept();
}
<file_sep>export interface IDispose {
dispose(): void;
}
export function ComponentDisposer(instances: IDispose[]) {
instances.forEach(instance => instance.dispose());
}<file_sep>async function ComponentLoader<T>(
condition: boolean,
factory: () => Promise<{ default: T }>,
map: (constructor: T) => void
) {
if (condition) {
const component = await factory();
map(component.default);
}
}
export default ComponentLoader;
<file_sep>// TODO: Group manifest in chunks and entrypoints!
const renderScripts = () => {
const manifest = require('../../../dist/scripts/manifest.json');
return `<script src=${manifest['main.js']}></script>`;
};
module.exports = renderScripts;
<file_sep>import ComponentLoader from '../../utils/ComponentLoader';
const targets = Array.from(document.querySelectorAll('.js-lazy'));
export default ComponentLoader(
targets.length > 0,
() => import(/* webpackChunkName: "Lazy" */ './Lazy'),
(Component) => targets.map(() => new Component())
);
|
d27c446cd13c0a108c749871734f37f661182bd7
|
[
"JavaScript",
"TypeScript"
] | 13 |
TypeScript
|
jffr/baardagaam
|
350870e79a26b638d9ead65c62d1fb4b8a8bd880
|
75dcb882af3af936175f3d6af47c18d291e58b8c
|
refs/heads/master
|
<file_sep>import React from "react";
class TwitterMessage extends React.Component {
constructor() {
super();
this.state = {
value: '',
chars_left: 140
};
}
maxChars = event => {
var input = event.target.value;
this.setState({
chars_left: 140 - input.length,
value: event.target.value
});
}
render() {
return (
<div>
<strong>Your message:</strong>
<input
type="text"
value={this.state.value}
onChange={this.maxChars.bind(this)}
/>
<p>Characters Left: {this.state.chars_left}</p>
</div>
);
}
}
export default TwitterMessage;
<file_sep>import React from "react";
const isValid = poem => {
const rows = poem.split("\n").map(row => row.trim());
const correctLength = rows.length === 3;
if(poem && correctLength){
return(
rows[0].split(" ").length === 5 &&
rows[1].split(" ").length === 3 &&
rows[2].split(" ").length === 5
)
} else {
return false;
}
}
class PoemWriter extends React.Component {
constructor() {
super();
this.state = {
value: '',
valid: true
};
}
handleInputChange = event => {
this.setState({
value: event.target.value,
valid: isValid(event.target.value)
})
}
render() {
return (
<div>
<textarea
rows="3"
cols="60"
value={this.state.value}
onChange={this.handleInputChange} />
{!this.state.valid ?
(<div id="poem-validation-error" style={{ color: "red" }}>
This poem is not written in the right structure!
</div>) : null}
</div>
);
}
}
export default PoemWriter;
|
88488970ee200f987f2d10df9edbfcf9e1e90126
|
[
"JavaScript"
] | 2 |
JavaScript
|
aimeemcgrenera/react-forms-lab-v-000
|
759de7c10fc4fe98b7c3010534729e014fbc15f9
|
4032b8aeb46d0abf05a5c533d886d3c636335817
|
refs/heads/master
|
<repo_name>AngelinaT-t/BooleanRetrival_PostingLists<file_sep>/README.md
# Boolean Retrival(布尔检索) and Posting Lists(倒排索引表)
## 问题描述
>利用文档和词项的布尔关系建立倒排索引表,根据倒排索引表进行布尔表达式查询.这里只实现AND操作.
## 布尔检索
>布尔检索模型反应了文档和词项集合的关系
布尔检索模型为一个关于词项-文档关联的二维矩阵,其中每一行表示一个词(term),每列表示一个文档(document).当词t在文档d中存在时,矩阵元素(t,d)的值为1,否则为0

## 倒排索引
>每个词项都有一个记录出现该词项所有文档的列表,该表中的每个元素记录的时词项在某个文档中的一次出现信息(有时候还会包括词项在文档中出现的位置),这个表中的每个元素通常称为倒排记录(posting).每个词项对应的整个表称为倒排索引表(posting list).
<br>
* **建立过程**
1. 对每篇文档建立索引时的输入为一个归一化的词条表,也可以看成二元组(词项,文档ID)的一个列表
2. 将这个列表按照词项的字母顺序进行排序,其中一个词项在同一个文档的多次出现会合并在一起,最后整个结果分成词典和倒排记录表两个部分.
>* 由于一个词项通常会在多篇文档中出现,上述组织数据的方法实际上也已经减少了索引的存储空间.
>* 词典中同样可以记录一些统计信息,比如出现某词项的文档数目,即文档频率,这里也就是每个倒排记录表的长度,该信息对于一个基本的布尔搜索引擎来说不是必需的,但是它可以在处理查询时提高搜索效率.
>* 倒排索引表会按照docID进行排序,这对于高效查询时非常重要的基础,也是实现布尔计算的必要条件.
* **完整的倒排索引**<br>
<br>
* 数据结构<br>
建立map<String,Object>的数据结构保存字典。String为字典里唯一的term,一个Object对象包括频率freq(int)和对应的文档ID列表postingList(Arraylist).
* 初始化数据时可以选择建立布尔检索模型,也可以直接调用插入方法.这里我实现的是直接调用插入方法`Insert(term,documentID)`
public void Insert(String term,int docID) {//term为单词(索引),docID为所在文档
if(!dir.containsKey(term)) {//如果字典里没有这个单词,则直接加入
FreqAndId fId = new FreqAndId();//建立包含频率freq和postingList的对象
fId.addFreq();//freq设置为1
fId.adddocId(docID);//postingList加入docID
dir.put(term, fId);//和term一起加入到字典中,按照升序插入
}
else {//如果字典里包含了这个term
FreqAndId fId = dir.get(term);//获取这个term所对应的object信息
if(!fId.postingList.contains(docID)) {//是否已经包含这个docID,不包含则进入
fId.addFreq();//freq++
fId.adddocId(docID);//postingList加入新的docID
dir.put(term, fId);//新的信息插入时为替代原来的信息(map Key值唯一)
}
}
}
* 虽然TreeMap默认会对插入元素根据Key的值(也就是term)进行升序排序,但是索引建立过程中,或者说查找过程中会希望是忽略大小写的,所以在这里需要重写TreeMap的比较器
dir = new TreeMap<String,FreqAndId>(new Comparator<String>(){
public int compare(String o1, String o2) {
//如果有空值,直接返回0
o1 = o1.toLowerCase();//将term的值转成小写
o2 = o2.toLowerCase();
if (o1 == null || o2 == null)
return 0;
return String.valueOf(o1).compareTo(String.valueOf(o2));//然后进行比较
}
});
## 倒排记录表(posting list)的合并
倒排记录的表的合并(AND)实现了当一个词条包含多个关键词(term)时,可以检索得到包含所有关键词的文档,也就是求倒排记录表的交集;以此类推,OR操作即求并集,可以检索包含一个或多个关键词的文档.求补集的操作则可以过滤包含某关键词的文档.
* 合并算法 `Intersection(String, String)`<br>
<br>
## 实现结果<br>
<file_sep>/BoolRetrival.java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Formatter;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class BoolRetrival {
class FreqAndId{
private int freq;
private List<Integer> postingList;
public FreqAndId() {
// TODO Auto-generated constructor stub
freq = 0;
postingList = new ArrayList<Integer>();
}
private void addFreq() {
freq ++;
}
private void adddocId(int id) {
postingList.add(id);
postingList.sort(null);
}
}
public Map<String,FreqAndId> dir;
static Formatter formatter = new Formatter(System.out);
public BoolRetrival() {
// TODO Auto-generated constructor stub
dir = new TreeMap<String,FreqAndId>(new Comparator<String>(){
public int compare(String o1, String o2) {
//如果有空值,直接返回0
o1 = o1.toLowerCase();//将term的值转成小写
o2 = o2.toLowerCase();
if (o1 == null || o2 == null)
return 0;
return String.valueOf(o1).compareTo(String.valueOf(o2));//然后进行比较
}
});
}
public void Insert(String term,int docID) {//term为单词(索引),docID为所在文档
if(!dir.containsKey(term)) {//如果字典里没有这个单词,则直接加入
FreqAndId fId = new FreqAndId();//建立包含频率freq和postingList的对象
fId.addFreq();//freq设置为1
fId.adddocId(docID);//postingList加入docID
dir.put(term, fId);//和term一起加入到字典中,按照升序插入
}
else {//如果字典里包含了这个term
FreqAndId fId = dir.get(term);//获取这个term所对应的object信息
if(!fId.postingList.contains(docID)) {//是否已经包含这个docID,不包含则进入
fId.addFreq();//freq++
fId.adddocId(docID);//postingList加入新的docID
dir.put(term, fId);//新的信息插入时为替代原来的信息(map Key值唯一)
}
}
}
public void Intersection(String t1,String t2) {
int i,j;
FreqAndId fid1 = dir.get(t1);//根据term值获取map中对应的value值,返回为一个Object
FreqAndId fid2 = dir.get(t2);//
List<Integer> l1 = fid1.freq > fid2.freq //较长的List命名为L1
? fid1.postingList : fid2.postingList;
List<Integer> l2 = fid1.freq < fid2.freq //较短的List命名为L2
? fid1.postingList : fid2.postingList;
List<Integer> list = new ArrayList<Integer>();//保存合并的结果
int len1 = l1.size(); //object的freq属性代表着postingList的长度
int len2 = l2.size();
for(i = 0,j = 0; i<len1 && j<len2;) {//直到遍历完其中一个postingList
while(l1.get(i) < l2.get(j)) {//找到l1第一个大于等于l2当前元素的位置
i++;
}
int id1 = l1.get(i);
int id2 = l2.get(j);
//System.out.println("i = "+l1.get(i)+" j = "+l2.get(j));
if( id1 == id2 ) {
list.add(id2);//相等则加入合并列表
i++; //L1,L2均取下一个元素
j++;
//System.out.println("i = "+l1.get(i)+" j = "+l2.get(j));
}
else if( id1 > id2 ){
j++;//大于则找到L2下一个比L1当前元素大于等于的元素
}
}
System.out.print("Intersection: ");
for (int tmp : list) { //输出结果
System.out.print("-->"+tmp);
}
}
public void print() {
formatter.format("%-10s %-10s %-10s\n", "term", "doc.freq", "posting lists");
for (String s : dir.keySet()) {
formatter.format("%-15s",s);
FreqAndId fId = dir.get(s);
formatter.format("%-10s",fId.freq);
for (int tmp : fId.postingList) {
System.out.print("-->");
formatter.format("%-1s",tmp);
}
System.out.println("");
}
}
public static void main(String[] args) {
BoolRetrival br = new BoolRetrival();
br.Insert("I",1);
br.Insert("did",1);
br.Insert("enact",1);
br.Insert("julius",1);
br.Insert("caesar",1);
br.Insert("I",1);
br.Insert("was",1);
br.Insert("killed",1);
br.Insert("i'",1);
br.Insert("the",1);
br.Insert("capital",1);
br.Insert("brutus",1);
br.Insert("killed",1);
br.Insert("me",1);
br.Insert("so",2);
br.Insert("let",2);
br.Insert("it",2);
br.Insert("be",2);
br.Insert("with",2);
br.Insert("caesar",2);
br.Insert("the",2);
br.Insert("noble",2);
br.Insert("brutus",2);
br.Insert("hath",2);
br.Insert("told",2);
br.Insert("you",2);
br.Insert("caesar",2);
br.Insert("was",2);
br.Insert("ambitious",2);
br.print();
br.Insert("Brutus",1);
br.Insert("Brutus",2);
br.Insert("Brutus",4);
br.Insert("Brutus",11);
br.Insert("Brutus",31);
br.Insert("Brutus",45);
br.Insert("Brutus",173);
br.Insert("Brutus",174);
br.Insert("Calpurnia",2);
br.Insert("Calpurnia",31);
br.Insert("Calpurnia",54);
br.Insert("Calpurnia",101);
//br.print();
//br.Intersection("brutus","Calpurnia");
}
}
|
06de07f5ef34e806c4b88d10e056081b0cbcab19
|
[
"Markdown",
"Java"
] | 2 |
Markdown
|
AngelinaT-t/BooleanRetrival_PostingLists
|
e03c602facb9142e16eacf1c43d73d90ad92be46
|
3fca5b1ae990eef9034ef889acc797eb9a1497ae
|
refs/heads/master
|
<file_sep>fun main(args: Array<String>) {
println("Hello, Kotlin JS!")
}<file_sep>Kotlin JS Hello World Demo
==========================
This project is created by IDEA.
`Build` -> `Build Project` will compile `src/*.kt` to javascript files in `out/`.
Open `index.html` to run the javascript code.
How to debug the Kotlin code
----------------------------
- Must use IDEA Ultimate. (IDEA CE doesn't support it)
- Enable IDEA source map: `Kotlin Compiler` -> `Kotlin to Javascript` -> `Generate Source Map`
- Install chrome extension: <https://chrome.google.com/webstore/detail/jetbrains-ide-support/hmhgeddbohgjknpmjagkdomcpobmllji>
- Right click `index.html`, `debug` the html page
|
da15b45a43a76e0ed33bcd530e728ffc2e92dfd0
|
[
"Markdown",
"Kotlin"
] | 2 |
Kotlin
|
freewind-demos/idea-kotlin-js-hello-world-demo
|
86d0bf0663ab12c3d39411bb4fc3ed6a8d5f1637
|
86b79f761487d3b1e7bb2e89f058d824db72c638
|
refs/heads/master
|
<file_sep><?php
/**
* Plugin Name: JSON Basic Authentication
* Description: Basic Authentication handler for the JSON API, used for development and debugging purposes
* Author: WordPress API Team
* Author URI: https://github.com/WP-API
* Version: 0.1
* Plugin URI: https://github.com/WP-API/Basic-Auth
*/
function json_basic_auth_handler($user) {
global $wp_json_basic_auth_error;
$wp_json_basic_auth_error = null;
/**
* Don't authenticate twice if X-WP-FORCE-REAUTH header is not set or if it is false
* This allow you to re-authenticate user which might be required when working with node-wpapi
* (such as in case of allowing user to change his password using REST API)
*/
$forceReauth = (isset($_SERVER['HTTP_X_WP_FORCE_REAUTH']) && $_SERVER['HTTP_X_WP_FORCE_REAUTH']);
if (!empty($user) && !$forceReauth) {
return $user;
}
// Check that we're trying to authenticate
if (!isset($_SERVER['PHP_AUTH_USER'])) {
return $user;
}
$username = $_SERVER['PHP_AUTH_USER'];
$password = <PASSWORD>['<PASSWORD>'];
/**
* In multi-site, wp_authenticate_spam_check filter is run on authentication. This filter calls
* get_currentuserinfo which in turn calls the determine_current_user filter. This leads to infinite
* recursion and a stack overflow unless the current function is removed from the determine_current_user
* filter during authentication.
*/
remove_filter('determine_current_user', 'json_basic_auth_handler', 10);
$user = wp_authenticate($username, $password);
add_filter('determine_current_user', 'json_basic_auth_handler', 10);
if (is_wp_error($user)) {
$wp_json_basic_auth_error = $user;
return null;
}
$wp_json_basic_auth_error = true;
return $user->ID;
}
add_filter('determine_current_user', 'json_basic_auth_handler', 10);
function json_basic_auth_error($error) {
// Passthrough other errors
if (!empty($error)) {
return $error;
}
global $wp_json_basic_auth_error;
return $wp_json_basic_auth_error;
}
add_filter('rest_authentication_errors', 'json_basic_auth_error');
|
2a950c3b6d68fad4b10066b0d79da994562f2472
|
[
"PHP"
] | 1 |
PHP
|
ashucg/Basic-Auth
|
020237598089cc9d859b053f891b4343bf50de35
|
ed2f8b1d22b8e0bd82036345c2533943eab001c0
|
refs/heads/trunk
|
<file_sep># $NetBSD: Makefile,v 1.5 2019/05/07 08:50:36 adam Exp $
DISTNAME= certbot-nginx-0.34.1
PKGNAME= ${PYPKGPREFIX}-${DISTNAME}
CATEGORIES= security python
MASTER_SITES= ${MASTER_SITE_PYPI:=c/certbot-nginx/}
COMMENT= Nginx plugin for Certbot
MAINTAINER= <EMAIL>
HOMEPAGE= https://github.com/certbot/certbot
LICENSE= apache-2.0
DEPENDS+= ${PYPKGPREFIX}-OpenSSL-[0-9]*:../../security/py-OpenSSL
DEPENDS+= ${PYPKGPREFIX}-acme>=0.29.0:../../security/py-acme
DEPENDS+= ${PYPKGPREFIX}-certbot>=0.34.0:../../security/py-certbot
DEPENDS+= ${PYPKGPREFIX}-mock-[0-9]*:../../devel/py-mock
DEPENDS+= ${PYPKGPREFIX}-pyparsing>=1.5.5:../../devel/py-pyparsing
DEPENDS+= ${PYPKGPREFIX}-setuptools-[0-9]*:../../devel/py-setuptools
DEPENDS+= ${PYPKGPREFIX}-ZopeInterface-[0-9]*:../../devel/py-ZopeInterface
USE_LANGUAGES= # none
.include "../../lang/python/egg.mk"
.include "../../mk/bsd.pkg.mk"
<file_sep>$NetBSD: patch-deps_openssl_openssl_crypto_init.c,v 1.1 2019/03/23 11:15:18 tsutsui Exp $
- pull fix from https://github.com/nodejs/node/pull/21848/commits/9868d403221bc9d566cb88a37510a182b7fbad3b
- apply similar ifdefs for NetBSD as FreeBSD and OpenBSD
--- deps/openssl/openssl/crypto/init.c.orig 2019-03-05 15:16:27.000000000 +0000
+++ deps/openssl/openssl/crypto/init.c
@@ -121,7 +121,8 @@ DEFINE_RUN_ONCE_STATIC(ossl_init_load_cr
#ifdef OPENSSL_INIT_DEBUG
fprintf(stderr, "OPENSSL_INIT: ossl_init_load_crypto_nodelete()\n");
#endif
-#if !defined(OPENSSL_NO_DSO) && !defined(OPENSSL_USE_NODELETE)
+#if defined(OPENSSL_NO_STATIC_ENGINE) && \
+ !defined(OPENSSL_NO_DSO) && !defined(OPENSSL_USE_NODELETE)
# ifdef DSO_WIN32
{
HMODULE handle = NULL;
@@ -285,7 +286,7 @@ DEFINE_RUN_ONCE_STATIC(ossl_init_engine_
return 1;
}
# if !defined(OPENSSL_NO_HW) && \
- (defined(__OpenBSD__) || defined(__FreeBSD__) || defined(HAVE_CRYPTODEV))
+ (defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(HAVE_CRYPTODEV))
static CRYPTO_ONCE engine_cryptodev = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(ossl_init_engine_cryptodev)
{
@@ -616,7 +617,7 @@ int OPENSSL_init_crypto(uint64_t opts, c
&& !RUN_ONCE(&engine_openssl, ossl_init_engine_openssl))
return 0;
# if !defined(OPENSSL_NO_HW) && \
- (defined(__OpenBSD__) || defined(__FreeBSD__) || defined(HAVE_CRYPTODEV))
+ (defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(HAVE_CRYPTODEV))
if ((opts & OPENSSL_INIT_ENGINE_CRYPTODEV)
&& !RUN_ONCE(&engine_cryptodev, ossl_init_engine_cryptodev))
return 0;
@@ -666,7 +667,8 @@ int OPENSSL_atexit(void (*handler)(void)
{
OPENSSL_INIT_STOP *newhand;
-#if !defined(OPENSSL_NO_DSO) && !defined(OPENSSL_USE_NODELETE)
+#if defined(OPENSSL_NO_STATIC_ENGINE) && \
+ !defined(OPENSSL_NO_DSO) && !defined(OPENSSL_USE_NODELETE)
{
union {
void *sym;
<file_sep># $NetBSD: Makefile,v 1.10 2019/04/25 07:33:12 maya Exp $
#
DISTNAME= nicovideo-dl-0.0.20190126
PKGREVISION= 1
CATEGORIES= net
MASTER_SITES= ${MASTER_SITE_OSDN:=nicovideo-dl/70568/}
MAINTAINER= <EMAIL>
HOMEPAGE= http://osdn.jp/projects/nicovideo-dl/
COMMENT= Download videos from www.nicovideo.jp
LICENSE= mit
USE_LANGUAGES= # none
NO_BUILD= yes
PYTHON_VERSIONS_INCOMPATIBLE= 27
DEPENDS+= ${PYPKGPREFIX}-expat-[0-9]*:../../textproc/py-expat
INSTALLATION_DIRS= bin
REPLACE_PYTHON+= nicovideo-dl
do-install:
${INSTALL_SCRIPT} ${WRKSRC}/nicovideo-dl ${DESTDIR}${PREFIX}/bin
.include "../../lang/python/application.mk"
.include "../../mk/bsd.pkg.mk"
<file_sep>$NetBSD: patch-clang__delta_ExpressionDetector.cpp,v 1.1 2018/12/12 12:44:43 adam Exp $
Fix for LLVM 7.0.
https://github.com/csmith-project/creduce/tree/llvm-7.0
--- clang_delta/ExpressionDetector.cpp.orig 2018-12-12 12:34:31.000000000 +0000
+++ clang_delta/ExpressionDetector.cpp
@@ -63,7 +63,8 @@ public:
StringRef FileName, bool IsAngled,
CharSourceRange FilenameRange, const FileEntry *File,
StringRef SearchPath, StringRef RelativePath,
- const Module *Imported) override;
+ const Module *Imported,
+ SrcMgr::CharacteristicKind FileType) override;
private:
SourceManager &SrcManager;
@@ -83,7 +84,8 @@ void IncludesPPCallbacks::InclusionDirec
const FileEntry * /*File*/,
StringRef /*SearchPath*/,
StringRef /*RelativePath*/,
- const Module * /*Imported*/)
+ const Module * /*Imported*/,
+ SrcMgr::CharacteristicKind /*FileType*/)
{
if (!SrcManager.isInMainFile(HashLoc))
return;
<file_sep>$NetBSD: patch-cmake_Modules_FindMySQL.cmake,v 1.1 2018/09/25 12:59:26 wiz Exp $
Fix detection of mysql library.
--- cmake/Modules/FindMySQL.cmake.orig 2013-09-14 10:09:01.000000000 +0000
+++ cmake/Modules/FindMySQL.cmake
@@ -21,7 +21,7 @@ FIND_PATH(MySQL_INCLUDE_DIR
# Library
#SET(MySQL_NAMES mysqlclient mysqlclient_r)
-SET(MySQL_NAMES mysqlclient_r)
+SET(MySQL_NAMES mysqlclient_r mysqlclient)
FIND_LIBRARY(MySQL_LIBRARY
NAMES ${MySQL_NAMES}
PATHS /usr/lib /usr/local/lib
<file_sep># $NetBSD: Makefile,v 1.21 2018/11/14 22:21:15 kleink Exp $
GST_PLUGINS1_NAME= pango
GST_PLUGINS1_DIRS= ext/pango
GST_PLUGINS1_FLAGS= pango
PKGREVISION= 2
.include "../../multimedia/gst-plugins1-base/Makefile.common"
.include "../../devel/pango/buildlink3.mk"
.include "../../mk/bsd.pkg.mk"
<file_sep># $NetBSD: buildlink3.mk,v 1.1 2019/03/19 10:07:47 jaapb Exp $
BUILDLINK_TREE+= ocaml-core_kernel
.if !defined(OCAML_CORE_KERNEL_BUILDLINK3_MK)
OCAML_CORE_KERNEL_BUILDLINK3_MK:=
BUILDLINK_API_DEPENDS.ocaml-core_kernel+= ocaml-core_kernel>=0.12.0
BUILDLINK_PKGSRCDIR.ocaml-core_kernel?= ../../devel/ocaml-core_kernel
.endif # OCAML_CORE_KERNEL_BUILDLINK3_MK
BUILDLINK_TREE+= -ocaml-core_kernel
<file_sep># $NetBSD: Makefile,v 1.3 2019/04/26 15:33:08 schmonz Exp $
PKGNAME= lld-7.0.1
PKGREVISION= 1
DISTNAME= ${PKGNAME_NOREV}.src
CATEGORIES= devel
MASTER_SITES= http://llvm.org/releases/${PKGVERSION_NOREV}/
EXTRACT_SUFX= .tar.xz
DISTFILES= ${DEFAULT_DISTFILES}
MAINTAINER= <EMAIL>
HOMEPAGE= http://lld.llvm.org/
COMMENT= The LLVM Linker
LICENSE= modified-bsd
USE_LANGUAGES= c c++11
USE_CMAKE= yes
GCC_REQD+= 4.8
CONFIGURE_DIRS= ${WRKDIR}/build
CMAKE_ARG_PATH= ${WRKSRC}
CMAKE_ARGS+= -DCMAKE_BUILD_TYPE=Release
CMAKE_ARGS+= -DCMAKE_C_COMPILER=${CC:Q}
CMAKE_ARGS+= -DCMAKE_CXX_COMPILER=${CXX:Q}
PYTHON_FOR_BUILD_ONLY= yes
post-extract:
${MKDIR} ${WRKDIR}/build
.include "options.mk"
.include "../../lang/python/tool.mk"
.include "../../lang/llvm/buildlink3.mk"
.include "../../mk/bsd.pkg.mk"
<file_sep># $NetBSD: Makefile,v 1.2 2019/02/27 10:46:16 maya Exp $
DISTNAME= zig-0.3.0+c59ce046
PKGNAME= zig-0.3.0.20190227
CATEGORIES= lang
MASTER_SITES= https://ziglang.org/builds/
EXTRACT_SUFX= .tar.xz
MAINTAINER= <EMAIL>
HOMEPAGE= https://ziglang.org/
COMMENT= Programming language designed for robustness and clarity
LICENSE= mit
USE_CMAKE= yes
USE_LANGUAGES= c c++
CHECK_PORTABILITY_SKIP+= ci/azure/macos_script
BUILDLINK_TRANSFORM+= rm:-Werror
.include "../../lang/clang/buildlink3.mk"
.include "../../lang/llvm/buildlink3.mk"
# Using builtin lld
#.include "../../devel/lld/buildlink3.mk"
.include "../../mk/bsd.pkg.mk"
<file_sep># $NetBSD: Makefile,v 1.1 2019/04/11 20:56:34 nia Exp $
PKGNAME= etlegacy-2.76
CATEGORIES= games
DIST_SUBDIR= etlegacy-${PKGVERSION_NOREV}
DISTFILES+= etlegacy.tar.gz
DISTFILES+= etlegacy-libs.tar.gz
LIBS_TAG= f04f846898a92d36fd9cfe7425b1ab4d31bca794
SITES.etlegacy.tar.gz= \
-https://github.com/etlegacy/etlegacy/archive/v${PKGVERSION_NOREV}.tar.gz
SITES.etlegacy-libs.tar.gz= \
-https://github.com/etlegacy/etlegacy-libs/archive/${LIBS_TAG}.tar.gz
MAINTAINER= <EMAIL>
HOMEPAGE= https://www.etlegacy.com/
COMMENT= Open source Wolfenstein: Enemy Territory client and server
LICENSE= gnu-gpl-v3
USE_CMAKE= yes
USE_LANGUAGES= c c++
CMAKE_ARGS+= -DBUNDLED_CURL=OFF
CMAKE_ARGS+= -DBUNDLED_FREETYPE=OFF
CMAKE_ARGS+= -DBUNDLED_GLEW=OFF
CMAKE_ARGS+= -DBUNDLED_JPEG=OFF
CMAKE_ARGS+= -DBUNDLED_LUA=OFF
CMAKE_ARGS+= -DBUNDLED_OGG_VORBIS=OFF
CMAKE_ARGS+= -DBUNDLED_OPENAL=OFF
CMAKE_ARGS+= -DBUNDLED_OPENSSL=OFF
CMAKE_ARGS+= -DBUNDLED_SDL=OFF
CMAKE_ARGS+= -DBUNDLED_SQLITE3=OFF
CMAKE_ARGS+= -DBUNDLED_THEORA=OFF
CMAKE_ARGS+= -DBUNDLED_ZLIB=OFF
CMAKE_ARGS+= -DCROSS_COMPILE32=OFF
CMAKE_ARGS+= -DFEATURE_AUTOUPDATE=OFF
CMAKE_ARGS+= -DFEATURE_OMNIBOT=OFF
CMAKE_ARGS+= -DINSTALL_OMNIBOT=OFF
CMAKE_ARGS+= -DFEATURE_OPENAL=ON
CMAKE_ARGS+= -DCMAKE_BUILD_TYPE="Release"
CMAKE_ARGS+= -DINSTALL_DEFAULT_BASEDIR="${PREFIX}/share/etlegacy"
CMAKE_ARGS+= -DINSTALL_DEFAULT_BINDIR="bin"
CMAKE_ARGS+= -DINSTALL_DEFAULT_MODDIR="share/etlegacy"
CFLAGS+= -DIOAPI_NO_64
CHECK_PORTABILITY_SKIP+= libs/sdl2/build-scripts/*
post-extract:
${MV} ${WRKDIR}/etlegacy-libs-${LIBS_TAG}/* \
${WRKDIR}/etlegacy-${PKGVERSION_NOREV}/libs
.include "options.mk"
.include "../../audio/openal-soft/buildlink3.mk"
.include "../../graphics/glew/buildlink3.mk"
.include "../../graphics/glu/buildlink3.mk"
.include "../../graphics/hicolor-icon-theme/buildlink3.mk"
.include "../../graphics/MesaLib/buildlink3.mk"
.include "../../devel/SDL2/buildlink3.mk"
.include "../../devel/zlib/buildlink3.mk"
.include "../../x11/libX11/buildlink3.mk"
.include "../../x11/libICE/buildlink3.mk"
BUILDLINK_TRANSFORM+= rm:-ldl
.include "../../mk/dlopen.buildlink3.mk"
.include "../../mk/jpeg.buildlink3.mk"
.include "../../mk/pthread.buildlink3.mk"
.include "../../mk/bsd.pkg.mk"
<file_sep># $NetBSD: Makefile,v 1.1 2019/03/13 11:50:24 jaapb Exp $
GITHUB_PROJECT= time_now
GITHUB_TAG= v${PKGVERSION_NOREV}
DISTNAME= ${GITHUB_PROJECT}-0.12.0
PKGNAME= ocaml-${DISTNAME}
CATEGORIES= time
MASTER_SITES= ${MASTER_SITE_GITHUB:=janestreet/}
MAINTAINER= <EMAIL>
HOMEPAGE= https://github.com/janestreet/time_now/
COMMENT= Library that reports the current time
LICENSE= mit
OCAML_USE_DUNE= yes
.include "../../mk/ocaml.mk"
.include "../../devel/ocaml-base/buildlink3.mk"
.include "../../devel/ocaml-jane-street-headers/buildlink3.mk"
.include "../../devel/ocaml-jst-config/buildlink3.mk"
.include "../../devel/ocaml-ppx_base/buildlink3.mk"
.include "../../devel/ocaml-ppx_optcomp/buildlink3.mk"
.include "../../mk/bsd.pkg.mk"
<file_sep># $NetBSD: version.mk,v 1.2 2018/09/15 03:06:15 ryoon Exp $
GCC8_DIST_VERSION:= 8.2.0
<file_sep># $NetBSD: Makefile,v 1.7 2018/11/16 14:56:27 kleink Exp $
DISTNAME= Flask-FlatPages-0.7.0
PKGNAME= ${PYPKGPREFIX}-${DISTNAME:tl}
CATEGORIES= www python
MASTER_SITES= ${MASTER_SITE_PYPI:=F/Flask-FlatPages/}
MAINTAINER= <EMAIL>
HOMEPAGE= https://github.com/SimonSapin/Flask-FlatPages
COMMENT= Provides flat static pages to a Flask application
LICENSE= modified-bsd
USE_LANGUAGES= # empty
DEPENDS+= ${PYPKGPREFIX}-flask>=1.0:../../www/py-flask
DEPENDS+= ${PYPKGPREFIX}-markdown>=2.5:../../textproc/py-markdown
DEPENDS+= ${PYPKGPREFIX}-yaml>=3.10:../../textproc/py-yaml
.include "../../lang/python/egg.mk"
.include "../../mk/bsd.pkg.mk"
<file_sep># $NetBSD: buildlink3.mk,v 1.1 2019/03/12 17:41:27 jaapb Exp $
BUILDLINK_TREE+= ocaml-fmt
.if !defined(OCAML_FMT_BUILDLINK3_MK)
OCAML_FMT_BUILDLINK3_MK:=
BUILDLINK_API_DEPENDS.ocaml-fmt+= ocaml-fmt>=0.8.5
BUILDLINK_PKGSRCDIR.ocaml-fmt?= ../../devel/ocaml-fmt
.endif # OCAML_FMT_BUILDLINK3_MK
BUILDLINK_TREE+= -ocaml-fmt
<file_sep># $NetBSD: options.mk,v 1.1 2019/05/03 17:14:27 nia Exp $
PKG_OPTIONS_VAR= PKG_OPTIONS.inspircd
PKG_SUPPORTED_OPTIONS= gnutls geoip openssl mysql mbedtls ldap pcre pgsql sqlite3
PKG_SUGGESTED_OPTIONS= gnutls
PLIST_VARS+= gnutls geoip openssl mysql mbedtls ldap pcre pgsql sqlite3
.include "../../mk/bsd.options.mk"
.if !empty(PKG_OPTIONS:Mgeoip)
PLIST.geoip= yes
INSPIRCD_EXTRAS_ON+= m_geo_maxmind.cpp
.include "../../geography/libmaxminddb/buildlink3.mk"
.else
INSPIRCD_EXTRAS_OFF+= m_geo_maxmind.cpp
.endif
.if !empty(PKG_OPTIONS:Mgnutls)
PLIST.gnutls= yes
INSPIRCD_EXTRAS_ON+= m_ssl_gnutls.cpp
.include "../../security/gnutls/buildlink3.mk"
.else
INSPIRCD_EXTRAS_OFF+= m_ssl_gnutls.cpp
.endif
.if !empty(PKG_OPTIONS:Mopenssl)
PLIST.openssl= yes
INSPIRCD_EXTRAS_ON+= m_ssl_openssl.cpp
.include "../../security/openssl/buildlink3.mk"
.else
INSPIRCD_EXTRAS_OFF+= m_ssl_openssl.cpp
.endif
.if !empty(PKG_OPTIONS:Mmbedtls)
PLIST.mbedtls= yes
INSPIRCD_EXTRAS_ON+= m_ssl_mbedtls.cpp
.include "../../security/mbedtls/buildlink3.mk"
.else
INSPIRCD_EXTRAS_OFF+= m_ssl_mbedtls.cpp
.endif
.if !empty(PKG_OPTIONS:Mmysql)
PLIST.mysql= yes
INSPIRCD_EXTRAS_ON+= m_mysql.cpp
.include "../../mk/mysql.buildlink3.mk"
.else
INSPIRCD_EXTRAS_OFF+= m_mysql.cpp
.endif
.if !empty(PKG_OPTIONS:Mldap)
PLIST.ldap= yes
INSPIRCD_EXTRAS_ON+= m_mysql.cpp
.include "../../databases/openldap-client/buildlink3.mk"
.else
INSPIRCD_EXTRAS_OFF+= m_mysql.cpp
.endif
.if !empty(PKG_OPTIONS:Mpcre)
PLIST.pcre= yes
INSPIRCD_EXTRAS_ON+= m_regex_pcre.cpp
.include "../../devel/pcre/buildlink3.mk"
.else
INSPIRCD_EXTRAS_OFF+= m_regex_pcre.cpp
.endif
.if !empty(PKG_OPTIONS:Mpgsql)
PLIST.pgsql= yes
INSPIRCD_EXTRAS_ON+= m_pgsql.cpp
.include "../../mk/pgsql.buildlink3.mk"
.else
INSPIRCD_EXTRAS_OFF+= m_pgsql.cpp
.endif
.if !empty(PKG_OPTIONS:Msqlite3)
PLIST.sqlite3= yes
INSPIRCD_EXTRAS_ON+= m_sqlite3.cpp
.include "../../databases/sqlite3/buildlink3.mk"
.else
INSPIRCD_EXTRAS_OFF+= m_sqlite3.cpp
.endif
<file_sep>$NetBSD: patch-src_effects_Effect.cpp,v 1.2 2019/02/10 17:14:42 nia Exp $
SunOS needs alloca.h for alloca().
--- src/effects/Effect.cpp.orig 2018-02-14 07:11:20.000000000 +0000
+++ src/effects/Effect.cpp
@@ -61,6 +61,10 @@ greater use in future.
#include <Cocoa/Cocoa.h>
#endif
+#ifdef __sun
+#include <alloca.h>
+#endif
+
#include "../Experimental.h"
#include "../commands/ScreenshotCommand.h"
<file_sep># $NetBSD: Makefile,v 1.34 2018/12/30 14:47:04 maya Exp $
DISTNAME= SDL2-2.0.9
PKGREVISION= 2
CATEGORIES= devel
MASTER_SITES= http://www.libsdl.org/release/
MAINTAINER= <EMAIL>
HOMEPAGE= http://www.libsdl.org/
COMMENT= Simple DirectMedia Layer is a cross-platform multimedia library
LICENSE= zlib
USE_LANGUAGES= c c++
USE_LIBTOOL= yes
USE_TOOLS+= gmake pkg-config autoconf automake autoreconf
GNU_CONFIGURE= yes
PKGCONFIG_OVERRIDE+= sdl2.pc.in
CONFIGURE_ENV+= SDL_RLD_FLAGS="${COMPILER_RPATH_FLAG}${PREFIX}/lib \
${COMPILER_RPATH_FLAG}${X11BASE}/lib"
CHECK_PORTABILITY_SKIP+=build-scripts/androidbuildlibs.sh
CHECK_PORTABILITY_SKIP+=build-scripts/iosbuild.sh
.include "../../mk/bsd.prefs.mk"
.if ${OPSYS} != "Linux"
BUILDLINK_TRANSFORM+= rm:-ldl
.endif
CFLAGS+= -DPREFIX=\"${PREFIX}\"
.include "options.mk"
.include "../../converters/libiconv/buildlink3.mk"
.include "../../mk/libusb.buildlink3.mk"
.include "../../mk/dlopen.buildlink3.mk"
.include "../../mk/pthread.buildlink3.mk"
.include "../../mk/bsd.pkg.mk"
<file_sep>$NetBSD: patch-mesonbuild_minstall.py,v 1.2 2019/03/05 16:30:18 prlw1 Exp $
Don't touch rpath.
--- mesonbuild/minstall.py.orig 2019-01-23 16:46:09.000000000 +0000
+++ mesonbuild/minstall.py
@@ -476,15 +476,6 @@ class Installer:
print("Symlink creation does not work on this platform. "
"Skipping all symlinking.")
printed_symlink_error = True
- if os.path.isfile(outname):
- try:
- depfixer.fix_rpath(outname, install_rpath, final_path,
- install_name_mappings, verbose=False)
- except SystemExit as e:
- if isinstance(e.code, int) and e.code == 0:
- pass
- else:
- raise
def run(opts):
datafilename = 'meson-private/install.dat'
<file_sep># $NetBSD: Makefile,v 1.1 2018/09/21 13:24:34 maya Exp $
DISTNAME= alure-1.2
CATEGORIES= audio
MASTER_SITES= http://kcat.strangesoft.net/alure-releases/
MAINTAINER= <EMAIL>
HOMEPAGE= http://kcat.strangesoft.net/alure
COMMENT= Helps manage common tasks with OpenAL applications
LICENSE= mit
USE_CMAKE= yes
USE_TOOLS+= pkg-config
USE_LANGUAGES= c c++
CMAKE_ARGS+= -DBUILD_EXAMPLES=OFF -DDUMB=OFF -DDYNLOAD=OFF
PKGCONFIG_OVERRIDE+= alure-static.pc.in
PKGCONFIG_OVERRIDE+= alure.pc.in
.include "options.mk"
.include "../../audio/openal-soft/buildlink3.mk"
.include "../../mk/bsd.pkg.mk"
<file_sep># $NetBSD: Makefile,v 1.4 2019/05/07 08:50:36 adam Exp $
DISTNAME= certbot-apache-0.34.1
PKGNAME= ${PYPKGPREFIX}-${DISTNAME}
CATEGORIES= security python
MASTER_SITES= ${MASTER_SITE_PYPI:=c/certbot-apache/}
COMMENT= Apache plugin for Certbot
MAINTAINER= <EMAIL>
HOMEPAGE= https://github.com/certbot/certbot
LICENSE= apache-2.0
DEPENDS+= ${PYPKGPREFIX}-acme>=0.29.0:../../security/py-acme
DEPENDS+= ${PYPKGPREFIX}-augeas-[0-9]*:../../sysutils/py-augeas
DEPENDS+= ${PYPKGPREFIX}-certbot>=0.34.0:../../security/py-certbot
DEPENDS+= ${PYPKGPREFIX}-mock-[0-9]*:../../devel/py-mock
DEPENDS+= ${PYPKGPREFIX}-pyparsing>=1.5.5:../../devel/py-pyparsing
DEPENDS+= ${PYPKGPREFIX}-setuptools-[0-9]*:../../devel/py-setuptools
DEPENDS+= ${PYPKGPREFIX}-ZopeComponent-[0-9]*:../../devel/py-ZopeComponent
DEPENDS+= ${PYPKGPREFIX}-ZopeInterface-[0-9]*:../../devel/py-ZopeInterface
USE_LANGUAGES= # none
.include "../../lang/python/egg.mk"
.include "../../mk/bsd.pkg.mk"
<file_sep>$NetBSD: patch-setup.py,v 1.2 2019/04/07 15:58:33 adam Exp $
Do not install tests.
Avoid too strict version requirements.
--- setup.py.orig 2018-09-23 11:26:23.000000000 +0000
+++ setup.py
@@ -35,7 +35,7 @@ setup(
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/python-hyper/wsproto/',
- packages=find_packages(),
+ packages=find_packages(exclude=['test']),
package_data={'': ['LICENSE', 'README.rst']},
package_dir={'wsproto': 'wsproto'},
include_package_data=True,
@@ -55,7 +55,7 @@ setup(
'Programming Language :: Python :: Implementation :: PyPy',
],
install_requires=[
- 'h11 ~= 0.8.1', # means: 0.8.x where x >= 1
+ 'h11>=0.8.1',
],
extras_require={
':python_version == "2.7"':
<file_sep>$NetBSD: patch-lib_isc_include_isc_types.h,v 1.1 2019/04/30 03:34:34 taca Exp $
* Changes change from NetBSD base.
--- lib/isc/include/isc/types.h.orig 2019-04-06 20:09:59.000000000 +0000
+++ lib/isc/include/isc/types.h
@@ -65,7 +65,11 @@ typedef struct isc_ratelimiter isc_rate
typedef struct isc_region isc_region_t; /*%< Region */
typedef uint64_t isc_resourcevalue_t; /*%< Resource Value */
typedef unsigned int isc_result_t; /*%< Result */
+#ifndef ISC_PLATFORM_USE_NATIVE_RWLOCKS
typedef struct isc_rwlock isc_rwlock_t; /*%< Read Write Lock */
+#else
+typedef pthread_rwlock_t isc_rwlock_t; /*%< Read Write Lock */
+#endif
typedef struct isc_sockaddr isc_sockaddr_t; /*%< Socket Address */
typedef ISC_LIST(isc_sockaddr_t) isc_sockaddrlist_t; /*%< Socket Address List */
typedef struct isc_socket isc_socket_t; /*%< Socket */
<file_sep>$NetBSD: patch-clang__delta_TransformationManager.cpp,v 1.4 2018/12/12 12:44:43 adam Exp $
Fix for LLVM 7.0.
https://github.com/csmith-project/creduce/tree/llvm-7.0
--- clang_delta/TransformationManager.cpp.orig 2018-12-12 12:37:38.000000000 +0000
+++ clang_delta/TransformationManager.cpp
@@ -223,7 +223,7 @@ llvm::raw_ostream *TransformationManager
std::error_code EC;
llvm::raw_fd_ostream *Out = new llvm::raw_fd_ostream(
- OutputFileName, EC, llvm::sys::fs::F_RW);
+ OutputFileName, EC, llvm::sys::fs::FA_Read | llvm::sys::fs::FA_Write);
assert(!EC && "Cannot open output file!");
return Out;
}
<file_sep>$NetBSD: patch-media_libcubeb_update.sh,v 1.5 2018/11/04 00:38:45 ryoon Exp $
--- media/libcubeb/update.sh.orig 2018-10-18 20:06:09.000000000 +0000
+++ media/libcubeb/update.sh
@@ -20,6 +20,7 @@ cp $1/src/cubeb_log.h src
cp $1/src/cubeb_mixer.cpp src
cp $1/src/cubeb_mixer.h src
cp $1/src/cubeb_opensl.c src
+cp $1/src/cubeb_oss.c src
cp $1/src/cubeb-jni.cpp src
cp $1/src/cubeb-jni.h src
cp $1/src/android/cubeb-output-latency.h src/android
<file_sep>$NetBSD: patch-src_libcryptobox_cryptobox.c,v 1.1 2018/10/12 12:49:28 roy Exp $
OpenSSL-1.1 automatically loads error strings.
Calling these without an OpenSSL init function can result in an error.
--- src/libcryptobox/cryptobox.c.orig 2018-09-24 13:53:53.000000000 +0000
+++ src/libcryptobox/cryptobox.c
@@ -374,7 +374,7 @@ rspamd_cryptobox_init (void)
ctx->blake2_impl = blake2b_load ();
ctx->ed25519_impl = ed25519_load ();
ctx->base64_impl = base64_load ();
-#ifdef HAVE_USABLE_OPENSSL
+#if defined(HAVE_USABLE_OPENSSL) && OPENSSL_VERSION_NUMBER < 0x10100000L
ERR_load_EC_strings ();
ERR_load_RAND_strings ();
ERR_load_EVP_strings ();
<file_sep>$NetBSD: patch-deps_openssl_config_dso__conf__no-asm.h,v 1.1 2019/02/24 12:18:55 rin Exp $
Support NetBSD/arm,aarch64,i386,amd64 (and hopefully other ILP32 archs)
--- deps/openssl/config/dso_conf_no-asm.h.orig 2019-01-29 16:20:45.000000000 +0900
+++ deps/openssl/config/dso_conf_no-asm.h 2019-02-24 10:24:59.496934700 +0900
@@ -9,9 +9,9 @@
# include "./archs/linux-x32/no-asm/crypto/include/internal/dso_conf.h"
#elif defined(OPENSSL_LINUX) && defined(__x86_64__)
# include "./archs/linux-x86_64/no-asm/crypto/include/internal/dso_conf.h"
-#elif defined(OPENSSL_LINUX) && defined(__arm__)
+#elif (defined(OPENSSL_LINUX) || defined(__NetBSD__)) && defined(__arm__)
# include "./archs/linux-armv4/no-asm/crypto/include/internal/dso_conf.h"
-#elif defined(OPENSSL_LINUX) && defined(__aarch64__)
+#elif (defined(OPENSSL_LINUX) || defined(__NetBSD__)) && defined(__aarch64__)
# include "./archs/linux-aarch64/no-asm/crypto/include/internal/dso_conf.h"
#elif defined(__APPLE__) && defined(__MACH__) && defined(__i386__)
# include "./archs/darwin-i386-cc/no-asm/crypto/include/internal/dso_conf.h"
@@ -21,9 +21,10 @@
# include "./archs/VC-WIN32/no-asm/crypto/include/internal/dso_conf.h"
#elif defined(_WIN32) && defined(_M_X64)
# include "./archs/VC-WIN64A/no-asm/crypto/include/internal/dso_conf.h"
-#elif (defined(__FreeBSD__) || defined(__OpenBSD__)) && defined(__i386__)
-# include "./archs/BSD-x86/no-asm/crypto/include/internal/dso_conf.h"
-#elif (defined(__FreeBSD__) || defined(__OpenBSD__)) && defined(__x86_64__)
+// XXX missing
+//#elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)) && defined(__i386__)
+//# include "./archs/BSD-x86/no-asm/crypto/include/internal/dso_conf.h"
+#elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)) && defined(__x86_64__)
# include "./archs/BSD-x86_64/no-asm/crypto/include/internal/dso_conf.h"
#elif defined(__sun) && defined(__i386__)
# include "./archs/solaris-x86-gcc/no-asm/crypto/include/internal/dso_conf.h"
<file_sep>$NetBSD: patch-lib_isc_include_isc_socket.h,v 1.1 2019/04/30 03:34:34 taca Exp $
* fdwatch change from NetBSD base.
--- lib/isc/include/isc/socket.h.orig 2019-04-06 20:09:59.000000000 +0000
+++ lib/isc/include/isc/socket.h
@@ -243,7 +243,8 @@ typedef enum {
isc_sockettype_udp = 1,
isc_sockettype_tcp = 2,
isc_sockettype_unix = 3,
- isc_sockettype_raw = 4
+ isc_sockettype_raw = 4,
+ isc_sockettype_fdwatch = 5
} isc_sockettype_t;
/*@{*/
@@ -1037,6 +1038,82 @@ isc_socketmgr_renderjson(isc_socketmgr_t
*/
typedef isc_result_t
(*isc_socketmgrcreatefunc_t)(isc_mem_t *mctx, isc_socketmgr_t **managerp);
+/*!
+ * Flags for fdwatchcreate.
+ */
+#define ISC_SOCKFDWATCH_READ 0x00000001 /*%< watch for readable */
+#define ISC_SOCKFDWATCH_WRITE 0x00000002 /*%< watch for writable */
+/*@}*/
+
+isc_result_t
+isc_socket_fdwatchcreate(isc_socketmgr_t *manager,
+ int fd,
+ int flags,
+ isc_sockfdwatch_t callback,
+ void *cbarg,
+ isc_task_t *task,
+ isc_socket_t **socketp);
+/*%<
+ * Create a new file descriptor watch socket managed by 'manager'.
+ *
+ * Note:
+ *
+ *\li 'fd' is the already-opened file descriptor (must be less
+ * than maxsockets).
+ *\li This function is not available on Windows.
+ *\li The callback function is called "in-line" - this means the function
+ * needs to return as fast as possible, as all other I/O will be suspended
+ * until the callback completes.
+ *
+ * Requires:
+ *
+ *\li 'manager' is a valid manager
+ *
+ *\li 'socketp' is a valid pointer, and *socketp == NULL
+ *
+ *\li 'fd' be opened.
+ *
+ * Ensures:
+ *
+ * '*socketp' is attached to the newly created fdwatch socket
+ *
+ * Returns:
+ *
+ *\li #ISC_R_SUCCESS
+ *\li #ISC_R_NOMEMORY
+ *\li #ISC_R_NORESOURCES
+ *\li #ISC_R_UNEXPECTED
+ *\li #ISC_R_RANGE
+ */
+
+isc_result_t
+isc_socket_fdwatchpoke(isc_socket_t *sock,
+ int flags);
+/*%<
+ * Poke a file descriptor watch socket informing the manager that it
+ * should restart watching the socket
+ *
+ * Note:
+ *
+ *\li 'sock' is the socket returned by isc_socket_fdwatchcreate
+ *
+ *\li 'flags' indicates what the manager should watch for on the socket
+ * in addition to what it may already be watching. It can be one or
+ * both of ISC_SOCKFDWATCH_READ and ISC_SOCKFDWATCH_WRITE. To
+ * temporarily disable watching on a socket the value indicating
+ * no more data should be returned from the call back routine.
+ *
+ *\li This function is not available on Windows.
+ *
+ * Requires:
+ *
+ *\li 'sock' is a valid isc socket
+ *
+ *
+ * Returns:
+ *
+ *\li #ISC_R_SUCCESS
+ */
ISC_LANG_ENDDECLS
<file_sep>$NetBSD: patch-mac_scripts_create__info__header.sh,v 1.1 2019/02/10 17:14:42 nia Exp $
Portability fix.
--- mac/scripts/create_info_header.sh.orig 2018-02-14 07:11:20.000000000 +0000
+++ mac/scripts/create_info_header.sh
@@ -21,7 +21,7 @@ done
cd ${TOPLEVEL}
mkdir -p mac/build
eval $(g++ -E -dM src/Audacity.h | awk '/#define *AUDACITY_(VERSION|RELEASE|REVISION|MODLEVEL) /{print $2 "=" $3}')
-if [ $CONFIGURATION == 'Debug' ]
+if [ $CONFIGURATION = 'Debug' ]
then
AUDACITY_EXECUTABLE=Audacity
else
<file_sep>$NetBSD: patch-lib_sanitizer__common_sanitizer__platform__limits__netbsd.cc,v 1.1 2018/12/09 20:04:40 adam Exp $
Network ATM has been removed from NetBSD.
--- lib/sanitizer_common/sanitizer_platform_limits_netbsd.cc.orig 2018-10-07 11:20:49.808236967 +0000
+++ lib/sanitizer_common/sanitizer_platform_limits_netbsd.cc
@@ -116,7 +116,9 @@
#include <dev/wscons/wsconsio.h>
#include <dev/wscons/wsdisplay_usl_io.h>
#include <net/bpf.h>
+#if __NetBSD_Version__ < 899000000
#include <net/if_atm.h>
+#endif
#include <net/if_gre.h>
#include <net/if_ppp.h>
#include <net/if_pppoe.h>
@@ -132,7 +134,9 @@
#include <netinet/ip_proxy.h>
#include <netinet6/in6_var.h>
#include <netinet6/nd6.h>
+#if __NetBSD_Version__ < 899000000
#include <netnatm/natm.h>
+#endif
#include <netsmb/smb_dev.h>
#include <soundcard.h>
#include <sys/agpio.h>
@@ -349,8 +353,10 @@ unsigned struct_apm_power_info_sz = size
unsigned struct_atabusiodetach_args_sz = sizeof(atabusiodetach_args);
unsigned struct_atabusioscan_args_sz = sizeof(atabusioscan_args);
unsigned struct_ath_diag_sz = sizeof(ath_diag);
+#if __NetBSD_Version__ < 899000000
unsigned struct_atm_flowmap_sz = sizeof(atm_flowmap);
unsigned struct_atm_pseudoioctl_sz = sizeof(atm_pseudoioctl);
+#endif
unsigned struct_audio_buf_info_sz = sizeof(audio_buf_info);
unsigned struct_audio_device_sz = sizeof(audio_device);
unsigned struct_audio_encoding_sz = sizeof(audio_encoding);
@@ -596,7 +602,9 @@ unsigned struct_priq_delete_filter_sz =
unsigned struct_priq_interface_sz = sizeof(priq_interface);
unsigned struct_priq_modify_class_sz = sizeof(priq_modify_class);
unsigned struct_ptmget_sz = sizeof(ptmget);
+#if __NetBSD_Version__ < 899000000
unsigned struct_pvctxreq_sz = sizeof(pvctxreq);
+#endif
unsigned struct_radio_info_sz = sizeof(radio_info);
unsigned struct_red_conf_sz = sizeof(red_conf);
unsigned struct_red_interface_sz = sizeof(red_interface);
@@ -1414,6 +1422,7 @@ unsigned IOCTL_BIOCSRTIMEOUT = BIOCSRTIM
unsigned IOCTL_BIOCGRTIMEOUT = BIOCGRTIMEOUT;
unsigned IOCTL_BIOCGFEEDBACK = BIOCGFEEDBACK;
unsigned IOCTL_BIOCSFEEDBACK = BIOCSFEEDBACK;
+#if __NetBSD_Version__ < 899000000
unsigned IOCTL_SIOCRAWATM = SIOCRAWATM;
unsigned IOCTL_SIOCATMENA = SIOCATMENA;
unsigned IOCTL_SIOCATMDIS = SIOCATMDIS;
@@ -1421,6 +1430,7 @@ unsigned IOCTL_SIOCSPVCTX = SIOCSPVCTX;
unsigned IOCTL_SIOCGPVCTX = SIOCGPVCTX;
unsigned IOCTL_SIOCSPVCSIF = SIOCSPVCSIF;
unsigned IOCTL_SIOCGPVCSIF = SIOCGPVCSIF;
+#endif
unsigned IOCTL_GRESADDRS = GRESADDRS;
unsigned IOCTL_GRESADDRD = GRESADDRD;
unsigned IOCTL_GREGADDRS = GREGADDRS;
@@ -1804,8 +1814,10 @@ unsigned IOCTL_MTIOCSLOCATE = MTIOCSLOCA
unsigned IOCTL_MTIOCHLOCATE = MTIOCHLOCATE;
unsigned IOCTL_POWER_EVENT_RECVDICT = POWER_EVENT_RECVDICT;
unsigned IOCTL_POWER_IOC_GET_TYPE = POWER_IOC_GET_TYPE;
+#if __NetBSD_Version__ < 899000000
unsigned IOCTL_POWER_IOC_GET_TYPE_WITH_LOSSAGE =
POWER_IOC_GET_TYPE_WITH_LOSSAGE;
+#endif
unsigned IOCTL_RIOCGINFO = RIOCGINFO;
unsigned IOCTL_RIOCSINFO = RIOCSINFO;
unsigned IOCTL_RIOCSSRCH = RIOCSSRCH;
<file_sep># $NetBSD: options.mk,v 1.2 2019/02/11 22:01:18 leot Exp $
PKG_OPTIONS_VAR= PKG_OPTIONS.sc-im
PKG_SUPPORTED_OPTIONS+= color xls xlsx lua
PKG_SUGGESTED_OPTIONS+= color xls xlsx lua
.include "../../mk/bsd.options.mk"
.if !empty(PKG_OPTIONS:Mcolor)
CFLAGS+= -DUSECOLORS
.endif
.if !empty(PKG_OPTIONS:Mxls)
CFLAGS+= -DXLS
LDFLAGS+= -lxlsreader
.include "../../textproc/libxls/buildlink3.mk"
.endif
.if !empty(PKG_OPTIONS:Mxlsx)
CFLAGS+= -DXLSX -DXLSX_EXPORT
LDFLAGS+= -lxlsxwriter
.include "../../archivers/libzip/buildlink3.mk"
.include "../../textproc/libxml2/buildlink3.mk"
.include "../../textproc/libxlsxwriter/buildlink3.mk"
.endif
.if !empty(PKG_OPTIONS:Mlua)
.include "../../lang/lua51/buildlink3.mk"
.endif
<file_sep>$NetBSD: patch-vendor_rand-0.5.5_src_rngs_os.rs,v 1.1 2019/03/07 20:19:11 jperkin Exp $
Explicitly disable getrandom support on SunOS, the test fails.
https://github.com/rust-random/rand/issues/637
--- vendor/rand-0.5.5/src/rngs/os.rs.orig 2019-02-28 10:22:24.000000000 +0000
+++ vendor/rand-0.5.5/src/rngs/os.rs
@@ -675,6 +675,7 @@ mod imp {
}
fn getrandom(buf: &mut [u8], blocking: bool) -> libc::c_long {
+ return -1;
extern "C" {
fn syscall(number: libc::c_long, ...) -> libc::c_long;
}
<file_sep># $NetBSD: buildlink3.mk,v 1.9 2018/11/12 03:49:09 ryoon Exp $
BUILDLINK_TREE+= harfbuzz
.if !defined(HARFBUZZ_BUILDLINK3_MK)
HARFBUZZ_BUILDLINK3_MK:=
BUILDLINK_API_DEPENDS.harfbuzz+= harfbuzz>=2.1.1
BUILDLINK_ABI_DEPENDS.harfbuzz+= harfbuzz>=2.1.1
BUILDLINK_PKGSRCDIR.harfbuzz?= ../../fonts/harfbuzz
.include "../../devel/glib2/buildlink3.mk"
.include "../../graphics/freetype2/buildlink3.mk"
.endif # HARFBUZZ_BUILDLINK3_MK
BUILDLINK_TREE+= -harfbuzz
<file_sep>$NetBSD: patch-test_rspamd__lua__pcall__vs__resume__test.c,v 1.1 2018/10/07 20:10:57 fhajny Exp $
Add Lua 5.3 support.
--- test/rspamd_lua_pcall_vs_resume_test.c.orig 2018-09-24 13:53:53.000000000 +0000
+++ test/rspamd_lua_pcall_vs_resume_test.c
@@ -53,7 +53,11 @@ test_resume(lua_State *L, gint function_
for (i = 0; i < N; i ++) {
lua_rawgeti (L, LUA_REGISTRYINDEX, function_call);
+#if LUA_VERSION_NUM < 503
lua_resume (L, 0);
+#else
+ lua_resume (L, NULL, 0);
+#endif
lua_pop (L, 1);
}
@@ -75,7 +79,11 @@ test_resume_get_thread(gint function_cal
ent = lua_thread_pool_get_for_config (rspamd_main->cfg);
lua_rawgeti (ent->lua_state, LUA_REGISTRYINDEX, function_call);
+#if LUA_VERSION_NUM < 503
lua_resume (ent->lua_state, 0);
+#else
+ lua_resume (ent->lua_state, NULL, 0);
+#endif
lua_pop (ent->lua_state, 1);
lua_thread_pool_return (rspamd_main->cfg->lua_thread_pool, ent);
@@ -99,7 +107,11 @@ test_resume_get_new_thread(gint function
ent = lua_thread_pool_get_for_task (rspamd_main->cfg->lua_thread_pool);
lua_rawgeti (ent->lua_state, LUA_REGISTRYINDEX, function_call);
+#if LUA_VERSION_NUM < 503
lua_resume (ent->lua_state, 0);
+#else
+ lua_resume (ent->lua_state, NULL, 0);
+#endif
lua_pop (ent->lua_state, 1);
/* lua_thread_pool_return (rspamd_main->cfg->lua_thread_pool, ent); */
<file_sep># $NetBSD: Makefile,v 1.3 2019/04/26 08:32:29 skrll Exp $
UBOOT_TARGET= odroid-c2
UBOOT_CONFIG= odroid-c2_defconfig
UBOOT_BIN= u-boot u-boot-dtb.bin
PKGREVISION= 2
.include "../../sysutils/u-boot/u-boot-arm64.mk"
<file_sep># $NetBSD: Makefile,v 1.4 2018/11/22 15:06:09 nia Exp $
#
DISTNAME= enchant-2.2.3
PKGNAME= enchant2-2.2.3
PKGREVISION= 1
CATEGORIES= textproc
MASTER_SITES= ${MASTER_SITE_GITHUB:=AbiWord/}
GITHUB_PROJECT= enchant
GITHUB_RELEASE= v${PKGVERSION_NOREV}
MAINTAINER= <EMAIL>
HOMEPAGE= https://abiword.github.io/enchant/
COMMENT= Generic spell checking library
LICENSE= gnu-lgpl-v2.1
USE_TOOLS+= pkg-config autoconf
USE_LANGUAGES= c c++11
USE_PKGLOCALEDIR= yes
USE_LIBTOOL= yes
PKGCONFIG_OVERRIDE+= enchant.pc.in
GNU_CONFIGURE= yes
CFLAGS.SunOS+= -D__EXTENSIONS__
INSTALLATION_DIRS+= share/examples
MAKE_DIRS+= ${PREFIX}/share/enchant
CONF_FILES= ${PREFIX}/share/examples/enchant.ordering ${PREFIX}/share/enchant/enchant.ordering
# unsupported in pkgsrc - other dictionaries can be used instead
# avoid PLIST problems
CONFIGURE_ARGS+= --without-hspell
CONFIGURE_ARGS+= --without-uspell
CONFIGURE_ARGS+= --without-voikko
# XXX: needs unittest-cpp as a test dependency
#TEST_TARGET= check
post-install:
cd ${DESTDIR}${PREFIX}/share && ${MV} enchant/enchant.ordering examples/enchant.ordering
.include "options.mk"
.include "../../devel/glib2/buildlink3.mk"
#BUILDLINK_DEPMETHOD.unittest-cpp= build # XXX: for tests
#.include "../../wip/unittest-cpp/buildlink3.mk"
.include "../../mk/bsd.pkg.mk"
<file_sep>$NetBSD: patch-setup.py,v 1.1 2019/01/28 08:41:37 adam Exp $
Allow newer pytest.
--- setup.py.orig 2019-01-15 08:36:48.000000000 +0000
+++ setup.py
@@ -21,7 +21,7 @@ classifiers = [
'Programming Language :: Python :: 3.6',
]
-install_requires = ['pytest<4.0.0']
+install_requires = ['pytest']
tests_require = ['six',
]
<file_sep># $NetBSD: Makefile,v 1.46 2018/11/23 08:06:31 ryoon Exp $
DISTNAME= gst-libav-1.14.4
PKGNAME= ${DISTNAME:S/gst/gst-plugins1/}
PKGREVISION= 1
CATEGORIES= multimedia
MASTER_SITES= https://gstreamer.freedesktop.org/src/gst-libav/
EXTRACT_SUFX= .tar.xz
MAINTAINER= <EMAIL>
HOMEPAGE= https://gstreamer.freedesktop.org/src/gst-libav/
COMMENT= GStreamer libav/ffmpeg plugin
LICENSE= gnu-gpl-v2
USE_LIBTOOL= yes
USE_PKGLOCALEDIR= yes
USE_TOOLS+= pkg-config gmake perl
GNU_CONFIGURE= yes
CONFIGURE_ARGS+= --with-system-libav
PKGSRC_MAKE_ENV+= PERL=${PERL5:Q}
BUILDLINK_API_DEPENDS.gstreamer1+= gstreamer1>=1.14.4
.include "../../multimedia/gstreamer1/buildlink3.mk"
.include "../../multimedia/gst-plugins1-base/buildlink3.mk"
.include "../../multimedia/ffmpeg3/buildlink3.mk"
.include "../../devel/orc/buildlink3.mk"
.include "../../mk/bsd.pkg.mk"
<file_sep># $NetBSD: Makefile,v 1.6 2019/02/15 19:49:15 wiz Exp $
DISTNAME= cproto-4.7o
CATEGORIES= devel
MASTER_SITES= ftp://ftp.invisible-island.net/cproto/
EXTRACT_SUFX= .tgz
MAINTAINER= <EMAIL>
HOMEPAGE= http://invisible-island.net/cproto/
COMMENT= Generates function prototypes from C source
LICENSE= public-domain
GNU_CONFIGURE= yes
USE_TOOLS+= yacc lex
.include "../../mk/bsd.pkg.mk"
<file_sep>$NetBSD: patch-src_startup__notification.c,v 1.1 2019/01/09 01:33:35 gutteridge Exp $
Crash fixer from <NAME> in PR pkg/53396:
sn_startup_sequence_get_last_active_time takes two long pointer
arguments, but xfce4-wm passes pointers to may-be-different types.
--- src/startup_notification.c.orig 2018-07-29 13:08:54.000000000 +0000
+++ src/startup_notification.c
@@ -128,6 +128,7 @@ sn_collect_timed_out_foreach (void *elem
SnStartupSequence *sequence;
time_t tv_sec;
suseconds_t tv_usec;
+ long l_sec, l_usec;
double elapsed;
g_return_if_fail (data != NULL);
@@ -135,7 +136,8 @@ sn_collect_timed_out_foreach (void *elem
sequence = element;
ctod = (CollectTimedOutData *) data;
- sn_startup_sequence_get_last_active_time (sequence, &tv_sec, &tv_usec);
+ sn_startup_sequence_get_last_active_time (sequence, &l_sec, &l_usec);
+ tv_sec = l_sec; tv_usec = l_sec;
elapsed =
((((double) ctod->now.tv_sec - tv_sec) * G_USEC_PER_SEC +
<file_sep># $NetBSD: Makefile,v 1.27 2018/11/30 10:37:07 adam Exp $
DISTNAME= networkx-2.2
PKGNAME= ${PYPKGPREFIX}-${DISTNAME}
CATEGORIES= math python
MASTER_SITES= ${MASTER_SITE_PYPI:=n/networkx/}
EXTRACT_SUFX= .zip
MAINTAINER= <EMAIL>
HOMEPAGE= http://networkx.github.io/
COMMENT= Python package for creating and manipulating graphs and networks
LICENSE= modified-bsd
DEPENDS+= ${PYPKGPREFIX}-decorator>=4.3.0:../../devel/py-decorator
TEST_DEPENDS+= ${PYPKGPREFIX}-nose>=1.3.7:../../devel/py-nose
USE_LANGUAGES= # none
post-extract:
find ${WRKSRC} -type f -exec chmod 644 {} +
.include "../../lang/python/egg.mk"
.include "../../mk/bsd.pkg.mk"
<file_sep>$NetBSD: patch-src_client_snd__main.c,v 1.1 2019/04/11 20:56:34 nia Exp $
Default to OpenAL over SDL2 - eliminates stuttering on NetBSD.
--- src/client/snd_main.c.orig 2019-01-05 19:54:35.000000000 +0000
+++ src/client/snd_main.c
@@ -809,7 +809,7 @@ void S_StopMusic_f(void)
*/
void S_Init(void)
{
- cvar_t *cv = Cvar_Get("s_initsound", "1", CVAR_ARCHIVE | CVAR_LATCH | CVAR_UNSAFE); // 0 = disabled, 1 = SDL2, 2 = OpenAL
+ cvar_t *cv = Cvar_Get("s_initsound", "2", CVAR_ARCHIVE | CVAR_LATCH | CVAR_UNSAFE); // 0 = disabled, 1 = SDL2, 2 = OpenAL
Com_Printf("------ Initializing Sound (%i)------\n", cv->integer);
<file_sep>$NetBSD: patch-lib_isc_rwlock.c,v 1.1 2019/04/30 03:34:34 taca Exp $
* Platform change from NetBSD base.
--- lib/isc/rwlock.c.orig 2019-04-06 20:09:59.000000000 +0000
+++ lib/isc/rwlock.c
@@ -54,11 +54,12 @@
# define isc_rwlock_pause() __asm__ __volatile__ ("rep; nop")
#elif defined(__ia64__)
# define isc_rwlock_pause() __asm__ __volatile__ ("hint @pause")
-#elif defined(__arm__)
+#elif defined(__arm__) && defined(_ARM_ARCH_6)
# define isc_rwlock_pause() __asm__ __volatile__ ("yield")
#elif defined(sun) && (defined(__sparc) || defined(__sparc__))
# define isc_rwlock_pause() smt_pause()
-#elif defined(__sparc) || defined(__sparc__)
+/* Disable pause, only works on v9 */
+#elif (defined(__sparc) || defined(__sparc__)) && defined(notdef)
# define isc_rwlock_pause() __asm__ __volatile__ ("pause")
#elif defined(__ppc__) || defined(_ARCH_PPC) || \
defined(_ARCH_PWR) || defined(_ARCH_PWR2) || defined(_POWER)
<file_sep># $NetBSD: Makefile,v 1.3 2018/12/16 14:54:39 adam Exp $
DISTNAME= Theano-1.0.3
PKGNAME= ${PYPKGPREFIX}-${DISTNAME}
CATEGORIES= math python
MASTER_SITES= ${MASTER_SITE_PYPI:=T/Theano/}
MAINTAINER= <EMAIL>
HOMEPAGE= http://deeplearning.net/software/theano/
COMMENT= Optimizing compiler for evaluating mathematical expressions
LICENSE= modified-bsd
DEPENDS+= ${PYPKGPREFIX}-scipy>=0.17.0:../../math/py-scipy
DEPENDS+= ${PYPKGPREFIX}-six-[0-9]*:../../lang/py-six
TEST_DEPENDS+= ${PYPKGPREFIX}-flake8-[0-9]*:../../devel/py-flake8
TEST_DEPENDS+= ${PYPKGPREFIX}-nose>=1.3.0:../../devel/py-nose
TEST_DEPENDS+= ${PYPKGPREFIX}-parameterized-[0-9]*:../../devel/py-parameterized
USE_TOOLS+= bash
USE_LANGUAGES= c c++
REPLACE_INTERPRETER+= bash
REPLACE.bash.old= .*/bin/bash
REPLACE.bash.new= ${SH}
REPLACE_FILES.bash= theano/misc/check_blas_many.sh
do-test:
${RUN} cd ${WRKSRC}/theano/tests && \
${SETENV} ${TEST_ENV} ${PYTHONBIN} main.py
post-install:
.for cmd in theano-cache theano-nose
${MV} ${DESTDIR}${PREFIX}/bin/${cmd} \
${DESTDIR}${PREFIX}/bin/${cmd}-${PYVERSSUFFIX} || ${TRUE}
.endfor
.include "../../lang/python/egg.mk"
.include "../../math/py-numpy/buildlink3.mk"
.include "../../mk/bsd.pkg.mk"
<file_sep># $NetBSD: options.mk,v 1.1 2018/12/16 02:05:23 nia Exp $
PKG_OPTIONS_VAR= PKG_OPTIONS.znc
PKG_SUPPORTED_OPTIONS= debug inet6 perl python sasl tcl
PKG_SUGGESTED_OPTIONS= inet6
.include "../../mk/bsd.options.mk"
# Debug build
.if !empty(PKG_OPTIONS:Mdebug)
CONFIGURE_ARGS+= --enable-debug
.endif
# IPv6 support
.if empty(PKG_OPTIONS:Minet6)
CONFIGURE_ARGS+= --disable-ipv6
.endif
# Perl support
.if !empty(PKG_OPTIONS:Mperl)
.include "../../lang/perl5/buildlink3.mk"
CONFIGURE_ARGS+= --enable-perl
USE_TOOLS+= perl
PLIST_SRC+= PLIST.perl
.endif
# TCL option
.if !empty(PKG_OPTIONS:Mtcl)
.include "../../lang/tcl/buildlink3.mk"
CONFIGURE_ARGS+= --enable-tcl
CONFIGURE_ARGS+= --with-tcl=${BUILDLINK_PREFIX.tcl}/lib
PLIST_SRC+= PLIST.tcl
.endif
# Python support
.if !empty(PKG_OPTIONS:Mpython)
PYTHON_VERSIONS_INCOMPATIBLE= 27
.include "../../lang/python/extension.mk"
CONFIGURE_ARGS+= --enable-python=python-${PYVERSSUFFIX}
PLIST_SRC+= PLIST.python
.endif
# Cyrus SASL support
.if !empty(PKG_OPTIONS:Msasl)
.include "../../security/cyrus-sasl/buildlink3.mk"
CONFIGURE_ARGS+= --enable-cyrus
PLIST_SRC+= PLIST.cyrus
.endif
<file_sep>$NetBSD: patch-clang__delta_RemoveUnusedEnumMember.cpp,v 1.1 2018/12/12 12:44:43 adam Exp $
Fix for LLVM 7.0.
https://github.com/csmith-project/creduce/tree/llvm-7.0
--- clang_delta/RemoveUnusedEnumMember.cpp.orig 2018-12-12 12:36:01.000000000 +0000
+++ clang_delta/RemoveUnusedEnumMember.cpp
@@ -99,15 +99,15 @@ void RemoveUnusedEnumMember::removeEnumC
{
SourceLocation StartLoc = (*TheEnumIterator)->getLocStart();
if (StartLoc.isMacroID()) {
- std::pair<SourceLocation, SourceLocation> Locs =
+ CharSourceRange CSRange =
SrcManager->getExpansionRange(StartLoc);
- StartLoc = Locs.first;
+ StartLoc = CSRange.getBegin();
}
SourceLocation EndLoc = (*TheEnumIterator)->getLocEnd();
if (EndLoc.isMacroID()) {
- std::pair<SourceLocation, SourceLocation> Locs =
+ CharSourceRange CSRange =
SrcManager->getExpansionRange(EndLoc);
- EndLoc = Locs.second;
+ EndLoc = CSRange.getEnd();
}
SourceLocation CommaLoc = Lexer::findLocationAfterToken(
EndLoc, tok::comma, *SrcManager, Context->getLangOpts(),
<file_sep># $NetBSD: Makefile,v 1.9 2018/10/07 23:21:26 ryoon Exp $
DISTNAME= link-grammar-5.5.1
CATEGORIES= textproc
MASTER_SITES= https://www.abisource.com/downloads/link-grammar/${PKGVERSION_NOREV}/
MAINTAINER= <EMAIL>
HOMEPAGE= http://www.abisource.com/projects/link-grammar/
COMMENT= Syntactic parsing library
LICENSE= modified-bsd AND gnu-lgpl-v2.1
USE_LANGUAGES= c99 c++
USE_LIBTOOL= yes
USE_TOOLS+= gmake pkg-config
GNU_CONFIGURE= yes
CONFIGURE_ARGS+= --disable-java-bindings
PKGCONFIG_OVERRIDE+= link-grammar.pc.in
.include "../../mk/bsd.pkg.mk"
<file_sep>$NetBSD: patch-src_ft2__unicode.c,v 1.2 2019/03/21 10:16:40 fox Exp $
1. Added a type cast to iconv(3) calls to match the prototypes defined
in NetBSD's iconv.h.
2. Added a NetBSD specific iconv_open() call to prevent failures due
to mismatches iconv_open() parameters present in GNU iconv(3).
--- src/ft2_unicode.c.orig 2019-03-16 22:34:24.000000000 +0000
+++ src/ft2_unicode.c
@@ -277,7 +277,11 @@ char *cp437ToUtf8(char *src)
inLen = srcLen;
outPtr = outBuf;
+#if defined(__NetBSD__)
+ rc = iconv(cd, (const char **)&inPtr, &inLen, &outPtr, &outLen);
+#else
rc = iconv(cd, &inPtr, &inLen, &outPtr, &outLen);
+#endif
iconv(cd, NULL, NULL, &outPtr, &outLen); // flush
iconv_close(cd);
@@ -307,6 +311,8 @@ char *utf8ToCp437(char *src, bool remove
#ifdef __APPLE__
cd = iconv_open("437//TRANSLIT//IGNORE", "UTF-8-MAC");
+#elif defined(__NetBSD__)
+ cd = iconv_open("437", "UTF-8");
#else
cd = iconv_open("437//TRANSLIT//IGNORE", "UTF-8");
#endif
@@ -323,7 +329,11 @@ char *utf8ToCp437(char *src, bool remove
inLen = srcLen;
outPtr = outBuf;
+#if defined(__NetBSD__)
+ rc = iconv(cd, (const char **)&inPtr, &inLen, &outPtr, &outLen);
+#else
rc = iconv(cd, &inPtr, &inLen, &outPtr, &outLen);
+#endif
iconv(cd, NULL, NULL, &outPtr, &outLen); // flush
iconv_close(cd);
<file_sep># $NetBSD: options.mk,v 1.3 2019/02/10 17:14:42 nia Exp $
PKG_OPTIONS_VAR= PKG_OPTIONS.audacity
PKG_SUPPORTED_OPTIONS= debug jack ladspa nls
PKG_SUGGESTED_OPTIONS+= ladspa nls
PLIST_VARS+= nls
.include "../../mk/bsd.options.mk"
.if !empty(PKG_OPTIONS:Mdebug)
CONFIGURE_ARGS+= --enable-debug=yes
.else
CONFIGURE_ARGS+= --enable-debug=no
.endif
.if !empty(PKG_OPTIONS:Mjack)
.include "../../audio/jack/buildlink3.mk"
.endif
.if !empty(PKG_OPTIONS:Mladspa)
.include "../../audio/ladspa/buildlink3.mk"
CONFIGURE_ARGS+= --enable-ladspa=yes
.else
CONFIGURE_ARGS+= --enable-ladspa=no
.endif
.if !empty(PKG_OPTIONS:Mnls)
.include "../../devel/gettext-lib/buildlink3.mk"
PLIST.nls= yes
.else
CONFIGURE_ARGS+= --disable-nls
.endif
<file_sep>$NetBSD: patch-deps_openssl_config_opensslconf__no-asm.h,v 1.3 2019/02/24 12:18:55 rin Exp $
Support NetBSD/arm,aarch64,i386,amd64 (and hopefully other ILP32 archs)
--- deps/openssl/config/opensslconf_no-asm.h.orig 2019-01-29 16:20:45.000000000 +0900
+++ deps/openssl/config/opensslconf_no-asm.h 2019-02-24 10:26:51.159213732 +0900
@@ -4,9 +4,9 @@
# include "./archs/linux-x32/no-asm/include/openssl/opensslconf.h"
#elif defined(OPENSSL_LINUX) && defined(__x86_64__)
# include "./archs/linux-x86_64/no-asm/include/openssl/opensslconf.h"
-#elif defined(OPENSSL_LINUX) && defined(__arm__)
+#elif (defined(OPENSSL_LINUX) || defined(__NetBSD__)) && defined(__arm__)
# include "./archs/linux-armv4/no-asm/include/openssl/opensslconf.h"
-#elif defined(OPENSSL_LINUX) && defined(__aarch64__)
+#elif (defined(OPENSSL_LINUX) || defined(__NetBSD__)) && defined(__aarch64__)
# include "./archs/linux-aarch64/no-asm/include/openssl/opensslconf.h"
#elif defined(__APPLE__) && defined(__MACH__) && defined(__i386__)
# include "./archs/darwin-i386-cc/no-asm/include/openssl/opensslconf.h"
@@ -16,9 +16,10 @@
# include "./archs/VC-WIN32/no-asm/include/openssl/opensslconf.h"
#elif defined(_WIN32) && defined(_M_X64)
# include "./archs/VC-WIN64A/no-asm/include/openssl/opensslconf.h"
-#elif (defined(__FreeBSD__) || defined(__OpenBSD__)) && defined(__i386__)
-# include "./archs/BSD-x86/no-asm/include/openssl/opensslconf.h"
-#elif (defined(__FreeBSD__) || defined(__OpenBSD__)) && defined(__x86_64__)
+// XXX missing
+//#elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)) && defined(__i386__)
+//# include "./archs/BSD-x86/no-asm/include/openssl/opensslconf.h"
+#elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)) && defined(__x86_64__)
# include "./archs/BSD-x86_64/no-asm/include/openssl/opensslconf.h"
#elif defined(__sun) && defined(__i386__)
# include "./archs/solaris-x86-gcc/no-asm/include/openssl/opensslconf.h"
<file_sep>$NetBSD: patch-lib_isc_stats.c,v 1.1 2019/04/30 03:34:34 taca Exp $
* Platform fixes from NetBSD base system.
--- lib/isc/stats.c.orig 2019-04-06 20:09:59.000000000 +0000
+++ lib/isc/stats.c
@@ -30,7 +30,11 @@
#define ISC_STATS_MAGIC ISC_MAGIC('S', 't', 'a', 't')
#define ISC_STATS_VALID(x) ISC_MAGIC_VALID(x, ISC_STATS_MAGIC)
+#ifndef _LP64
+typedef atomic_int_fast32_t isc_stat_t;
+#else
typedef atomic_int_fast64_t isc_stat_t;
+#endif
struct isc_stats {
/*% Unlocked */
<file_sep>$NetBSD: patch-src_ft2__diskop.c,v 1.3 2019/04/19 02:05:14 fox Exp $
Added <sys/types.h> / <sys/stat.h> to prevent "unknown type name"
(dev_t, ino_t and nlink_t) error from the included <fts.h>.
--- src/ft2_diskop.c.orig 2019-04-19 01:53:39.359713817 +0000
+++ src/ft2_diskop.c
@@ -13,6 +13,8 @@
#include <direct.h>
#include <shlobj.h> // SHGetFolderPathW()
#else
+#include <sys/types.h>
+#include <sys/stat.h>
#include <fts.h> // for fts_open() and stuff in recursiveDelete()
#include <unistd.h>
#include <dirent.h>
<file_sep># $NetBSD: Makefile,v 1.3 2018/11/13 09:57:10 markd Exp $
DISTNAME= scikit-image-0.14.1
PKGNAME= ${PYPKGPREFIX}-${DISTNAME}
CATEGORIES= graphics python
MASTER_SITES= ${MASTER_SITE_PYPI:=s/scikit-image/}
MAINTAINER= <EMAIL>
HOMEPAGE= http://scikit-image.org
COMMENT= Image processing routines for SciPy
LICENSE= modified-bsd
USE_LANGUAGES= c c++
DEPENDS+= ${PYPKGPREFIX}-Pillow>=2.9.0:../../graphics/py-Pillow
DEPENDS+= ${PYPKGPREFIX}-PyWavelets>=0.5.2:../../math/py-pywavelets
DEPENDS+= ${PYPKGPREFIX}-matplotlib-[0-9]*:../../graphics/py-matplotlib
DEPENDS+= ${PYPKGPREFIX}-networkx>=1.9:../../math/py-networkx
DEPENDS+= ${PYPKGPREFIX}-scipy>=0.15.1:../../math/py-scipy
DEPENDS+= ${PYPKGPREFIX}-six>=1.9.0:../../lang/py-six
post-install:
cd ${DESTDIR}${PREFIX}/bin && ${MV} skivi skivi${PYVERSSUFFIX} || ${TRUE}
.include "../../devel/py-cython/buildlink3.mk"
.include "../../lang/python/egg.mk"
.include "../../math/py-numpy/buildlink3.mk"
.include "../../mk/bsd.pkg.mk"
<file_sep># $NetBSD: Makefile,v 1.16 2018/12/15 21:12:21 wiz Exp $
DISTNAME= argcomplete-1.9.4
PKGNAME= ${PYPKGPREFIX}-${DISTNAME}
CATEGORIES= sysutils
MASTER_SITES= ${MASTER_SITE_PYPI:=a/argcomplete/}
MAINTAINER= <EMAIL>
HOMEPAGE= https://github.com/kislyuk/argcomplete/
COMMENT= Bash tab completion for argparse
LICENSE= apache-2.0
USE_LANGUAGES= # none
.include "../../lang/python/egg.mk"
.include "../../mk/bsd.pkg.mk"
<file_sep>$NetBSD: patch-extensions_gggl.c,v 1.2 2018/11/22 12:59:07 ryoon Exp $
Patch also submitted upstream:
https://bugzilla.gnome.org/show_bug.cgi?id=795726
Fixes crashes on alignment critical architectures.
--- extensions/gggl.c.orig 2018-10-22 16:57:44.000000000 +0000
+++ extensions/gggl.c
@@ -56,12 +56,15 @@ conv_F_8 (const Babl *conversion,unsigne
while (n--)
{
- float f = ((*(float *) src));
- int uval = lrint (f * 255.0);
+ float f;
+ int uval;
+
+ memcpy(&f, src, sizeof(f));
+ uval = lrint (f * 255.0);
if (uval < 0) uval = 0;
if (uval > 255) uval = 255;
- *(unsigned char *) dst = uval;
+ *dst = uval;
dst += 1;
src += 4;
@@ -72,21 +75,26 @@ static void
conv_F_16 (const Babl *conversion,unsigned char *src, unsigned char *dst, long samples)
{
long n = samples;
+ unsigned short v;
while (n--)
{
- float f = ((*(float *) src));
+ float f;
+ memcpy(&f, src, sizeof(f));
if (f < 0.0)
{
- *(unsigned short *) dst = 0;
+ v = 0;
+ memcpy(dst, &v, sizeof(v));
}
else if (f > 1.0)
{
- *(unsigned short *) dst = 65535;
+ v = 65535;
+ memcpy(dst, &v, sizeof(v));
}
else
{
- *(unsigned short *) dst = lrint (f * 65535.0);
+ v = lrint (f * 65535.0);
+ memcpy(dst, &v, sizeof(v));
}
dst += 2;
src += 4;
@@ -100,7 +108,9 @@ conv_8_F (const Babl *conversion,unsigne
while (n--)
{
- (*(float *) dst) = ((*(unsigned char *) src) / 255.0);
+ float v;
+ v = *src / 255.0;
+ memcpy(dst, &v, sizeof(v));
dst += 4;
src += 1;
}
@@ -113,7 +123,8 @@ conv_16_F (const Babl *conversion,unsign
while (n--)
{
- (*(float *) dst) = *(unsigned short *) src / 65535.0;
+ float v = *src / 65535.0;
+ memcpy(dst, &v, sizeof(v));
dst += 4;
src += 2;
}
@@ -130,13 +141,18 @@ conv_rgbaF_rgb8 (const Babl *conversion,
for (c = 0; c < 3; c++)
{
- int val = rint ((*(float *) src) * 255.0);
+ float v;
+ int val;
+
+ memcpy(&v, src, sizeof(v));
+ val = rint (v * 255.0);
+
if (val < 0)
- *(unsigned char *) dst = 0;
+ *dst = 0;
else if (val > 255)
- *(unsigned char *) dst = 255;
+ *dst = 255;
else
- *(unsigned char *) dst = val;
+ *dst = val;
dst += 1;
src += 4;
}
@@ -151,7 +167,11 @@ conv_F_D (const Babl *conversion,unsigne
while (n--)
{
- *(double *) dst = ((*(float *) src));
+ float sv;
+ double dv;
+ memcpy(&sv, src, sizeof(sv));
+ dv = (float)sv;
+ memcpy(dst, &dv, sizeof(dv));
dst += 8;
src += 4;
}
@@ -164,7 +184,11 @@ conv_D_F (const Babl *conversion,unsigne
while (n--)
{
- *(float *) dst = ((*(double *) src));
+ float dv;
+ double sv;
+ memcpy(&sv, src, sizeof(sv));
+ dv = sv;
+ memcpy(dst, &dv, sizeof(dv));
dst += 4;
src += 8;
}
@@ -189,7 +213,9 @@ conv_16_8 (const Babl *conversion,unsign
while (n--)
{
- (*(unsigned char *) dst) = div_257 (*(unsigned short *) src);
+ unsigned short sv;
+ memcpy(&sv, src, sizeof(sv));
+ *dst = div_257 (sv);
dst += 1;
src += 2;
}
@@ -201,7 +227,8 @@ conv_8_16 (const Babl *conversion,unsign
long n = samples;
while (n--)
{
- (*(unsigned short *) dst) = *src << 8 | *src;
+ unsigned short dv = (*src << 8) | *src;
+ memcpy(dst, &dv, sizeof(dv));
dst += 2;
src += 1;
}
@@ -363,12 +390,14 @@ conv_gaF_gAF (const Babl *conversion,uns
while (n--)
{
- float alpha = (*(float *) (src + 4));
-
- *(float *) dst = ((*(float *) src) * alpha);
+ float alpha, sv;
+ memcpy(&alpha, src + 4, sizeof(alpha));
+ memcpy(&sv, src, sizeof(sv));
+ sv *= alpha;
+ memcpy(dst, &sv, sizeof(sv));
dst += 4;
src += 4;
- *(float *) dst = alpha;
+ memcpy(dst, &alpha, sizeof(alpha));
dst += 4;
src += 4;
}
@@ -381,15 +410,19 @@ conv_gAF_gaF (const Babl *conversion,uns
while (n--)
{
- float alpha = (*(float *) (src + 4));
+ float alpha, sv, dv;
+ memcpy(&alpha, src+4, sizeof(alpha));
if (alpha == 0.0f)
- *(float *) dst = 0.0f;
- else
- *(float *) dst = ((*(float *) src) / alpha);
+ dv = 0.0f;
+ else {
+ memcpy(&sv, src, sizeof(sv));
+ dv = sv / alpha;
+ }
+ memcpy(dst, &dv, sizeof(dv));
dst += 4;
src += 4;
- *(float *) dst = alpha;
+ memcpy(dst, &alpha, sizeof(alpha));
dst += 4;
src += 4;
}
@@ -404,16 +437,9 @@ conv_rgbaF_rgbF (const Babl *conversion,
while (n--)
{
- *(uint32_t *) dst = (*(uint32_t *) src);
- dst += 4;
- src += 4;
- *(uint32_t *) dst = (*(uint32_t *) src);
- dst += 4;
- src += 4;
- *(uint32_t *) dst = (*(uint32_t *) src);
- dst += 4;
- src += 4;
- src += 4;
+ memcpy(dst, src, 4*3);
+ dst += 4*3;
+ src += 4*4;
}
}
@@ -421,15 +447,12 @@ static void
conv_rgbF_rgbaF (const Babl *conversion,unsigned char *src, unsigned char *dst, long samples)
{
long n = samples;
- float *fsrc = (void*) src;
- float *fdst = (void*) dst;
+ float one = 1.0f;
while (n--)
{
- *fdst++ = *fsrc++;
- *fdst++ = *fsrc++;
- *fdst++ = *fsrc++;
- *fdst++ = 1.0f;
+ memcpy(dst, src, sizeof(float)*3);
+ memcpy(dst, &one, sizeof(one));
}
}
@@ -443,7 +466,7 @@ conv_gaF_gF (const Babl *conversion,unsi
while (n--)
{
- *(int *) dst = (*(int *) src);
+ memcpy(dst, src, 4);
dst += 4;
src += 4;
src += 4;
@@ -454,13 +477,14 @@ static void
conv_gF_gaF (const Babl *conversion,unsigned char *src, unsigned char *dst, long samples)
{
long n = samples;
+ float one = 1.0f;
while (n--)
{
- *(float *) dst = (*(float *) src);
+ memcpy(dst, src, sizeof(float));
dst += 4;
src += 4;
- *(float *) dst = 1.0;
+ memcpy(dst, &one, sizeof(one));
dst += 4;
}
}
@@ -482,7 +506,7 @@ conv_gF_rgbF (const Babl *conversion,uns
for (c = 0; c < 3; c++)
{
- (*(float *) dst) = (*(float *) src);
+ memcpy(dst, src, 4);
dst += 4;
}
src += 4;
@@ -531,11 +555,11 @@ conv_gaF_rgbaF (const Babl *conversion,u
for (c = 0; c < 3; c++)
{
- (*(int *) dst) = (*(int *) src);
+ memcpy(dst, src, 4);
dst += 4;
}
src += 4;
- (*(int *) dst) = (*(int *) src);
+ memcpy(dst, src, 4);
dst += 4;
src += 4;
}
@@ -553,16 +577,20 @@ conv_rgbaF_rgbA8 (const Babl *conversion
while (n--)
{
- float alpha = (*(float *) (src + (4 * 3)));
+ float alpha;
int c;
+ memcpy(&alpha, src + 4*3, sizeof(alpha));
+
for (c = 0; c < 3; c++)
{
- *(unsigned char *) dst = lrint (((*(float *) src) * alpha) * 255.0);
+ float sv;
+ memcpy(&sv, src, sizeof(sv));
+ *dst = lrint ((sv * alpha) * 255.0);
dst += 1;
src += 4;
}
- *(unsigned char *) dst = lrint (alpha * 255.0);
+ *dst = lrint (alpha * 255.0);
dst++;
src += 4;
}
@@ -579,12 +607,17 @@ conv_rgbaF_rgb16 (const Babl *conversion
for (c = 0; c < 3; c++)
{
- if ((*(float *) src) >= 1.0)
- *(unsigned short *) dst = 65535;
- else if ((*(float *) src) <=0)
- *(unsigned short *) dst = 0;
+ float sv;
+ unsigned short dv;
+
+ memcpy(&sv, src, sizeof(sv));
+ if (sv >= 1.0)
+ dv = 65535;
+ else if (sv <=0)
+ dv = 0;
else
- *(unsigned short *) dst = lrint ((*(float *) src) * 65535.0);
+ dv = lrint (sv * 65535.0);
+ memcpy(dst, &dv, 2);
dst += 2;
src += 4;
}
@@ -599,10 +632,14 @@ conv_rgbA16_rgbaF (const Babl *conversio
while (n--)
{
- float alpha = (((unsigned short *) src)[3]) / 65535.0;
+ unsigned short v;
+ float alpha;
int c;
float recip_alpha;
+ memcpy(&v, src+3*sizeof(unsigned short), sizeof(v));
+ alpha = v / 65535.0;
+
if (alpha == 0.0f)
recip_alpha = 10000.0;
else
@@ -610,11 +647,15 @@ conv_rgbA16_rgbaF (const Babl *conversio
for (c = 0; c < 3; c++)
{
- (*(float *) dst) = (*(unsigned short *) src / 65535.0) * recip_alpha;
+ float d;
+
+ memcpy(&v, src, sizeof(v));
+ d = (v / 65535.0) * recip_alpha;
+ memcpy(dst, &d, sizeof(d));
dst += 4;
src += 2;
}
- *(float *) dst = alpha;
+ memcpy(dst, &alpha, sizeof(alpha));
dst += 4;
src += 2;
}
@@ -624,16 +665,13 @@ static void
conv_gF_rgbaF (const Babl *conversion,unsigned char *src, unsigned char *dst, long samples)
{
long n = samples;
+ float one = 1.0f;
while (n--)
{
- *(int *) dst = (*(int *) src);
- dst += 4;
- *(int *) dst = (*(int *) src);
- dst += 4;
- *(int *) dst = (*(int *) src);
- dst += 4;
- *(float *) dst = 1.0;
+ memcpy(dst, src, 3*4);
+ dst += 3*4;
+ memcpy(dst, &one, sizeof(one));
dst += 4;
src += 4;
}
@@ -648,15 +686,18 @@ conv_gF_rgbaF (const Babl *conversion,un
int samples)
{
long n=samples;
+ float one = 1.0f;
+
while (n--) {
int c;
for (c = 0; c < 3; c++) {
- (*(float *) dst) = *(unsigned char *) src / 255.0;
+ float dv = *src / 255.0;
+ memcpy(dst, &dv, sizeof(dv));
dst += 4;
src += 1;
}
- (*(float *) dst) = 1.0;
+ memcpy(dst, &one, sizeof(one));
dst += 4;
}
}
@@ -667,15 +708,18 @@ conv_gF_rgbaF (const Babl *conversion,un
int samples)
{
long n=samples;
+ float one = 1.0f;
+
while (n--) {
int c;
for (c = 0; c < 3; c++) {
- (*(float *) dst) = *(unsigned char *) src / 255.0;
+ float v = *src / 255.0;
+ memcpy(dst, &v, sizeof(v));
dst += 4;
}
src += 1;
- (*(float *) dst) = 1.0;
+ memcpy(dst, &one, sizeof(one));
dst += 4;
}
}
@@ -686,15 +730,21 @@ conv_gF_rgbaF (const Babl *conversion,un
int samples)
{
long n=samples;
+ float one = 1.0f;
+
while (n--) {
int c;
for (c = 0; c < 3; c++) {
- *(float *) dst = (*(unsigned short *) src) / 65535.0;
+ unsigned short v;
+ float d;
+ memcpy(&v, src, sizeof(v));
+ d = v / 65535.0;
+ memcpy(dst, &d, sizeof(d));
src += 2;
dst += 4;
}
- *(float *) dst = 1.0;
+ memcpy(dst, &one, sizeof(one));
src += 2;
dst += 4;
}
@@ -706,14 +756,12 @@ conv_gF_rgbaF (const Babl *conversion,un
int samples)
{
long n=samples;
+ float one = 1.0f;
+
while (n--) {
- (*(float *) dst) = (*(float *) src);
- dst += 4;
- (*(float *) dst) = (*(float *) src);
- dst += 4;
- (*(float *) dst) = (*(float *) src);
- dst += 4;
- (*(float *) dst) = 1.0;
+ memcpy(dst, src, 4*3);
+ dst += 4*3;
+ memcpy(dst, &one, 4);
dst += 4;
src += 4;
@@ -729,11 +777,12 @@ conv_rgba8_rgbA8 (const Babl *conversion
{
if (src[3] == 255)
{
- *(unsigned int *) dst = *(unsigned int *) src;
+ memcpy(dst, src, 4);
}
else if (src[3] == 0)
{
- *(unsigned int *) dst = 0;
+ unsigned int zero = 0;
+ memcpy(dst, &zero, 4);
}
else
{
@@ -757,12 +806,13 @@ conv_rgbA8_rgba8 (const Babl *conversion
{
if (src[3] == 255)
{
- *(unsigned int *) dst = *(unsigned int *) src;
+ memcpy(dst, src, 4);
dst += 4;
}
else if (src[3] == 0)
{
- *(unsigned int *) dst = 0;
+ unsigned int zero = 0;
+ memcpy(dst, &zero, 4);
dst += 4;
}
else
@@ -786,7 +836,10 @@ conv_rgb8_rgba8 (const Babl *conversion,
long n = samples-1;
while (n--)
{
- *(unsigned int *) dst = (*(unsigned int *) src) | (255UL << 24);
+ unsigned int sv, dv;
+ memcpy(&sv, src, sizeof(sv));
+ dv = sv | (255UL << 24);
+ memcpy(dst, &dv, sizeof(dv));
src += 3;
dst += 4;
}
<file_sep># $NetBSD: Makefile,v 1.5 2019/04/02 13:18:07 nia Exp $
DISTNAME= papirus-icon-theme-20190331
CATEGORIES= graphics
MASTER_SITES= ${MASTER_SITE_GITHUB:=PapirusDevelopmentTeam/}
GITHUB_PROJECT= papirus-icon-theme
GITHUB_TAG= ${PKGVERSION_NOREV}
MAINTAINER= <EMAIL>
HOMEPAGE= https://github.com/PapirusDevelopmentTeam/papirus-icon-theme
COMMENT= SVG icon theme based on the Paper Icon Set
LICENSE= gnu-gpl-v3
EXTRACT_USING= bsdtar
USE_TOOLS+= gmake
ICON_THEMES= yes
.include "../../graphics/gnome-icon-theme/buildlink3.mk"
.include "../../graphics/hicolor-icon-theme/buildlink3.mk"
.include "../../mk/bsd.pkg.mk"
<file_sep>$NetBSD: patch-deps_openssl_config_archs_linux-elf_asm_openssl-cl.gypi,v 1.1 2019/01/21 11:00:45 ryoon Exp $
--- deps/openssl/config/archs/linux-elf/asm/openssl-cl.gypi.orig 2018-09-20 07:28:30.000000000 +0000
+++ deps/openssl/config/archs/linux-elf/asm/openssl-cl.gypi
@@ -28,8 +28,16 @@
'openssl_cflags_linux-elf': [
'-Wall -O3 -pthread -DL_ENDIAN -fomit-frame-pointer',
],
- 'openssl_ex_libs_linux-elf': [
- '-ldl -pthread',
+ 'conditions': [
+ ['OS=="linux"', {
+ 'openssl_ex_libs_linux-elf': [
+ '-ldl -pthread',
+ ],
+ }, {
+ 'openssl_ex_libs_linux-elf': [
+ '',
+ ],
+ }],
],
'openssl_cli_srcs_linux-elf': [
'openssl/apps/app_rand.c',
<file_sep># $NetBSD: Makefile,v 1.42 2019/04/18 07:22:08 adam Exp $
DISTNAME= nginx-1.15.12
MAINTAINER= <EMAIL>
.include "../../www/nginx/Makefile.common"
<file_sep># $NetBSD: Makefile,v 1.2 2018/09/01 12:04:56 tnn Exp $
UBOOT_TARGET= rockpro64
UBOOT_CONFIG= rockpro64-rk3399_defconfig
UBOOT_BIN= idbloader.img rksd_loader.img u-boot.itb
PKGREVISION= 1
UBOOT_VERSION= ${GITHUB_TAG:C/-.*$//}
MASTER_SITES= ${MASTER_SITE_GITHUB:=ayufan-rock64/}
GITHUB_PROJECT= linux-u-boot
GITHUB_TAG= 2017.09-rockchip-ayufan-1033-gdf02018479
DISTNAME= ${GITHUB_TAG}
DISTINFO_FILE= ${.CURDIR}/../../sysutils/u-boot-rockpro64/distinfo
PATCHDIR= ${.CURDIR}/../../sysutils/u-boot-rockpro64/patches
DISTFILES= ${DEFAULT_DISTFILES}
EXTRACT_SUFX= .tar.gz
# Boot Loader stage 3-1 (BL31) EL3 Runtime Firmware
# XXX LICENSE?
BL31= rk3399_bl31_v1.18.elf
DISTFILES+= ${BL31}
SITES.${BL31}= ${MASTER_SITE_GITHUB:=rockchip-linux/rkbin/raw/9e6625e7551ffa591f0ac4c271f12a7ab5cedcf4/bin/rk33/}
# DDR init binary
DDR_BIN= rk3399_ddr_800MHz_v1.14.bin
SITES.${DDR_BIN}= ${MASTER_SITE_GITHUB:=rockchip-linux/rkbin/raw/dbc8710a93406669fb2df2d57dc086228bf1979f/bin/rk33/}
DISTFILES+= ${DDR_BIN}
# pkgsrc tries to run distfiles that end in .bin; handle manually
EXTRACT_ONLY= ${DISTFILES:N*.bin}
USE_TOOLS+= gawk
MAKE_ENV+= BL31=${WRKDIR}/${BL31}
post-extract:
cp ${DISTDIR}/${DDR_BIN} ${WRKDIR}
post-build:
# build stage 3 package
cd ${WRKSRC} && ${SETENV} ${MAKE_ENV} ${MAKE_PROGRAM} u-boot.itb
# build stage 1 loader
${WRKSRC}/tools/mkimage -n rk3399 -T rksd -d ${WRKDIR}/${DDR_BIN} ${WRKSRC}/idbloader.img
# append stage2 loader
cat ${WRKSRC}/spl/u-boot-spl.bin >> ${WRKSRC}/idbloader.img
# wrap everything up into a single file that can be written to an SD card
cp ${WRKSRC}/idbloader.img ${WRKSRC}/rksd_loader.img
dd if=${WRKSRC}/u-boot.itb seek=448 conv=notrunc of=${WRKSRC}/rksd_loader.img
.include "../../sysutils/u-boot/u-boot-arm64.mk"
<file_sep>$NetBSD: patch-setup.py,v 1.1 2018/11/30 10:37:07 adam Exp $
Do not install examples; they have different requirements.
--- setup.py.orig 2018-11-30 10:28:52.000000000 +0000
+++ setup.py
@@ -150,7 +150,6 @@ if __name__ == "__main__":
download_url=release.download_url,
classifiers=release.classifiers,
packages=packages,
- data_files=data,
package_data=package_data,
install_requires=install_requires,
extras_require=extras_require,
<file_sep>$NetBSD: patch-src_effects_EffectManager.cpp,v 1.2 2019/02/10 17:14:42 nia Exp $
SunOS needs alloca.h for alloca().
--- src/effects/EffectManager.cpp.orig 2018-02-14 07:11:20.000000000 +0000
+++ src/effects/EffectManager.cpp
@@ -15,6 +15,10 @@
#include <wx/stopwatch.h>
#include <wx/tokenzr.h>
+#ifdef __sun
+#include <alloca.h>
+#endif
+
#include "../Experimental.h"
#include "../widgets/ErrorDialog.h"
<file_sep>$NetBSD: patch-src_mumble_AudioOutput.cpp,v 1.1 2018/12/22 18:17:39 nia Exp $
https://github.com/mumble-voip/mumble/pull/3287
--- src/mumble/AudioOutput.cpp.orig 2017-01-27 06:48:33.000000000 +0000
+++ src/mumble/AudioOutput.cpp
@@ -431,7 +431,7 @@ bool AudioOutput::mix(void *outbuff, uns
top[2] = 0.0f;
}
- if (std::abs<float>(front[0] * top[0] + front[1] * top[1] + front[2] * top[2]) > 0.01f) {
+ if (std::abs(front[0] * top[0] + front[1] * top[1] + front[2] * top[2]) > 0.01f) {
// Not perpendicular. Assume Y up and rotate 90 degrees.
float azimuth = 0.0f;
<file_sep>$NetBSD: patch-magic__build__and__package.sh,v 1.1 2019/04/19 14:02:03 fox Exp $
Disable build and packaging of tests.
--- magic_build_and_package.sh.orig 2019-04-10 11:18:54.578708528 +0000
+++ magic_build_and_package.sh
@@ -43,8 +43,8 @@ fi
echo '***** Building *****'
./mach build
-echo '***** Building tests *****'
-./mach build package-tests
+#echo '***** Building tests *****'
+#./mach build package-tests
echo '***** Packaging *****'
./mach package
<file_sep># $NetBSD: Makefile,v 1.3 2019/01/27 14:24:59 wen Exp $
CATEGORIES= devel
MAINTAINER= <EMAIL>
HOMEPAGE= https://github.com/r-lib/cli
COMMENT= Helpers for developing command line interfaces
LICENSE= mit
R_PKGNAME= cli
R_PKGVER= 1.0.1
DEPENDS+= R-assertthat-[0-9]*:../../devel/R-assertthat
DEPENDS+= R-crayon-[0-9]*:../../devel/R-crayon
USE_LANGUAGES= # none
BUILDLINK_API_DEPENDS.R+= R>=2.10
.include "../../math/R/Makefile.extension"
.include "../../mk/bsd.pkg.mk"
<file_sep>$NetBSD: patch-src_ircd.c,v 1.1 2019/02/08 13:09:35 fox Exp $
Properly check for possible fgets(3) errors (otherwise possible
unrelated errors are logged).
--- src/ircd.c.orig 2018-04-04 22:33:37.000000000 +0000
+++ src/ircd.c
@@ -265,8 +265,11 @@ check_pidfile(const char *filename)
if ((fb = fopen(filename, "r")))
{
if (!fgets(buf, 20, fb))
- ilog(LOG_TYPE_IRCD, "Error reading from pid file %s: %s",
- filename, strerror(errno));
+ {
+ if (ferror(fb))
+ ilog(LOG_TYPE_IRCD, "Error reading from pid file %s: %s",
+ filename, strerror(errno));
+ }
else
{
pid_t pid = atoi(buf);
<file_sep>$NetBSD: patch-gegl_gegl-config.c,v 1.1 2019/04/09 13:09:03 ryoon Exp $
--- gegl/gegl-config.c.orig 2019-02-25 19:00:08.000000000 +0000
+++ gegl/gegl-config.c
@@ -244,7 +244,11 @@ gegl_config_class_init (GeglConfigClass
#else
mem_total = sysconf (_SC_PHYS_PAGES) * sysconf (_SC_PAGESIZE);
+#if defined(_SC_AVPHYS_PAGES)
mem_available = sysconf (_SC_AVPHYS_PAGES) * sysconf (_SC_PAGESIZE);
+#else
+ mem_available = sysconf (_SC_PHYS_PAGES) * sysconf (_SC_PAGESIZE);
+#endif
#endif
default_tile_cache_size = mem_total;
<file_sep># $NetBSD: Makefile,v 1.2 2019/05/06 09:17:12 sjmulder Exp $
DISTNAME= bcal-2.1
CATEGORIES= math
MASTER_SITES= ${MASTER_SITE_GITHUB:=jarun/}
GITHUB_TAG= v${PKGVERSION_NOREV}
MAINTAINER= <EMAIL>
HOMEPAGE= https://github.com/jarun/bcal/
COMMENT= Storage and general-purpose calculator
LICENSE= gnu-gpl-v3
USE_TOOLS+= gmake
DEPENDS+= bc-[0-9]*:../../math/bc
MAKE_FLAGS+= MANDIR=${DESTDIR}${PREFIX}/${PKGMANDIR}/man1
.include "../../mk/readline.buildlink3.mk"
.include "../../mk/bsd.pkg.mk"
<file_sep># $NetBSD: Makefile,v 1.3 2019/05/06 09:17:13 sjmulder Exp $
DISTNAME= libxls-1.5.1
CATEGORIES= textproc
MASTER_SITES= ${MASTER_SITE_GITHUB:=libxls/}
GITHUB_RELEASE= v${PKGVERSION_NOREV}
MAINTAINER= <EMAIL>
HOMEPAGE= https://github.com/libxls/libxls
COMMENT= Extract cell data from legacy Microsoft Excel files
LICENSE= 2-clause-bsd
GNU_CONFIGURE= yes
# cplusplus/* is used for tests, but built always
USE_LANGUAGES= c c++11
USE_LIBTOOL= yes
TEST_TARGET= check
PKGCONFIG_OVERRIDE+= libxls.pc.in
.include "../../converters/libiconv/buildlink3.mk"
.include "../../mk/bsd.pkg.mk"
<file_sep># $NetBSD: Makefile,v 1.5 2019/01/22 09:57:05 adam Exp $
DISTNAME= flexmock-0.10.3
PKGNAME= ${PYPKGPREFIX}-${DISTNAME}
CATEGORIES= devel python
MASTER_SITES= ${MASTER_SITE_PYPI:=f/flexmock/}
MAINTAINER= <EMAIL>
HOMEPAGE= https://github.com/bkabrda/flexmock
COMMENT= Mock/Stub/Spy library for Python
LICENSE= 2-clause-bsd
USE_LANGUAGES= # none
.include "../../lang/python/egg.mk"
.include "../../mk/bsd.pkg.mk"
<file_sep>$NetBSD: patch-cmake_config-ix.cmake,v 1.2 2018/12/09 20:04:40 adam Exp $
Disable components that aren't ready for SunOS yet.
--- cmake/config-ix.cmake.orig 2018-07-25 03:01:35.000000000 +0000
+++ cmake/config-ix.cmake
@@ -500,7 +500,7 @@ set(COMPILER_RT_SANITIZERS_TO_BUILD all
list_replace(COMPILER_RT_SANITIZERS_TO_BUILD all "${ALL_SANITIZERS}")
if (SANITIZER_COMMON_SUPPORTED_ARCH AND NOT LLVM_USE_SANITIZER AND
- (OS_NAME MATCHES "Android|Darwin|Linux|FreeBSD|NetBSD|OpenBSD|Fuchsia|SunOS" OR
+ (OS_NAME MATCHES "Android|Darwin|Linux|FreeBSD|NetBSD|OpenBSD|Fuchsia" OR
(OS_NAME MATCHES "Windows" AND (NOT MINGW AND NOT CYGWIN))))
set(COMPILER_RT_HAS_SANITIZER_COMMON TRUE)
else()
@@ -520,7 +520,7 @@ else()
set(COMPILER_RT_HAS_ASAN FALSE)
endif()
-if (OS_NAME MATCHES "Linux|FreeBSD|Windows|NetBSD|SunOS")
+if (OS_NAME MATCHES "Linux|FreeBSD|Windows|NetBSD")
set(COMPILER_RT_ASAN_HAS_STATIC_RUNTIME TRUE)
else()
set(COMPILER_RT_ASAN_HAS_STATIC_RUNTIME FALSE)
@@ -557,7 +557,7 @@ else()
endif()
if (PROFILE_SUPPORTED_ARCH AND NOT LLVM_USE_SANITIZER AND
- OS_NAME MATCHES "Darwin|Linux|FreeBSD|Windows|Android|Fuchsia|SunOS")
+ OS_NAME MATCHES "Darwin|Linux|FreeBSD|Windows|Android|Fuchsia")
set(COMPILER_RT_HAS_PROFILE TRUE)
else()
set(COMPILER_RT_HAS_PROFILE FALSE)
@@ -571,7 +571,7 @@ else()
endif()
if (COMPILER_RT_HAS_SANITIZER_COMMON AND UBSAN_SUPPORTED_ARCH AND
- OS_NAME MATCHES "Darwin|Linux|FreeBSD|NetBSD|OpenBSD|Windows|Android|Fuchsia|SunOS")
+ OS_NAME MATCHES "Darwin|Linux|FreeBSD|NetBSD|OpenBSD|Windows|Android|Fuchsia")
set(COMPILER_RT_HAS_UBSAN TRUE)
else()
set(COMPILER_RT_HAS_UBSAN FALSE)
<file_sep>$NetBSD: patch-lib_isc_unix_socket.c,v 1.1 2019/04/30 03:34:34 taca Exp $
* Apply fixes from NetBSD base system.
--- lib/isc/unix/socket.c.orig 2019-04-06 20:09:59.000000000 +0000
+++ lib/isc/unix/socket.c
@@ -225,6 +225,7 @@ typedef enum { poll_idle, poll_active, p
(e) == EWOULDBLOCK || \
(e) == ENOBUFS || \
(e) == EINTR || \
+ (e) == ENOBUFS || \
(e) == 0)
#define DLVL(x) ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_SOCKET, ISC_LOG_DEBUG(x)
@@ -366,6 +367,10 @@ struct isc__socket {
unsigned char overflow; /* used for MSG_TRUNC fake */
#endif
+ void *fdwatcharg;
+ isc_sockfdwatch_t fdwatchcb;
+ int fdwatchflags;
+ isc_task_t *fdwatchtask;
unsigned int dscp;
};
@@ -452,10 +457,14 @@ static void free_socket(isc__socket_t **
static isc_result_t allocate_socket(isc__socketmgr_t *, isc_sockettype_t,
isc__socket_t **);
static void destroy(isc__socket_t **);
+#if 0
static void internal_accept(isc__socket_t *);
+#endif
static void internal_connect(isc__socket_t *);
static void internal_recv(isc__socket_t *);
static void internal_send(isc__socket_t *);
+static void internal_fdwatch_write(isc__socket_t *);
+static void internal_fdwatch_read(isc__socket_t *);
static void process_cmsg(isc__socket_t *, struct msghdr *, isc_socketevent_t *);
static void build_msghdr_send(isc__socket_t *, char *, isc_socketevent_t *,
struct msghdr *, struct iovec *, size_t *);
@@ -1576,6 +1585,7 @@ doio_recv(isc__socket_t *sock, isc_socke
case isc_sockettype_udp:
case isc_sockettype_raw:
break;
+ case isc_sockettype_fdwatch:
default:
INSIST(0);
ISC_UNREACHABLE();
@@ -1778,9 +1788,26 @@ socketclose(isc__socketthread_t *thread,
*/
LOCK(&thread->fdlock[lockid]);
thread->fds[fd] = NULL;
- thread->fdstate[fd] = CLOSE_PENDING;
+ if (sock->type == isc_sockettype_fdwatch)
+ thread->fdstate[fd] = CLOSED;
+ else
+ thread->fdstate[fd] = CLOSE_PENDING;
UNLOCK(&thread->fdlock[lockid]);
- select_poke(thread->manager, thread->threadid, fd, SELECT_POKE_CLOSE);
+ if (sock->type == isc_sockettype_fdwatch) {
+ /*
+ * The caller may close the socket once this function returns,
+ * and `fd' may be reassigned for a new socket. So we do
+ * unwatch_fd() here, rather than defer it via select_poke().
+ * Note: this may complicate data protection among threads and
+ * may reduce performance due to additional locks. One way to
+ * solve this would be to dup() the watched descriptor, but we
+ * take a simpler approach at this moment.
+ */
+ (void)unwatch_fd(thread, fd, SELECT_POKE_READ);
+ (void)unwatch_fd(thread, fd, SELECT_POKE_WRITE);
+ } else
+ select_poke(thread->manager, thread->threadid, fd,
+ SELECT_POKE_CLOSE);
inc_stats(thread->manager->stats, sock->statsindex[STATID_CLOSE]);
if (sock->active == 1) {
@@ -2187,6 +2214,13 @@ opensocket(isc__socketmgr_t *manager, is
}
#endif
break;
+ case isc_sockettype_fdwatch:
+ /*
+ * We should not be called for isc_sockettype_fdwatch
+ * sockets.
+ */
+ INSIST(0);
+ break;
}
} else {
sock->fd = dup(dup_socket->fd);
@@ -2485,6 +2519,7 @@ socket_create(isc_socketmgr_t *manager0,
REQUIRE(VALID_MANAGER(manager));
REQUIRE(socketp != NULL && *socketp == NULL);
+ REQUIRE(type != isc_sockettype_fdwatch);
result = allocate_socket(manager, type, &sock);
if (result != ISC_R_SUCCESS)
@@ -2605,6 +2640,7 @@ isc_socket_open(isc_socket_t *sock0) {
*/
REQUIRE(sock->fd == -1);
REQUIRE(sock->threadid == -1);
+ REQUIRE(sock->type != isc_sockettype_fdwatch);
result = opensocket(sock->manager, sock, NULL);
if (result != ISC_R_SUCCESS) {
@@ -2684,6 +2720,7 @@ isc_socket_close(isc_socket_t *sock0) {
LOCK(&sock->lock);
+ REQUIRE(sock->type != isc_sockettype_fdwatch);
REQUIRE(sock->fd >= 0 && sock->fd < (int)sock->manager->maxsocks);
INSIST(!sock->connecting);
@@ -2714,6 +2751,24 @@ isc_socket_close(isc_socket_t *sock0) {
return (ISC_R_SUCCESS);
}
+static void
+dispatch_recv(isc__socket_t *sock) {
+ if (sock->type != isc_sockettype_fdwatch) {
+ internal_recv(sock);
+ } else {
+ internal_fdwatch_read(sock);
+ }
+}
+
+static void
+dispatch_send(isc__socket_t *sock) {
+ if (sock->type != isc_sockettype_fdwatch) {
+ internal_send(sock);
+ } else {
+ internal_fdwatch_write(sock);
+ }
+}
+
/*
* Dequeue an item off the given socket's read queue, set the result code
* in the done event to the one provided, and send it to the task it was
@@ -2790,6 +2845,7 @@ send_connectdone_event(isc__socket_t *so
isc_task_sendtoanddetach(&task, (isc_event_t **)dev, sock->threadid);
}
+#if 0
/*
* Call accept() on a socket, to get the new file descriptor. The listen
* socket is used as a prototype to create a new isc_socket_t. The new
@@ -3048,6 +3104,7 @@ internal_accept(isc__socket_t *sock) {
inc_stats(manager->stats, sock->statsindex[STATID_ACCEPTFAIL]);
return;
}
+#endif
static void
internal_recv(isc__socket_t *sock) {
@@ -3154,6 +3211,64 @@ internal_send(isc__socket_t *sock) {
UNLOCK(&sock->lock);
}
+static void
+internal_fdwatch_write(isc__socket_t *sock)
+{
+ int more_data;
+
+ INSIST(VALID_SOCKET(sock));
+
+ LOCK(&sock->lock);
+ isc_refcount_increment(&sock->references);
+ UNLOCK(&sock->lock);
+
+ more_data = (sock->fdwatchcb)(sock->fdwatchtask, (isc_socket_t *)sock,
+ sock->fdwatcharg, ISC_SOCKFDWATCH_WRITE);
+
+ LOCK(&sock->lock);
+
+ if (isc_refcount_decrement(&sock->references) == 0) {
+ UNLOCK(&sock->lock);
+ destroy(&sock);
+ return;
+ }
+
+ if (more_data)
+ select_poke(sock->manager, sock->threadid, sock->fd,
+ SELECT_POKE_WRITE);
+
+ UNLOCK(&sock->lock);
+}
+
+static void
+internal_fdwatch_read(isc__socket_t *sock)
+{
+ int more_data;
+
+ INSIST(VALID_SOCKET(sock));
+
+ LOCK(&sock->lock);
+ isc_refcount_increment(&sock->references);
+ UNLOCK(&sock->lock);
+
+ more_data = (sock->fdwatchcb)(sock->fdwatchtask, (isc_socket_t *)sock,
+ sock->fdwatcharg, ISC_SOCKFDWATCH_READ);
+
+ LOCK(&sock->lock);
+
+ if (isc_refcount_decrement(&sock->references) == 0) {
+ UNLOCK(&sock->lock);
+ destroy(&sock);
+ return;
+ }
+
+ if (more_data)
+ select_poke(sock->manager, sock->threadid, sock->fd,
+ SELECT_POKE_READ);
+
+ UNLOCK(&sock->lock);
+}
+
/*
* Process read/writes on each fd here. Avoid locking
* and unlocking twice if both reads and writes are possible.
@@ -3194,7 +3309,7 @@ process_fd(isc__socketthread_t *thread,
if (readable) {
if (sock->listener) {
- internal_accept(sock);
+ dispatch_recv(sock);
} else {
internal_recv(sock);
}
@@ -3204,7 +3319,7 @@ process_fd(isc__socketthread_t *thread,
if (sock->connecting) {
internal_connect(sock);
} else {
- internal_send(sock);
+ dispatch_send(sock);
}
}
@@ -3858,8 +3973,8 @@ isc_socketmgr_create2(isc_mem_t *mctx, i
&manager->threads[i],
&manager->threads[i].thread)
== ISC_R_SUCCESS);
- char tname[1024];
- sprintf(tname, "isc-socket-%d", i);
+ char tname[128];
+ snprintf(tname, sizeof(tname), "sock-%d", i);
isc_thread_setname(manager->threads[i].thread, tname);
}
@@ -5326,7 +5441,7 @@ static isc_once_t hasreuseport_once = IS
static bool hasreuseport = false;
static void
-init_hasreuseport() {
+init_hasreuseport(void) {
/*
* SO_REUSEPORT works very differently on *BSD and on Linux (because why not).
* We only want to use it on Linux, if it's available. On BSD we want to dup()
@@ -5376,6 +5491,8 @@ _socktype(isc_sockettype_t type)
return ("tcp");
case isc_sockettype_unix:
return ("unix");
+ case isc_sockettype_fdwatch:
+ return ("fdwatch");
default:
return ("not-initialized");
}
@@ -5605,3 +5722,112 @@ isc_socketmgr_createinctx(isc_mem_t *mct
return (result);
}
+
+/*
+ * Create a new 'type' socket managed by 'manager'. Events
+ * will be posted to 'task' and when dispatched 'action' will be
+ * called with 'arg' as the arg value. The new socket is returned
+ * in 'socketp'.
+ */
+isc_result_t
+isc_socket_fdwatchcreate(isc_socketmgr_t *manager0, int fd, int flags,
+ isc_sockfdwatch_t callback, void *cbarg,
+ isc_task_t *task, isc_socket_t **socketp)
+{
+ isc__socketmgr_t *manager = (isc__socketmgr_t *)manager0;
+ isc__socket_t *sock = NULL;
+ isc__socketthread_t *thread;
+ isc_result_t result;
+ int lockid;
+
+ REQUIRE(VALID_MANAGER(manager));
+ REQUIRE(socketp != NULL && *socketp == NULL);
+
+ if (fd < 0 || (unsigned int)fd >= manager->maxsocks)
+ return (ISC_R_RANGE);
+
+ result = allocate_socket(manager, isc_sockettype_fdwatch, &sock);
+ if (result != ISC_R_SUCCESS)
+ return (result);
+
+ sock->fd = fd;
+ sock->fdwatcharg = cbarg;
+ sock->fdwatchcb = callback;
+ sock->fdwatchflags = flags;
+ sock->fdwatchtask = task;
+
+ sock->threadid = gen_threadid(sock);
+ isc_refcount_init(&sock->references, 1);
+ thread = &manager->threads[sock->threadid];
+ *socketp = (isc_socket_t *)sock;
+
+ /*
+ * Note we don't have to lock the socket like we normally would because
+ * there are no external references to it yet.
+ */
+
+ lockid = FDLOCK_ID(sock->fd);
+ LOCK(&thread->fdlock[lockid]);
+ thread->fds[sock->fd] = sock;
+ thread->fdstate[sock->fd] = MANAGED;
+
+#if defined(USE_EPOLL)
+ manager->threads->epoll_events[sock->fd] = 0;
+#endif
+ UNLOCK(&thread->fdlock[lockid]);
+
+ LOCK(&manager->lock);
+ ISC_LIST_APPEND(manager->socklist, sock, link);
+#ifdef USE_SELECT
+ if (manager->maxfd < sock->fd)
+ manager->maxfd = sock->fd;
+#endif
+ UNLOCK(&manager->lock);
+
+ sock->active = 1;
+ if (flags & ISC_SOCKFDWATCH_READ)
+ select_poke(sock->manager, sock->threadid, sock->fd,
+ SELECT_POKE_READ);
+ if (flags & ISC_SOCKFDWATCH_WRITE)
+ select_poke(sock->manager, sock->threadid, sock->fd,
+ SELECT_POKE_WRITE);
+
+ socket_log(sock, NULL, CREATION, "fdwatch-created");
+
+ return (ISC_R_SUCCESS);
+}
+
+/*
+ * Indicate to the manager that it should watch the socket again.
+ * This can be used to restart watching if the previous event handler
+ * didn't indicate there was more data to be processed. Primarily
+ * it is for writing but could be used for reading if desired
+ */
+
+isc_result_t
+isc_socket_fdwatchpoke(isc_socket_t *sock0, int flags)
+{
+ isc__socket_t *sock = (isc__socket_t *)sock0;
+
+ REQUIRE(VALID_SOCKET(sock));
+
+ /*
+ * We check both flags first to allow us to get the lock
+ * once but only if we need it.
+ */
+
+ if ((flags & (ISC_SOCKFDWATCH_READ | ISC_SOCKFDWATCH_WRITE)) != 0) {
+ LOCK(&sock->lock);
+ if ((flags & ISC_SOCKFDWATCH_READ) != 0)
+ select_poke(sock->manager, sock->threadid, sock->fd,
+ SELECT_POKE_READ);
+ if ((flags & ISC_SOCKFDWATCH_WRITE) != 0)
+ select_poke(sock->manager, sock->threadid, sock->fd,
+ SELECT_POKE_WRITE);
+ UNLOCK(&sock->lock);
+ }
+
+ socket_log(sock, NULL, TRACE, "fdwatch-poked flags: %d", flags);
+
+ return (ISC_R_SUCCESS);
+}
|
f81b00acb16519b6ee9bc6ad742db0342725c446
|
[
"CMake",
"Makefile",
"Rust",
"Python",
"C",
"C++",
"Shell"
] | 70 |
Makefile
|
realzhtw/pkgsrc
|
77e604449bf22ee3df039bab5a8169bce4deef38
|
f37ea4f9c0321cae1ef98090882fd09961af08be
|
refs/heads/master
|
<repo_name>wilmercity93/Proyecto-Escuela<file_sep>/preguntas/edit.php
<?php
include('conn.php');
$id=$_GET['id'];
$pregunta=$_POST['pregunta'];
$a=$_POST['a'];
$b=$_POST['b'];
$c=$_POST['c'];
$d=$_POST['d'];
$respuesta=$_POST['respuesta'];
mysqli_query($conn,"update pregunta set pregunta='$pregunta', a='$a', b='$b', c='$c', d='$d', respuesta='$respuesta' where id='$id'");
header('location:index.php');
?><file_sep>/README.md
# Proyecto-Escuela
Este proyecto consiste en realizar unas series de pruebas que contengan preguntas, para luego ingresar y resolverlas de acuerdo
con la prueba, donde se obtendra un resultado final, las preguntas cuentan con un tiempo estimado y todas tienen un porcentaje
igual al ser evaluadas.
Tecnologias:
-> MySqlLi
-> HTML5
-> CSS3
-> PHP 5.6.33
-> JQuery
-> Boostrap
-> XAMPP
-> Tomcat Server
<file_sep>/preguntas/index.php
<!DOCTYPE html>
<html>
<head>
<title>PREGUNTAS</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<?php
$id_prueba = $_REQUEST['id_prueba'];
?>
<div style="height:50px;"></div>
<div class="well" style="margin:auto; padding:auto; width:100%;">
<span style="font-size:30px;"><center><strong>PREGUNTAS</strong></center></span>
<span class="pull-left"><a href="#addnew" data-toggle="modal" class="btn btn-primary"><span class="glyphicon glyphicon-plus"></span> Add New</a></span>
<span class="pull-right"><a href="../pruebas/index.php?id_prueba=<?php echo $id_prueba; ?>" class="btn btn-secondary btn-lg"><span class="glyphicon glyphicon-share"></span> Regresar Pruebas</a></span>
<div style="height:50px;"></div>
<table class="table table-striped table-bordered table-hover">
<thead>
<th>Preguntas</th>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>Respuestas</th>
<th>Prueba</th>
<th>Action</th>
</thead>
<tbody>
<?php
include('conn.php');
$query=mysqli_query($conn,"select pre.id,pre.pregunta, pre.a,pre.b,pre.c,pre.d,pre.respuesta,pru.descripcion from `pregunta` as pre, `prueba` as pru where pru.id = pre.prueba_id and pru.id ='+$id_prueba+' ");
while($row=mysqli_fetch_array($query)){
?>
<tr>
<td><?php echo $row['pregunta']; ?></td>
<td><?php echo $row['a']; ?></td>
<td><?php echo $row['b']; ?></td>
<td><?php echo $row['c']; ?></td>
<td><?php echo $row['d']; ?></td>
<td><?php echo $row['respuesta']; ?></td>
<td><?php echo $row['descripcion']; ?></td>
<td>
<a href="#edit<?php echo $row['id']; ?>" data-toggle="modal" class="btn btn-warning"><span class="glyphicon glyphicon-edit"></span> Edit</a> ||
<a href="#del<?php echo $row['id']; ?>" data-toggle="modal" class="btn btn-danger"><span class="glyphicon glyphicon-trash"></span> Delete</a>
<?php include('button.php'); ?>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<?php include('add_modal.php'); ?>
</div>
</body>
</html><file_sep>/quizzer-master/README.md
# quizzer
Código del ejemplo
<file_sep>/pruebas/edit.php
<?php
include('conn.php');
$id=$_GET['id'];
$descripcion=$_POST['descripcion'];
mysqli_query($conn,"update prueba set descripcion='$descripcion'where id='$id'");
header('location:index.php');
?><file_sep>/pruebas/addnew.php
<?php
include('conn.php');
$descripcion = $_POST['descripcion'];
mysqli_query($conn,"insert into prueba (descripcion) values ('$descripcion')");
header('location:index.php');
?><file_sep>/quizzer-master/conn.php
<?php
//MySQLi Procedural
$conn = mysqli_connect("localhost","root","","examen");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// obtener un array asociativo
$arrRespuesta=array();
$query=mysqli_query($conn,"select pregunta,a,b,c,d,respuesta from `pregunta` where prueba_id = 1");
while($filas=mysqli_fetch_array($query)){
$arrRespuesta[]=$filas;
}
// echo json_encode(array('success' => 1));
echo json_encode($arrRespuesta);
?><file_sep>/preguntas/addnew.php
<?php
include('conn.php');
$pregunta=$_POST['pregunta'];
$a=$_POST['a'];
$b=$_POST['b'];
$c=$_POST['c'];
$d=$_POST['d'];
$respuesta=$_POST['respuesta'];
$prueba_id=$_POST['prueba_id'];
//$prueba_id = 1;
mysqli_query($conn,"insert into pregunta (pregunta, a, b, c, d, respuesta, prueba_id) values ('$pregunta', '$a', '$b', '$c', '$d', '$respuesta', '$prueba_id')");
header('location:index.php');
?><file_sep>/preguntas/add_modal.php
<!-- Add New -->
<div class="modal fade" id="addnew" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<center><h4 class="modal-title" id="myModalLabel">Add New</h4></center>
</div>
<div class="modal-body">
<div class="container-fluid">
<form method="POST" action="addnew.php">
<div class="row">
<div class="col-lg-2">
<label class="control-label" style="position:relative; top:7px;">Pregunta:</label>
</div>
<div class="col-lg-10">
<input type="text" class="form-control" name="pregunta">
</div>
</div>
<div style="height:10px;"></div>
<div class="row">
<div class="col-lg-2">
<label class="control-label" style="position:relative; top:7px;">A:</label>
</div>
<div class="col-lg-10">
<input type="text" class="form-control" name="a">
</div>
</div>
<div style="height:10px;"></div>
<div class="row">
<div class="col-lg-2">
<label class="control-label" style="position:relative; top:7px;">B:</label>
</div>
<div class="col-lg-10">
<input type="text" class="form-control" name="b">
</div>
</div>
<div style="height:10px;"></div>
<div class="row">
<div class="col-lg-2">
<label class="control-label" style="position:relative; top:7px;">C:</label>
</div>
<div class="col-lg-10">
<input type="text" class="form-control" name="c">
</div>
</div>
<div style="height:10px;"></div>
<div class="row">
<div class="col-lg-2">
<label class="control-label" style="position:relative; top:7px;">D:</label>
</div>
<div class="col-lg-10">
<input type="text" class="form-control" name="d">
</div>
</div>
<div style="height:10px;"></div>
<div class="row">
<div class="col-lg-2">
<label class="control-label" style="position:relative; top:7px;">Respuesta:</label>
</div>
<div class="col-lg-10">
<select type="text" name="respuesta" required>
<option value="" >SELECCIONAR</option>
<option value="0">A</option>
<option value="1">B</option>
<option value="2">C</option>
<option value="3">D</option>
</select>
</div>
</div>
<div style="height:10px;"></div>
<div class="row">
<div class="col-lg-2">
<label class="control-label" style="position:relative; top:7px;">Prueba:</label>
</div>
<div class="col-lg-10" >
<input type="number" class="form-control" name="prueba_id" value ="<?php echo $id_prueba ?>" disabled>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
<button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-floppy-disk"></span> Save</a>
</form>
</div>
</div>
</div>
</div>
|
086fa146f7008cf37898595491b60a623b6efeb4
|
[
"Markdown",
"PHP"
] | 9 |
PHP
|
wilmercity93/Proyecto-Escuela
|
ebe4ead621246fc439c58d7b50a164463d607bd7
|
bb07a983d104acba6ae28d30922394f9252839e0
|
refs/heads/master
|
<repo_name>weakit/GCI19-NewsScraper<file_sep>/README.md
# News Scraper
A simple news scraper in python.
Finds articles of interest from [newsapi.org](https://newsapi.org/ "News API"), renders html with the articles, and then opens them in your browser.
You need to set `API_KEY` in `newslist.py` for the script to work. Get one from [newsapi.org](https://newsapi.org/ "News API"). \
While you're doing that, feel free to edit the keywords to get articles specific to your interests.
Video demo [here](https://youtu.be/hvNQfspKybg).
<file_sep>/newslist.py
#!/usr/bin/env python3
import json
import time
import tempfile
import webbrowser
import requests as r
API_KEY = '<KEY>'
ENDPOINT = 'https://newsapi.org/v2/everything?q={}&apiKey={}'
keywords = ('linux', 'open source', 'android')
article_html = open('article.min.html').read()
news_html = open('news.min.html').read()
def get_tags():
st = keywords[0]
for keyword in keywords[1:]:
st += ' • ' + keyword
return st
def get_list(keyword):
url = ENDPOINT.format(keyword, API_KEY)
req = r.get(url)
if req.status_code == 200:
return json.loads(req.text)['articles']
return None
def parse_article(article):
return {
'title': article['title'],
'author': article['author'],
'description': article['description'],
'link': article['url'],
'image': article['urlToImage'],
'site': article['source']['name']
}
def render_articles(articles):
return [article_html.format(**parse_article(article)) for article in articles]
def get_articles():
articles = []
for keyword in keywords:
articles += get_list(keyword)
articles.sort(key=lambda x: x['publishedAt'], reverse=True)
return render_articles(articles)
def render_page():
return news_html.replace('{tags}', get_tags()).replace('{articles}', ''.join(get_articles()))
if __name__ == '__main__':
print("Scraping news.")
html = render_page()
print("Done. Displaying News.")
temp = tempfile.NamedTemporaryFile(suffix='.html')
temp.write(html.encode())
webbrowser.open_new(temp.name)
time.sleep(5)
print("Exiting.")
|
708cf111c634456df11ad1df21f05a28a73497ae
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
weakit/GCI19-NewsScraper
|
7d139e5413e548f6117f1d656d8513a2a3f987aa
|
d4a22c2a06602b1190a3630ea9e5272372efff3d
|
refs/heads/master
|
<file_sep>//Modelos de negocio
import User from '../models/User';
import Task from '../models/Task';
import ItemTask from '../models/ItemTask';
//Schemas de la base de datos
import { ItemModel } from './schemas/itemTaskSchema';
import { TaskModel } from './schemas/TaskSchema';
import { UserModel } from './schemas/UserSchema';
export default class MongoConnection {
public async getOneUser(data:any):Promise<User>{
let userMongo:any = await UserModel.findOne({name:data.name,password:data.<PASSWORD>}).populate('tasks').exec();
let temp:User = new User(userMongo.name,userMongo.password);
temp.setId(userMongo._id);
temp.setTasks(userMongo.tasks);
return temp;
}
public getUsers():Promise<User[]>{
return UserModel.find().then((users:any[]) => {
let arrayUsers:User[] = [];
for(let e of users){
let temp:User = new User(e.name,e.password);
temp.setId(e._id);
temp.setTasks(e.tasks);
arrayUsers.push(temp);
}
return arrayUsers;
}).catch( () => {return []} );
}
public async createUser(user:User):Promise<User>{
const dataUser = new UserModel(user);
let result = await dataUser.save();
user.setId(result._id);
return user;
}
public async createTask(idUser:string,task:Task):Promise<Task>{
const taskData = new TaskModel(task);
let result:any = await taskData.save();
let user:any = await UserModel.findOne({_id:idUser});
user.tasks.push(result._id);
await user.save();
return task;
}
public async createItemTask(idTask:string,itemTask:ItemTask):Promise<ItemTask>{
const itemTaskData = new ItemModel(itemTask);
let result:any = await itemTaskData.save();
let task:any = await TaskModel.findOne({_id:idTask});
task.itemTasks.push(result._id);
await task.save();
return itemTask;
}
public async updateUser(userData:User):Promise<User>{
let user:any = await UserModel.findOne({_id:userData.getId()});
for(let key in user){
if(userData.toObject().hasOwnProperty(key)){
user[key] = userData[key];
}
}
await user.save();
return userData;
}
public async updateTask(taskData:Task):Promise<any>{
let task:any = await TaskModel.findOne({_id:taskData.getId()});
for(let key in task){
if(taskData.toObject().hasOwnProperty(key)){
task[key] = taskData[key];
}
}
await task.save();
return taskData;
}
public async updateItemTask(idTask:string,data:ItemTask):Promise<any>{
let task:any = await TaskModel.findOne({_id:idTask});
let tempItem = task.itemTasks[data.getID()];
let itemTask = await ItemModel.findOneAndUpdate({_id:tempItem},{id:data.getID(),isDone:data.getIsDone(),text:data.getText()});
return itemTask;
}
}<file_sep>import { model,Schema } from 'mongoose';
const UserSchema:Schema = new Schema({
name:{type:String,required:true},
password:{type:String,required:true},
tasks:[{type: Schema.Types.ObjectId,ref: 'Task'}]
});
export const UserModel = model('User',UserSchema);<file_sep>import ItemTask from './ItemTask';
export default class Task{
private _id:string;
private title:string;
private description:string;
private isDone:boolean;
private startDate:Date;
private endDate:Date;
private itemsTasks:ItemTask[];
constructor(title:string, description:string, isDone:boolean, startDate:Date, endDate:Date, itemsTasks:ItemTask[]){
this.title = title;
this.description = description;
this.isDone = isDone;
this.startDate = startDate;
this.endDate = endDate;
this.itemsTasks = itemsTasks;
}
public getId():string{
return this._id;
}
public getTitle():string{
return this.title;
}
public getDescription():string{
return this.description;
}
public getIsDone():boolean{
return this.isDone;
}
public getStartDate():Date{
return this.startDate;
}
public getEndDate():Date{
return this.endDate;
}
public getItemsTasks():ItemTask[]{
return this.itemsTasks;
}
public setId(id:string):void{
this._id = id;
}
public setTitle(title:string):void{
this.title = title;
}
public setDescription(description:string):void{
this.description = description;
}
public setIsDone(isDone:boolean):void{
this.isDone = isDone;
}
public setStartDate(startDate:Date):void{
this.startDate = startDate;
}
public setEndDate(endDate:Date):void{
this.endDate = endDate;
}
public setItemsTasks(itemsTasks:ItemTask[]):void{
this.itemsTasks = itemsTasks;
}
public toObject():Object{
return {_id:this._id,description:this.description,isDone:this.isDone,itemsTasks:this.itemsTasks,endDate:this.endDate,startDate:this.startDate}
}
}<file_sep>import { model,Schema } from 'mongoose';
const itemTask:Schema = new Schema({
id:{type:Number,required:true},
isDone:{type:Boolean,required:true},
text:{type:String,required:true}
});
export const ItemModel = model('ItemTask',itemTask);<file_sep># Todo-Grapql-Server
Aplicación del lado del servidor con arqutectura graphql para el backend de una aplicación de tareas
## Autor
- <NAME><file_sep>#!/bin/bash
rm -rf dist
yarn compile
#clear
cp src/config/graphql/schema.graphql dist/config/graphql
yarn start<file_sep>import { GraphQLSchema } from 'graphql';
import { loadSchemaSync,GraphQLFileLoader,addResolversToSchema } from 'graphql-tools';
import { resolve } from 'path';
import { resolvers } from './resolvers';
const dataSchema:GraphQLSchema = loadSchemaSync(resolve('../src/config',__dirname, './schema.graphql'),{
loaders:[new GraphQLFileLoader()]
});
export const finalSchema:GraphQLSchema = addResolversToSchema(
dataSchema,resolvers
);<file_sep>import { model,Schema } from 'mongoose';
const TaskSchema:Schema = new Schema({
title:{type:String,required:true},
description:{type:String,required:true},
isDone:{type:Boolean,required:true},
startDate:{type:Date,required:true},
endDate:{type:Date,required:true},
itemTasks:[{type: Schema.Types.ObjectId,ref: 'ItemTask'}]
});
export const TaskModel = model('Task',TaskSchema);<file_sep>import { IResolvers } from 'graphql-tools';
import { Date } from 'graphql-tools-types';
import MongoConnection from '../../db/MongoConection';
import ItemTask from '../../models/ItemTask';
import Task from '../../models/Task';
import User from '../../models/User';
let databaseConnection:MongoConnection = new MongoConnection();
export const resolvers:IResolvers = {
Date:Date({name: "Date" }),
Query:{
getUser: (_:any,{ user }) => { return databaseConnection.getOneUser(user); },
getUsers: async () => { return await databaseConnection.getUsers(); }
},
Mutation:{
createUser: async (_:any,{ userInput }) => {
let user:User = new User(userInput.name,userInput.password);
return await databaseConnection.createUser(user);
},
createTaskData: async (_:any,{ idUser,taskInput }) => {
let task:Task = new Task(taskInput.title,taskInput.description,taskInput.isDone,taskInput.startDate,taskInput.endDate,taskInput.itemsTasks);
let result = await databaseConnection.createTask(idUser,task);
return result;
},
createItemTask:async (_:any,{ idTask,itemTaskInput })=>{
let item:ItemTask = new ItemTask(itemTaskInput.id,itemTaskInput.isDone,itemTaskInput.text);
return await databaseConnection.createItemTask(idTask,item);
},
updateUserInfo:async (_:any,{ idUser,userData }) => {
let user:User = new User(userData.name,userData.password);
user.setTasks(userData.tasks);
user.setId(idUser);
return databaseConnection.updateUser(user);
},
updateTaskInfo:async (_:any,{ idTask,taskData }) => {
let task:Task = new Task(taskData.title,taskData.description,taskData.isDone,taskData.startDate,taskData.endDate,taskData.itemsTasks);
task.setId(idTask);
return await databaseConnection.updateTask(task);
},
updateItemTaskInfo:async (_:any,{ idTask,itemData }) => {
let item:ItemTask = new ItemTask(itemData.id,itemData.isDone,itemData.text);
return await databaseConnection.updateItemTask(idTask,item);
}
}
}<file_sep>import Task from './Task';
export default class User{
public _id: string | number;
private name:string;
private password:string;
private tasks: Task[];
public constructor (name:string,password:string){
this.name = name;
this.password = <PASSWORD>;
this.tasks = [];
}
public setTasks(tasks:Task[]):void{
this.tasks = tasks;
}
public setId(id:string):void{
this._id = id;
}
public getId():string | number{
return this._id;
}
public getName():string{
return this.name;
}
public getTasks():Task[]{
return this.tasks;
}
public getPassword():string{
return <PASSWORD>;
}
public toObject():Object{
return {_id:this._id,name:this.name,password:<PASSWORD>,tasks:this.tasks};
}
}<file_sep>import { connect } from 'mongoose';
export function startDatabaseConnection(){
connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('Base de datos conectada');
}).catch((error) => {
console.log(error);
});
}<file_sep>import express = require('express');
import cors = require('cors');
import { config } from 'dotenv'
import { resolve } from 'path';
import { Application } from 'express';
import { graphqlHTTP } from 'express-graphql';
import { finalSchema } from '../graphql/schemaConfig';
import { startDatabaseConnection } from './dataBase';
export const initServer = async () => {
await config({path:resolve('.env')});
startDatabaseConnection();
const grahqlServer = graphqlHTTP({
schema:finalSchema,
graphiql:true
});
const server:Application = express();
server.use('*',cors());
server.use('/',grahqlServer);
server.listen(process.env.PORT,() => {
console.log(`server running in http://localhost:${process.env.PORT}/`);
});
}<file_sep>import { initServer } from './config/server/initServer';
initServer();<file_sep>export default class ItemTask{
private id:number;
private isDone:boolean;
private text:string;
public constructor(id:number, isDone:boolean,text:string){
this.id = id;
this.isDone = isDone;
this.text = text;
}
public getID():number{
return this.id;
}
public getIsDone():boolean{
return this.isDone;
}
public getText():string{
return this.text;
}
}
|
8d4eb2b4fb11bf47fd56d33542c410abce9d49ac
|
[
"Markdown",
"TypeScript",
"Shell"
] | 14 |
TypeScript
|
spaezsuarez/to_do_graphql_server
|
517ff7dd2af4a82673b6ef3dc543204aae0a2d8d
|
5087eeebf001710388fe6a221884e95f45d9e191
|
refs/heads/master
|
<file_sep>var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var TopstorySchema= new Schema({
title: {
type: String,
requied: true
},
imagelink: {
type: String,
required: true
},
titlelink: {
type: String,
required: true
},
comment: {
type: Schema.Types.ObjectId,
ref: "Comment"
}
});
var Topstories = mongoose.model("Topstories",TopstorySchema);
module.exports = Topstories;
|
ad2b97f98889030e0a7a8e63e669510d335fd520
|
[
"JavaScript"
] | 1 |
JavaScript
|
Elhanang2/Scrap
|
85af8ade8e874dc8d1f9581969f68cb4120883a8
|
60c6754a80defd384bd0e0f573fec46f73a49df2
|
refs/heads/master
|
<file_sep><?php
/*
Plugin Name: Comments Plus
Plugin URI: http://premium.wpmudev.org/project/comments-plus
Description: Super-ifys comments on your site by adding ability to comment using facebook, twitter, and google accounts. Once activated, go to Settings > Comments Plus to configure.
Version: 1.5.3
Text Domain: wdcp
Author: Incsub
Author URI: http://premium.wpmudev.org
WDP ID: 247
Copyright 2009-2011 Incsub (http://incsub.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License (Version 2 - GPLv2) as published by
the Free Software Foundation.
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 GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
///////////////////////////////////////////////////////////////////////////
/* -------------------- Update Notifications Notice -------------------- */
if ( !function_exists( 'wdp_un_check' ) ) {
add_action( 'admin_notices', 'wdp_un_check', 5 );
add_action( 'network_admin_notices', 'wdp_un_check', 5 );
function wdp_un_check() {
if ( class_exists( 'WPMUDEV_Update_Notifications' ) )
return;
if ( $delay = get_site_option( 'un_delay' ) ) {
if ( $delay <= time() && current_user_can( 'install_plugins' ) )
echo '<div class="error fade"><p>' . __('Please install the latest version of <a href="http://premium.wpmudev.org/project/update-notifications/" title="Download Now »">our free Update Notifications plugin</a> which helps you stay up-to-date with the most stable, secure versions of WPMU DEV themes and plugins. <a href="http://premium.wpmudev.org/wpmu-dev/update-notifications-plugin-information/">More information »</a>', 'wpmudev') . '</a></p></div>';
} else {
update_site_option( 'un_delay', strtotime( "+1 week" ) );
}
}
}
/* --------------------------------------------------------------------- */
define ('WDCP_PLUGIN_SELF_DIRNAME', basename(dirname(__FILE__)), true);
define ('WDCP_PROTOCOL', (@$_SERVER["HTTPS"] == 'on' ? 'https://' : 'http://'), true);
//Setup proper paths/URLs and load text domains
if (is_multisite() && defined('WPMU_PLUGIN_URL') && defined('WPMU_PLUGIN_DIR') && file_exists(WPMU_PLUGIN_DIR . '/' . basename(__FILE__))) {
define ('WDCP_PLUGIN_LOCATION', 'mu-plugins', true);
define ('WDCP_PLUGIN_BASE_DIR', WPMU_PLUGIN_DIR, true);
define ('WDCP_PLUGIN_URL', str_replace('http://', (@$_SERVER["HTTPS"] == 'on' ? 'https://' : 'http://'), WPMU_PLUGIN_URL), true);
$textdomain_handler = 'load_muplugin_textdomain';
} else if (defined('WP_PLUGIN_URL') && defined('WP_PLUGIN_DIR') && file_exists(WP_PLUGIN_DIR . '/' . WDCP_PLUGIN_SELF_DIRNAME . '/' . basename(__FILE__))) {
define ('WDCP_PLUGIN_LOCATION', 'subfolder-plugins', true);
define ('WDCP_PLUGIN_BASE_DIR', WP_PLUGIN_DIR . '/' . WDCP_PLUGIN_SELF_DIRNAME, true);
define ('WDCP_PLUGIN_URL', str_replace('http://', (@$_SERVER["HTTPS"] == 'on' ? 'https://' : 'http://'), WP_PLUGIN_URL) . '/' . WDCP_PLUGIN_SELF_DIRNAME, true);
$textdomain_handler = 'load_plugin_textdomain';
} else if (defined('WP_PLUGIN_URL') && defined('WP_PLUGIN_DIR') && file_exists(WP_PLUGIN_DIR . '/' . basename(__FILE__))) {
define ('WDCP_PLUGIN_LOCATION', 'plugins', true);
define ('WDCP_PLUGIN_BASE_DIR', WP_PLUGIN_DIR, true);
define ('WDCP_PLUGIN_URL', str_replace('http://', (@$_SERVER["HTTPS"] == 'on' ? 'https://' : 'http://'), WP_PLUGIN_URL), true);
$textdomain_handler = 'load_plugin_textdomain';
} else {
// No textdomain is loaded because we can't determine the plugin location.
// No point in trying to add textdomain to string and/or localizing it.
wp_die(__('There was an issue determining where Comments Plus plugin is installed. Please reinstall.'));
}
$textdomain_handler('wdcp', false, WDCP_PLUGIN_SELF_DIRNAME . '/languages/');
require_once WDCP_PLUGIN_BASE_DIR . '/lib/class_wdcp_options.php';
require_once WDCP_PLUGIN_BASE_DIR . '/lib/class_wdcp_model.php';
require_once WDCP_PLUGIN_BASE_DIR . '/lib/class_wdcp_comments_worker.php';
require_once WDCP_PLUGIN_BASE_DIR . '/lib/class_wdcp_plugins_handler.php';
Wdcp_PluginsHandler::init();
function wdcp_initialize () {
//$opts = get_option('wdcp_options');
$data = new Wdcp_Options;
define('WDCP_TW_API_KEY', $data->get_option('tw_api_key'));
define('WDCP_CONSUMER_KEY', $data->get_option('tw_api_key'));
define('WDCP_CONSUMER_SECRET', $data->get_option('tw_app_secret'));
define('WDCP_SKIP_TWITTER', $data->get_option('tw_skip_init'));
define('WDCP_APP_ID', $data->get_option('fb_app_id'));
define('WDCP_APP_SECRET', $data->get_option('fb_app_secret'));
if (!defined('WDCP_SKIP_FACEBOOK')) define('WDCP_SKIP_FACEBOOK', $data->get_option('fb_skip_init'));
}
wdcp_initialize();
if (is_admin()) {
require_once WDCP_PLUGIN_BASE_DIR . '/lib/class_wdcp_admin_form_renderer.php';
require_once WDCP_PLUGIN_BASE_DIR . '/lib/class_wdcp_admin_pages.php';
require_once WDCP_PLUGIN_BASE_DIR . '/lib/class_wdcp_contextual_help.php';
require_once WDCP_PLUGIN_BASE_DIR . '/lib/class_wdcp_tutorial.php';
Wdcp_AdminPages::serve();
Wdcp_ContextualHelp::serve();
Wdcp_Tutorial::serve();
} else {
require_once WDCP_PLUGIN_BASE_DIR . '/lib/class_wdcp_public_pages.php';
Wdcp_PublicPages::serve();
}<file_sep><?php
/*
Plugin Name: Alternative Facebook Initialization
Description: Activate this add-on to solve some of the Facebook javascript initialization conflicts with other plugins.
Plugin URI: http://premium.wpmudev.org/project/comments-plus
Version: 1.0
Author: <NAME> (Incsub)
*/
class Wdcp_Afi_PublicPages {
private function __construct () {}
public static function serve () {
$me = new Wdcp_Afi_PublicPages;
$me->_add_hooks();
}
private function _add_hooks () {
add_filter('wdcp-service_initialization-facebook', array($this, 'handle_initialization'));
}
function handle_initialization () {
return "<script>
window.fbAsyncInit = function() {
FB.init({
appId: '" . WDCP_APP_ID . "',
status: true,
cookie: true,
xfbml: true,
oauth: true
});
};
if (typeof FB != 'undefined') FB.init({
appId: '" . WDCP_APP_ID . "',
status: true,
cookie: true,
xfbml: true,
oauth: true
});
</script>";
}
}
if (is_admin()) {
} else Wdcp_Afi_PublicPages::serve();
<file_sep><?php
class Wdcp_Tutorial {
private $_setup_tutorial;
private $_settings_url;
private $_setup_steps = array(
'facebook',
'hooks',
'addons',
);
private function __construct () {
if (!class_exists('Pointer_Tutorial')) require_once WDCP_PLUGIN_BASE_DIR . '/lib/external/pointers_tutorial.php';
$this->_setup_tutorial = new Pointer_Tutorial('wdcp-setup', __('Setup tutorial', 'wdcp'), false, false);
$this->_setup_tutorial->add_icon('');
$this->_settings_url = is_network_admin() ? network_admin_url('settings.php?page=wdcp') : admin_url('options-general.php?page=wdcp');
}
public static function serve () {
$me = new Wdcp_Tutorial;
$me->_add_hooks();
}
private function _add_hooks () {
add_action('admin_init', array($this, 'process_tutorial'));
add_action('wp_ajax_wdcp_restart_tutorial', array($this, 'json_restart_tutorial'));
}
function process_tutorial () {
/*
global $hook_suffix;
if ('settings_page_wdcp' == $hook_suffix) $this->_init_tutorial($this->_setup_steps);
if (defined('DOING_AJAX')) {
$this->_init_tutorial($this->_setup_steps);
}
*/
$this->_init_tutorial($this->_setup_steps);
$this->_setup_tutorial->initialize();
}
function json_restart_tutorial () {
$this->restart();
die;
}
public function restart () {
$tutorial = "_setup_tutorial";
if (isset($this->$tutorial)) return $this->$tutorial->restart();
}
private function _init_tutorial ($steps) {
$this->_setup_tutorial->set_capability('manage_options');
foreach ($steps as $step) {
$call_step = "add_{$step}_step";
if (method_exists($this, $call_step)) $this->$call_step();
}
}
/* ----- Setup Steps ----- */
function add_facebook_step () {
$this->_setup_tutorial->add_step(
$this->_settings_url, 'settings_page_wdcp',
'#fb_app_id',
__('Facebook App ID', 'wdcp'),
array(
'content' => '<p>' .
esc_js(__('Follow the steps to create your Facebook App, then paste its ID here.', 'wdcp')) .
'<br /><a href="#wdcp-more_help-fb" class="wdcp-more_help-fb">' . __('More help', 'wdcp') . '</a>' .
'</p>',
'position' => array('edge' => 'top', 'align' => 'left'),
)
);
$this->_setup_tutorial->add_step(
$this->_settings_url, 'settings_page_wdcp',
'#fb_app_secret',
__('Facebook App Secret', 'wdcp'),
array(
'content' => '<p>' .
esc_js(__('Follow the steps to create your Facebook App, then paste its Secret key here.', 'wdcp')) .
'<br /><a href="#wdcp-more_help-fb" class="wdcp-more_help-fb">' . __('More help', 'wdcp') . '</a>' .
'</p>',
'position' => array('edge' => 'top', 'align' => 'left'),
)
);
$this->_setup_tutorial->add_step(
$this->_settings_url, 'settings_page_wdcp',
'#fb_skip_init',
__('Facebook javascript loading', 'wdcp'),
array(
'content' => '' .
'<p>' .
esc_js(__('Check this option if your page already includes javascript from Facebook.', 'wdcp')) .
'</p>' .
'<p>' .
esc_js(__('Alternatively, you may want to activate the Alternative Facebook Initialization add-on (below).', 'wdcp')) .
'</p>' .
'',
'position' => array('edge' => 'top', 'align' => 'left'),
)
);
}
function add_hooks_step () {
$this->_setup_tutorial->add_step(
$this->_settings_url, 'settings_page_wdcp',
'#begin_injection_hook',
__('Comments form opening hook', 'wdcp'),
array(
'content' => '' .
'<p>' .
esc_js(__('If you do not see Comments Plus on your pages, it is likely that your theme does not use the hooks we need to display our interface. Use this field to set up custom hooks.', 'wdcp')) .
'</p>' .
'<p>' .
esc_js(__('Alternatively, you may want to leave this value at default setting and activate the Custom Comments Template add-on instead (below).', 'wdcp')) .
'</p>' .
'',
'position' => array('edge' => 'top', 'align' => 'left'),
)
);
$this->_setup_tutorial->add_step(
$this->_settings_url, 'settings_page_wdcp',
'#finish_injection_hook',
__('Comments form closing hook', 'wdcp'),
array(
'content' => '' .
'<p>' .
esc_js(__('If you do not see Comments Plus on your pages, it is likely that your theme does not use the hooks we need to display our interface. Use this field to set up custom hooks.', 'wdcp')) .
'</p>' .
'<p>' .
esc_js(__('Alternatively, you may want to leave this value at default setting and activate the Custom Comments Template add-on instead (below).', 'wdcp')) .
'</p>' .
'',
'position' => array('edge' => 'top', 'align' => 'left'),
)
);
}
function add_addons_step () {
$this->_setup_tutorial->add_step(
$this->_settings_url, 'settings_page_wdcp',
'#wdcp-alter_fb_init',
__('Alternative Facebook Initialization', 'wdcp'),
array(
'content' => '' .
'<p>' .
esc_js(__('Activating this add-on may help solving conflicts with other Facebook-related plugins.', 'wdcp')) .
'</p>' .
'',
'position' => array('edge' => 'top', 'align' => 'left'),
)
);
$this->_setup_tutorial->add_step(
$this->_settings_url, 'settings_page_wdcp',
'#wdcp-custom_comments_template',
__('Custom Comments Template', 'wdcp'),
array(
'content' => '' .
'<p>' .
esc_js(__('Activating this add-on may help with resolving issues with your theme.', 'wdcp')) .
'</p>' .
'',
'position' => array('edge' => 'top', 'align' => 'left'),
)
);
$this->_setup_tutorial->add_step(
$this->_settings_url, 'settings_page_wdcp',
'#wdcp-tw_fake_email',
__('Fake Twitter Email', 'wdcp'),
array(
'content' => '' .
'<p>' .
esc_js(__('Activating this add-on may help with comment approval issues with WordPress for your Twitter commenters.', 'wdcp')) .
'</p>' .
'',
'position' => array('edge' => 'top', 'align' => 'left'),
)
);
}
}
<file_sep>(function ($) {
$(function () {
// Bind local event handlers
$(document).bind('wdcp_google_login_attempt', function () {
var url = $("#login-with-google a").attr('href');
var googleLogin = window.open('https://www.google.com/accounts', "google_login", "scrollbars=no,resizable=no,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no,height=400,width=600");
$.post(_wdcp_ajax_url, {
"action": "wdcp_google_auth_url",
"url": url
}, function (data) {
var href = data.url;
googleLogin.location = href;
var gTimer = setInterval(function () {
try {
if (googleLogin.location.hostname == window.location.hostname) {
clearInterval(gTimer);
googleLogin.close();
$(document).trigger('wdcp_logged_in', ['google']);
}
} catch (e) {}
}, 300);
return false;
});
});
//Handle logout requests gracefully
$("#comment-provider-google a.comment-provider-logout").live('click', function () {
$.post(_wdcp_ajax_url, {
"action": "wdcp_google_logout"
}, function (data) {
window.location.reload(); // Refresh
});
return false;
});
// Handle post comment requests
$("#send-google-comment").live('click', function () {
var comment = $("#google-comment").val();
var commentParent = $('#comment_parent').val();
var subscribe = ($("#subscribe").length && $("#subscribe").is(":checked")) ? 'subscribe' : '';
var to_send = {
"action": "wdcp_post_google_comment",
"post_id": _wdcp_data.post_id,
"comment_parent": commentParent,
"subscribe": subscribe,
"comment": comment
};
$(document).trigger('wdcp_preprocess_comment_data', [to_send]);
// Start UI change...
$(this).parents(".comment-provider").empty().append('<div class="comment-provider-waiting-response"></div>');
$.post(_wdcp_ajax_url, to_send, function (data) {
$(document).trigger('wdcp_comment_sent', ['google']);
window.location.reload(); // Refresh
});
return false;
});
});
})(jQuery);<file_sep><?php
class Wdcp_Options {
private $_data;
private $_site;
private $_fb;
private $_tw;
function __construct () {
$this->_data = get_option('wdcp_options');
$this->_site = get_site_option('wdcp_options');
$this->_fb = array('fb_app_id', 'fb_app_secret');
$this->_tw = array('tw_api_key', 'tw_app_secret');
}
public function get_option ($name) {
if (!$name) return false;
if (in_array($name, $this->_fb) && @$this->_site['fb_network_only']) {
return @$this->_site[$name];
}
if (in_array($name, $this->_tw) && @$this->_site['tw_network_only']) {
return @$this->_site[$name];
}
return @$this->_data[$name] ? @$this->_data[$name] : @$this->_site[$name];
}
/**
* Sets all stored options.
*/
function set_options ($opts) {
return WP_NETWORK_ADMIN ? update_site_option('wdcp_options', $opts) : update_option('wdcp_options', $opts);
}
}<file_sep><li id="li-comment-<?php echo $comment->comment_ID; ?>">
<div id="comment-<?php echo $comment->comment_ID; ?>">
<div class="comment-author vcard">
<?php echo $avatar; ?>
</div>
<div class="comment-body"><?php echo $comment->comment_content; ?>
<div class="comment-meta commentmetadata">
<a href="<?php echo $comment->comment_author_url;?>" rel="nofollow">
<?php printf( '<cite class="fn">%s</cite>', $comment->comment_author ); ?>
<?php printf(
__('<span class="date">%1$s at %2$s</span>'),
mysql2date(get_option('date_format'), $comment->comment_date),
mysql2date(get_option('time_format'), $comment->comment_date)
); ?>
</a>
</div>
</div>
<div class="clear"></div>
</div>
</li><file_sep><?php
/**
* Handles generic Admin functionality and AJAX requests
*/
class Wdcp_AdminPages {
var $model;
var $data;
function Wdcp_AdminPages () { $this->__construct(); }
function __construct () {
$this->model = new Wdcp_Model;
$this->data = new Wdcp_Options;
}
/**
* Main entry point.
*
* @static
*/
function serve () {
$me = new Wdcp_AdminPages;
$me->add_hooks();
}
/**
* Add an admin info message about plugin configuration.
*/
function show_nag_messages () {
if (isset($_GET['page']) && 'wdcp' == $_GET['page']) return false;
$skips = $this->data->get_option('skip_services');
$skips = $skips ? $skips : array();
if (
(!$this->data->get_option('fb_app_id') && !in_array('facebook', $skips)) // Not skipping Facebook, no FB API key
||
(!$this->data->get_option('tw_api_key') && !in_array('twitter', $skips)) // Not skipping Twitter, no Twitter API creds
) {
echo '<div class="error">' .
'<p>' . sprintf(
__('You need to configure the Comments Plus plugin, you can do so <a href="%s">here</a>', 'wdcp'),
admin_url('/options-general.php?page=wdcp')
) . '</p>' .
'</div>';
}
}
/**
* Add Network Admin footer messages.
*/
function show_nag_footer () {
//if (!is_network_admin()) return false;
$screen = get_current_screen();
if ('plugins' != $screen->id) return false;
echo '<div class="wdcp-notice">' .
'<p>' . __('You will also find add-ons that you can enable on a blog basis in Settings > Comments Plus in the site admin', 'wdcp') . '</p>' .
'</div>';
}
/**
* Registers settings.
*/
function register_settings () {
register_setting('wdcp', 'wdcp_options');
$form = new Wdcp_AdminFormRenderer;
add_settings_section('wdcp_options', __('App settings', 'wdcp'), create_function('', ''), 'wdcp_options');
add_settings_field('wdcp_facebook_app', __('Facebook App info', 'wdcp'), array($form, 'create_facebook_app_box'), 'wdcp_options', 'wdcp_options');
add_settings_field('wdcp_facebook_skip', __('Skip loading Facebook javascript', 'wdcp'), array($form, 'create_skip_facebook_init_box'), 'wdcp_options', 'wdcp_options');
add_settings_field('wdcp_twitter_app', __('Twitter App info', 'wdcp'), array($form, 'create_twitter_app_box'), 'wdcp_options', 'wdcp_options');
add_settings_field('wdcp_twitter_skip', __('Skip loading Twitter javascript', 'wdcp'), array($form, 'create_skip_twitter_init_box'), 'wdcp_options', 'wdcp_options');
add_settings_section('wdcp_general', __('General Settings', 'wdcp'), create_function('', ''), 'wdcp_options');
add_settings_field('wdcp_wp_icon', __('WordPress branding & options', 'wdcp'), array($form, 'create_wp_icon_box'), 'wdcp_options', 'wdcp_general');
add_settings_field('wdcp_skip_services', __('Do not show "Comment with…"', 'wdcp'), array($form, 'create_skip_services_box'), 'wdcp_options', 'wdcp_general');
add_settings_field('wdcp_style', __('Comments Plus Styling', 'wdcp'), array($form, 'create_style_box'), 'wdcp_options', 'wdcp_general');
add_settings_section('wdcp_hooks', __('Hooks', 'wdcp'), array($form, 'create_hooks_section'), 'wdcp_options');
add_settings_field('wdcp_start_hook', __('Start injection hook', 'wdcp'), array($form, 'create_start_hook_box'), 'wdcp_options', 'wdcp_hooks');
add_settings_field('wdcp_end_hook', __('Finish injection hook', 'wdcp'), array($form, 'create_end_hook_box'), 'wdcp_options', 'wdcp_hooks');
if (!is_multisite() || (is_multisite() && (!defined('WP_NETWORK_ADMIN') || !WP_NETWORK_ADMIN))) {
add_settings_section('wdcp_plugins', __('Comments Plus add-ons', 'wdcp'), create_function('', ''), 'wdcp_options');
add_settings_field('wdcp_plugins_all_plugins', __('All add-ons', 'wdcp'), array($form, 'create_plugins_box'), 'wdcp_options', 'wdcp_plugins');
do_action('wdcp-options-plugins_options');
}
}
/**
* Creates Admin menu entry.
*/
function create_admin_menu_entry () {
if (@$_POST && isset($_POST['option_page']) && 'wdcp' == @$_POST['option_page']) {
if (isset($_POST['wdcp_options'])) {
$this->data->set_options($_POST['wdcp_options']);
}
$goback = add_query_arg('settings-updated', 'true', wp_get_referer());
wp_redirect($goback);
die;
}
$page = WP_NETWORK_ADMIN ? 'settings.php' : 'options-general.php';
$perms = WP_NETWORK_ADMIN ? 'manage_network_options' : 'manage_options';
add_submenu_page($page, __('Comments Plus', 'wdcp'), __('Comments Plus', 'wdcp'), $perms, 'wdcp', array($this, 'create_admin_page'));
}
/**
* Creates Admin menu page.
*/
function create_admin_page () {
include(WDCP_PLUGIN_BASE_DIR . '/lib/forms/plugin_settings.php');
}
function json_get_form () {
$worker = new Wdcp_CommentsWorker;
$provider = $_POST['provider'];
$html = call_user_func(array($worker, "_prepare_{$provider}_comments"), $_POST['page']);
header('Content-type: application/json');
echo json_encode(array(
'html' => $html,
));
exit();
}
function json_google_auth_url () {
header('Content-type: application/json');
echo json_encode(array(
'url' => $this->model->get_google_auth_url($_POST['url']),
));
exit();
}
function json_google_logout () {
$this->model->google_logout_user();
header('Content-type: application/json');
echo json_encode(array(
'status' => 1,
));
exit();
}
function json_twitter_logout () {
$this->model->twitter_logout_user();
header('Content-type: application/json');
echo json_encode(array(
'status' => 1,
));
exit();
}
function json_twitter_auth_url () {
header('Content-type: application/json');
echo json_encode(array(
'url' => $this->model->get_twitter_auth_url($_POST['url']),
));
exit();
}
function json_facebook_logout () {
$this->model->facebook_logout_user();
header('Content-type: application/json');
echo json_encode(array(
'status' => 1,
));
exit();
}
function json_post_facebook_comment () {
if (!$this->model->current_user_logged_in('facebook')) return false;
$fb_uid = $this->model->current_user_id('facebook');
$username = $this->model->current_user_name('facebook');
$email = $this->model->current_user_email('facebook');
$url = $this->model->current_user_url('facebook');
$data = apply_filters('wdcp-comment_data', apply_filters('wdcp-comment_data-facebook', array(
'comment_post_ID' => @$_POST['post_id'],
'comment_author' => $username,
'comment_author_email' => $email,
'comment_author_url' => $url,
'comment_content' => @$_POST['comment'],
'comment_type' => '',
'comment_parent' => (int)@$_POST['comment_parent'],
'_wdcp_provider' => 'facebook',
)));
$meta = array (
'wdcp_fb_author_id' => $fb_uid,
);
$comment_id = wp_new_comment($data);
add_comment_meta($comment_id, 'wdcp_comment', $meta) ;
do_action('comment_post', $comment_id, $data['comment_approved']);
$this->_postprocess_comment($comment_id);
// Post comment to Facebook ...
if ((int)$_POST['post_on_facebook']) {
$result = $this->model->post_to_facebook($_POST);
do_action('wdcp-remote_comment_posted-facebook', $comment_id, $result, $data);
}
header('Content-type: application/json');
echo json_encode(array(
'status' => 1,
));
exit();
}
function json_post_twitter_comment () {
if (!$this->model->current_user_logged_in('twitter')) return false;
$tw_uid = $this->model->current_user_id('twitter');
$username = $this->model->current_user_name('twitter');
$email = $this->model->current_user_email('twitter');
$url = $this->model->current_user_url('twitter');
$avatar = $this->model->twitter_avatar();
$data = apply_filters('wdcp-comment_data', apply_filters('wdcp-comment_data-twitter', array(
'comment_post_ID' => @$_POST['post_id'],
'comment_author' => $username,
'comment_author_email' => $email,
'comment_author_url' => $url,
'comment_content' => @$_POST['comment'],
'comment_type' => '',
'comment_parent' => (int)@$_POST['comment_parent'],
'_wdcp_provider' => 'twitter',
)));
$meta = array (
'wdcp_tw_avatar' => $avatar,
);
//$comment_id = wp_insert_comment($data);
$comment_id = wp_new_comment($data);
add_comment_meta($comment_id, 'wdcp_comment', $meta) ;
do_action('comment_post', $comment_id, $data['comment_approved']);
$this->_postprocess_comment($comment_id);
// Post comment to Facebook ...
if ((int)$_POST['post_on_twitter']) {
$result = $this->model->post_to_twitter($_POST);
do_action('wdcp-remote_comment_posted-twitter', $comment_id, $result, $data);
}
header('Content-type: application/json');
echo json_encode(array(
'status' => 1,
));
exit();
}
function json_post_google_comment () {
if (!$this->model->current_user_logged_in('google')) return false;
$guid = $this->model->current_user_id('google');
$username = $this->model->current_user_name('google');
$email = $this->model->current_user_email('google');
$data = apply_filters('wdcp-comment_data', apply_filters('wdcp-comment_data-google', array(
'comment_post_ID' => @$_POST['post_id'],
'comment_author' => $username,
'comment_author_email' => $email,
'comment_content' => @$_POST['comment'],
'comment_type' => '',
'comment_parent' => (int)@$_POST['comment_parent'],
'_wdcp_provider' => 'google',
)));
$meta = array (
'wdcp_gg_author_id' => $guid,
);
//$comment_id = wp_insert_comment($data);
$comment_id = wp_new_comment($data);
add_comment_meta($comment_id, 'wdcp_comment', $meta) ;
do_action('comment_post', $comment_id, $data['comment_approved']);
$this->_postprocess_comment($comment_id);
header('Content-type: application/json');
echo json_encode(array(
'status' => 1,
));
exit();
}
function _postprocess_comment ($comment_id) {
$comment = get_comment($comment_id);
if ( !get_current_user_id() ) {
$comment_cookie_lifetime = apply_filters('comment_cookie_lifetime', 30000000);
setcookie('comment_author_' . COOKIEHASH, $comment->comment_author, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN);
setcookie('comment_author_email_' . COOKIEHASH, $comment->comment_author_email, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN);
setcookie('comment_author_url_' . COOKIEHASH, esc_url($comment->comment_author_url), time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN);
}
do_action('wdcp-comment_posted-postprocess', $comment_id, $comment);
}
function json_activate_plugin () {
$status = Wdcp_PluginsHandler::activate_plugin($_POST['plugin']);
echo json_encode(array(
'status' => $status ? 1 : 0,
));
exit();
}
function json_deactivate_plugin () {
$status = Wdcp_PluginsHandler::deactivate_plugin($_POST['plugin']);
echo json_encode(array(
'status' => $status ? 1 : 0,
));
exit();
}
function add_hooks () {
// Register options and menu
add_action('admin_init', array($this, 'register_settings'));
add_action('admin_menu', array($this, 'create_admin_menu_entry'));
add_action('network_admin_menu', array($this, 'create_admin_menu_entry'));
add_action('admin_notices', array($this, 'show_nag_messages'));
add_action('in_admin_footer', array($this, 'show_nag_footer'));
// Bind AJAX requests
add_action('wp_ajax_nopriv_wdcp_get_form', array($this, 'json_get_form'));
add_action('wp_ajax_wdcp_get_form', array($this, 'json_get_form'));
add_action('wp_ajax_nopriv_wdcp_google_auth_url', array($this, 'json_google_auth_url'));
add_action('wp_ajax_wdcp_google_auth_url', array($this, 'json_google_auth_url'));
add_action('wp_ajax_nopriv_wdcp_twitter_auth_url', array($this, 'json_twitter_auth_url'));
add_action('wp_ajax_wdcp_twitter_auth_url', array($this, 'json_twitter_auth_url'));
add_action('wp_ajax_wdcp_post_facebook_comment', array($this, 'json_post_facebook_comment'));
add_action('wp_ajax_nopriv_wdcp_post_facebook_comment', array($this, 'json_post_facebook_comment'));
add_action('wp_ajax_wdcp_post_google_comment', array($this, 'json_post_google_comment'));
add_action('wp_ajax_nopriv_wdcp_post_google_comment', array($this, 'json_post_google_comment'));
add_action('wp_ajax_wdcp_post_twitter_comment', array($this, 'json_post_twitter_comment'));
add_action('wp_ajax_nopriv_wdcp_post_twitter_comment', array($this, 'json_post_twitter_comment'));
add_action('wp_ajax_wdcp_facebook_logout', array($this, 'json_facebook_logout'));
add_action('wp_ajax_nopriv_wdcp_facebook_logout', array($this, 'json_facebook_logout'));
add_action('wp_ajax_wdcp_google_logout', array($this, 'json_google_logout'));
add_action('wp_ajax_nopriv_wdcp_google_logout', array($this, 'json_google_logout'));
add_action('wp_ajax_wdcp_twitter_logout', array($this, 'json_twitter_logout'));
add_action('wp_ajax_nopriv_wdcp_twitter_logout', array($this, 'json_twitter_logout'));
// AJAX plugin handlers
add_action('wp_ajax_wdcp_activate_plugin', array($this, 'json_activate_plugin'));
add_action('wp_ajax_wdcp_deactivate_plugin', array($this, 'json_deactivate_plugin'));
}
}<file_sep><?php
/*
Plugin Name: Link to Twitter profile
Description: Enabling this addon will force the plugn to always use Twitter profile URLs as websites for your Twitter commenters, regardles of their Twitter profile settings.
Plugin URI: http://premium.wpmudev.org/project/comments-plus
Version: 1.0
Author: <NAME> (Incsub)
*/
class Wdcp_Twltp_AdminPages {
private $_model;
private function __construct () {
$this->_model = new Wdcp_Model;
}
public static function serve () {
$me = new Wdcp_Twltp_AdminPages;
$me->_add_hooks();
}
private function _add_hooks () {
add_filter('wdcp-comment_data-twitter', array($this, 'process_data'));
}
function process_data ($data) {
$twitter_username = $this->_model->current_user_username('twitter');
$data['comment_author_url'] = "https://twitter.com/#!/{$twitter_username}";
return $data;
}
}
if (is_admin()) Wdcp_Twltp_AdminPages::serve();
<file_sep><?php
class Wdcp_CommentsWorker {
var $model;
var $data;
function Wdcp_CommentsWorker () { $this->__construct(); }
function __construct () {
$this->model = new Wdcp_Model;
$this->data = new Wdcp_Options;
}
function js_load_scripts () {
wp_enqueue_script('jquery');
if (!apply_filters('wdcp-script_inclusion-facebook', WDCP_SKIP_FACEBOOK)) {
$locale = defined('WDCP_FACEBOOK_LOCALE') && WDCP_FACEBOOK_LOCALE
? WDCP_FACEBOOK_LOCALE : preg_replace('/-/', '_', get_locale())
;
$locale = apply_filters('wdcp-locale-facebook_locale', $locale);
wp_enqueue_script('facebook-all', WDCP_PROTOCOL . 'connect.facebook.net/' . $locale . '/all.js');
}
if (!apply_filters('wdcp-script_inclusion-twitter', WDCP_SKIP_TWITTER)) {
wp_enqueue_script('twitter-anywhere', WDCP_PROTOCOL . 'platform.twitter.com/anywhere.js?id=' . WDCP_TW_API_KEY . '&v=1');
}
wp_enqueue_script('wdcp_comments', WDCP_PLUGIN_URL . '/js/comments.js', array('jquery'));
wp_enqueue_script('wdcp_twitter', WDCP_PLUGIN_URL . '/js/twitter.js', array('jquery', 'wdcp_comments'));
wp_enqueue_script('wdcp_facebook', WDCP_PLUGIN_URL . '/js/facebook.js', array('jquery', 'wdcp_comments'));
wp_enqueue_script('wdcp_google', WDCP_PLUGIN_URL . '/js/google.js', array('jquery', 'wdcp_comments'));
printf(
//'<script type="text/javascript">var _wdcp_post_id="%d";</script>',
//get_the_ID()
'<script type="text/javascript">var _wdcp_data={"post_id": %d, "fit_tabs": %d, "text": {"reply": "%s", "cancel_reply": "%s"}};</script>',
get_the_ID(), (int)$this->data->get_option('stretch_tabs'),
esc_js(__('Reply', 'wdcp')), esc_js(__('Cancel reply', 'wdcp'))
);
}
function css_load_styles () {
$skip = $this->data->get_option('skip_color_css');
wp_enqueue_style('wdcp_comments', WDCP_PLUGIN_URL . '/css/comments.css');
if (!current_theme_supports('wdcp_comments-specific') && !$skip) {
wp_enqueue_style('wdcp_comments-specific', WDCP_PLUGIN_URL . '/css/comments-specific.css');
}
$icon = $this->data->get_option('wp_icon');
if ($icon) {
$selector = apply_filters('wdcp-wordpress_custom_icon_selector', 'ul#all-comment-providers li a#comment-provider-wordpress-link');
printf(
'<style type="text/css">
%s {
background-image: url(%s) !important;
}
</style>', $selector, $icon);
}
}
function header_dependencies () {
echo $this->_prepare_header_dependencies();
}
function begin_injection () {
$skips = (array)$this->data->get_option('skip_services');
$instructions = $this->data->get_option('show_instructions') ? '' : 'no-instructions';
if (!in_array('facebook', $skips)) $fb_html = $this->_prepare_facebook_comments();
if (!in_array('twitter', $skips)) $tw_html = $this->_prepare_twitter_comments();
if (!in_array('google', $skips)) $gg_html = $this->_prepare_google_comments();
if (!in_array('wordpress', $skips)) {
$default_name = defined('WDCP_DEFAULT_WP_PROVIDER_NAME') && WDCP_DEFAULT_WP_PROVIDER_NAME ? WDCP_DEFAULT_WP_PROVIDER_NAME : get_bloginfo('name');
$default_name = $default_name ? $default_name : 'WordPress';
$wp_name = $this->model->current_user_logged_in('wordpress')
? $this->model->current_user_name('wordpress')
: apply_filters('wdcp-providers-wordpress-name', $default_name)
;
}
if (!in_array('twitter', $skips)) $tw_name = $this->model->current_user_logged_in('twitter') ? $this->model->current_user_name('twitter') : apply_filters('wdcp-providers-twitter-name', 'Twitter');
if (!in_array('facebook', $skips)) $fb_name = $this->model->current_user_logged_in('facebook') ? $this->model->current_user_name('facebook') : apply_filters('wdcp-providers-facebook-name', 'Facebook');
if (!in_array('google', $skips)) $gg_name = $this->model->current_user_logged_in('google') ? $this->model->current_user_name('google') : apply_filters('wdcp-providers-google-name', 'Google');
echo "
<div id='comment-providers-select-message'>" . __("Click on a tab to select how you'd like to leave your comment", 'wdcp') . "</div>
<div id='comment-providers'><a name='comments-plus-form'></a>
<ul id='all-comment-providers'>";
if (!in_array('wordpress', $skips)) echo "<li><a id='comment-provider-wordpress-link' href='#comment-provider-wordpress'><span>$wp_name</span></a></li>";
if (!in_array('twitter', $skips)) echo "<li><a id='comment-provider-twitter-link' href='#comment-provider-twitter'><span>$tw_name</span></a></li>";
if (!in_array('facebook', $skips)) echo "<li><a id='comment-provider-facebook-link' href='#comment-provider-facebook'><span>$fb_name</span></a></li>";
if (!in_array('google', $skips)) echo "<li><a id='comment-provider-google-link' href='#comment-provider-google'><span>$gg_name</span></a></li>";
echo "</ul>";
if (!in_array('facebook', $skips)) echo "<div class='comment-provider' id='comment-provider-facebook'>$fb_html</div>";
if (!in_array('twitter', $skips)) echo "<div class='comment-provider' id='comment-provider-twitter'>$tw_html</div>";
if (!in_array('google', $skips)) echo "<div class='comment-provider' id='comment-provider-google'>$gg_html</div>";
echo "<div class='comment-provider {$instructions}' id='comment-provider-wordpress'>";
}
function finish_injection () {
echo "</div> <!-- Wordpress provider -->";
echo "</div> <!-- #comment-providers -->";
}
function footer_dependencies () {
echo $this->_prepare_footer_dependencies();
}
function replace_avatars ($avatar, $comment) {
if (!is_object($comment) || !isset($comment->comment_ID)) return $avatar;
$fb_uid = false;
$meta = get_comment_meta($comment->comment_ID, 'wdcp_comment', true);
if (!$meta) return $avatar;
$fb_uid = @$meta['wdcp_fb_author_id'];
if (!$fb_uid) {
$tw_avatar = @$meta['wdcp_tw_avatar'];
if (!$tw_avatar) return $avatar;
return "<img class='avatar avatar-40 photo' width='40' height='40' src='{$tw_avatar}' />";
}
return "<img class='avatar avatar-40 photo' width='40' height='40' src='". WDCP_PROTOCOL . "graph.facebook.com/{$fb_uid}/picture' />";
}
/*** Privates ***/
function _prepare_header_dependencies () {
}
function _prepare_facebook_comments () {
if (!$this->model->current_user_logged_in('facebook')) return $this->_prepare_facebook_login();
$preselect = $this->data->get_option('dont_select_social_sharing') ? '' : 'checked="checked"';
$disconnect = __('Disconnect', 'wdcp');
return "
<p>" . __('Connected as', 'wdcp') . " <b class='connected-as'>" . $this->model->current_user_name('facebook') . "</b>. <a class='comment-provider-logout' href='#'>{$disconnect}</a></p>
<textarea id='facebook-comment' rows='8' cols='45' rows='6'></textarea>
<p><label for='post-on-facebook'><input type='checkbox' id='post-on-facebook' value='1' {$preselect} /> " . __("Post my comment on my wall", "wdcp"). "</label></p>
<p><a class='button' href='#' id='send-facebook-comment'>" . sprintf(__('Comment via %s', 'wdcp'), 'Facebook') . "</a></p>
";
}
function _prepare_facebook_login () {
return "<img src='" . WDCP_PLUGIN_URL . "/img/fb-login.png' style='position:absolute;left:-1200000000px;display:none' />" . '<div class="comment-provider-login-button" id="login-with-facebook"><a href="#" title="' . __('Login with Facebook', 'wdcp') . '"><span>Login</span></a></div>';
}
function _prepare_google_comments () {
if (!$this->model->current_user_logged_in('google')) return $this->_prepare_google_login();
$disconnect = __('Disconnect', 'wdcp');
return "
<p>" . __('Connected as', 'wdcp') . " <b class='connected-as'>" . $this->model->current_user_name('google') . "</b>. <a class='comment-provider-logout' href='#'>{$disconnect}</a></p>
<textarea id='google-comment' rows='8' cols='45' rows='6'></textarea>
<p><a class='button' href='#' id='send-google-comment'>" . sprintf(__('Comment via %s', 'wdcp'), 'Google') . "</a></p>
";
}
function _prepare_google_login () {
$href = WDCP_PROTOCOL . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
return "<img src='" . WDCP_PLUGIN_URL . "/img/gg-login.png' style='position:absolute;left:-1200000000px;display:none' />" . '<div class="comment-provider-login-button" id="login-with-google"><a href="' . $href . '" title="' . __('Login with Google', 'wdcp') . '"><span>Login</span></a></div>';
}
function _prepare_twitter_comments () {
if (!$this->model->current_user_logged_in('twitter')) return $this->_prepare_twitter_login();
$preselect = $this->data->get_option('dont_select_social_sharing') ? '' : 'checked="checked"';
$disconnect = __('Disconnect', 'wdcp');
return "
<p>" . __('Connected as', 'wdcp') . " <b class='connected-as'>" . $this->model->current_user_name('twitter') . "</b>. <a class='comment-provider-logout' href='#'>{$disconnect}</a></p>
<textarea id='twitter-comment' rows='8' cols='45' rows='6'></textarea>
<p><label for='post-on-twitter'><input type='checkbox' id='post-on-twitter' value='1' {$preselect} /> " . __("Post my comment on Twitter", "wdcp"). "</label></p>
<p><a class='button' href='#' id='send-twitter-comment'>" . sprintf(__('Comment via %s', 'wdcp'), 'Twitter') . "</a></p>
";
}
function _prepare_twitter_login () {
$href = WDCP_PROTOCOL . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
return "<img src='" . WDCP_PLUGIN_URL . "/img/tw-login.png' style='position:absolute;left:-1200000000px;display:none' />" . '<div class="comment-provider-login-button" id="login-with-twitter"><a href="' . $href . '" title="' . __('Login with Twitter', 'wdcp') . '"><span>Login</span></a></div>';
}
function _prepare_footer_dependencies () {
if (WDCP_SKIP_FACEBOOK) $fb_part = ''; // Solve possible UFb conflict
//UPDATED BY FEAST TO MAKE THIS POS PLUGIN LOAD FB ASYNCHRONOUSLY
/*
else $fb_part = "<div id='fb-root'></div>" .
"<script>
FB.init({
appId: '" . WDCP_APP_ID . "',
status: true,
cookie: true,
xfbml: true,
oauth: true
});
</script>";*/
else $fb_part = "<div id='fb-root'></div>" .
"<script>
window.fbAsyncInit = function() {
FB.init({
appId: '" . WDCP_APP_ID . "',
status: true,
cookie: true,
xfbml: true,
oauth: true
});
};
if (typeof FB != 'undefined') FB.init({
appId: '" . WDCP_APP_ID . "',
status: true,
cookie: true,
xfbml: true,
oauth: true
});
</script>";
//UPDATED BY FEAST TO MAKE THIS POS PLUGIN NOT LOAD TWITTER IF IT'S NOT CONFIGURED
if (WDCP_SKIP_TWITTER) $tw_part = ''; // Solves conflict when Twitter is not configured
else $tw_part = sprintf(
'<script type="text/javascript">jQuery(function () { if ("undefined" != typeof twttr && twttr.anywhere && twttr.anywhere.config) twttr.anywhere.config({ callbackURL: "%s" }); });</script>',
get_permalink()
);
$fb_part = apply_filters('wdcp-service_initialization-facebook', $fb_part);
$tw_part = apply_filters('wdcp-service_initialization-twitter', $tw_part);
return "{$fb_part}{$tw_part}";
}
}<file_sep><?php
/*
Plugin Name: MailChimp List Subscription
Description: Adds a checkbox to facilitate subscribing your commenters to your existing MailChimp list.
Plugin URI: http://premium.wpmudev.org/project/comments-plus
Version: 1.0
Author: <NAME> (Incsub)
*/
class Wdcp_Mcls_Admin_Pages {
private $_data;
private function __construct () {
$this->_data = new Wdcp_Options;
}
public static function serve () {
$me = new Wdcp_Mcls_Admin_Pages;
$me->_add_hooks();
}
private function _add_hooks () {
add_action('wdcp-options-plugins_options', array($this, 'register_settings'));
add_action('wdcp-plugin_settings-javascript_init', array($this, 'add_javascript'));
add_action('wp_ajax_wdcp_mcls_refresh_lists', array($this, 'json_refresh_lists'));
add_action('comment_post', array($this, 'mailchimp_signup'));
}
function mailchimp_signup ($comment_id) {
if (!@$_POST['wdcp-mcls-subscribe']) return false;
$current = $this->_data->get_option('mcls_list');
if (!$current) return false;
$comment = get_comment($comment_id);
$email = $comment->comment_author_email;
if (!is_email($email)) return false;
list($server, $key) = $this->_get_parsed_key();
if (!$server || !$key) return false;
$resp = wp_remote_get("http://{$server}.api.mailchimp.com/1.3/?method=listSubscribe&apikey={$key}&id={$current}&email_address={$email}");
if(is_wp_error($resp)) return false; // Request fail
if ((int)$resp['response']['code'] != 200) return false; // Request fail
$subscribed = get_option("wdcp-mcls-{$current}");
$subscribed = is_array($subscribed) ? $subscribed : array();
$subscribed[] = $email;
update_option("wdcp-mcls-{$current}", array_unique($subscribed));
}
function register_settings () {
add_settings_section('wdcp_mcls_settings', __('MailChimp Settings', 'wdcp'), create_function('', ''), 'wdcp_options');
add_settings_field('wdcp_mcls_apikey', __('API key', 'wdcp'), array($this, 'create_apikey_box'), 'wdcp_options', 'wdcp_mcls_settings');
add_settings_field('wdcp_mcls_lists', __('Lists', 'wdcp'), array($this, 'create_lists_box'), 'wdcp_options', 'wdcp_mcls_settings');
}
function create_apikey_box () {
$key = $this->_data->get_option('mcls_apikey');
echo '<input type="text" class="widefat" name="wdcp_options[mcls_apikey]" value="' . esc_attr($key) . '" />';
}
function create_lists_box () {
$key = $this->_data->get_option('mcls_apikey');
if (!$key) {
echo '<div class="error below-h2"><p>' . __('Please set up your API key in the field above, and save the settings.', 'wdcp') . '</p></div>';
return false;
}
echo $this->_generate_lists_output();
echo '<a href="#mcls-refresh" id="wdcp-mcls-refresh">' . __('Refresh', 'wdcp') . '</a>';
echo '<div><small>' . __('Select a list you wish to offer subscriptions to.', 'wdcp') . '</small></div>';
}
function json_refresh_lists () {
echo $this->_generate_lists_output();
die;
}
function add_javascript () {
$loading = WDCP_PLUGIN_URL . '/img/loading.gif';
echo <<<EOMclsAdminJs
function mcls_refresh_lists () {
$("#wdcp-mcls-refresh").parents('td:first').find("select").remove();
$("#wdcp-mcls-refresh").hide().after('<img src="{$loading}" id="wdcp-mcls-spinner" />');
$.post(ajaxurl, {
"action": "wdcp_mcls_refresh_lists",
}, function (data) {
$("#wdcp-mcls-spinner").remove();
$("#wdcp-mcls-refresh").show().before(data);
});
return false;
}
$("#wdcp-mcls-refresh").click(mcls_refresh_lists);
EOMclsAdminJs;
}
private function _get_parsed_key () {
$err = array(false,false);
$key = $this->_data->get_option('mcls_apikey');
if (preg_match('/-/', $key)) list($key, $server) = explode('-', $key);
else return err;
if (!$key || !$server) return $err;
return array($server, $key);
}
private function _refresh_lists () {
list($server, $key) = $this->_get_parsed_key();
$resp = wp_remote_get("http://{$server}.api.mailchimp.com/1.3/?method=lists&apikey={$key}");
if(is_wp_error($resp)) return false; // Request fail
if ((int)$resp['response']['code'] != 200) return false; // Request fail
$lists = json_decode($resp['body']);
$store = array();
if (isset($lists->data) && $lists->data) foreach ($lists->data as $list) {
$store[] = array(
'id' => $list->id,
'name' => $list->name,
'created' => strtotime($list->date_created),
);
}
return $store;
}
private function _generate_lists_output () {
$out = '<select name="wdcp_options[mcls_list]">';
$lists = $this->_refresh_lists();
$current = $this->_data->get_option('mcls_list');
if ($lists) foreach ($lists as $list) {
$selected = $list['id'] == $current ? 'selected="selected"' : '';
$out .= '<option value="' . esc_attr($list['id']) . '" ' . $selected . '>' . $list['name'] . '</option>';
}
$out .= '</select>';
return $out;
}
}
class Wdcp_Mcls_Public_Pages {
private $_data;
private function __construct () {
$this->_data = new Wdcp_Options;
}
public static function serve () {
$me = new Wdcp_Mcls_Public_Pages;
$me->_add_hooks();
}
private function _add_hooks () {
add_action('comment_form', array($this, 'show_subscription_checkbox'));
add_action('comment_post', 'wdcp_mcls_mailchimp_signup');
}
function show_subscription_checkbox () {
$current = $this->_data->get_option('mcls_list');
if (!$current) return false;
$subscribed = get_option("wdcp-mcls-{$current}");
$subscribed = is_array($subscribed) ? $subscribed : array();
$providers = array('wordpress', 'google', 'facebook');
$model = new Wdcp_Model;
foreach ($providers as $provider) {
$email = $model->current_user_email($provider);
if ($email && in_array($email, $subscribed)) return false; // Already subscribed
}
$label = apply_filters('wdcp-mcls-checkbox_label_text', __('Subscribe me to the newsletter', 'wdcp'));
echo '<p class="wdcp-mcls-subscription">' .
'<input type="checkbox" name="wdcp-mcls-subscribe" id="wdcp-mcls-subscribe" value="1" /> <label for="wdcp-mcls-subscribe">' . $label . '</label>' .
'</p>';
echo <<<EOMclsPublicJs
<script type="text/javascript">
(function ($) {
$(document).bind('wdcp_preprocess_comment_data', function (e, to_send) {
if (!$("#wdcp-mcls-subscribe").length) return false;
if (!$("#wdcp-mcls-subscribe").is(":visible")) return false;
to_send["wdcp-mcls-subscribe"] = $("#wdcp-mcls-subscribe").is(":checked") ? 1 : 0;
});
})(jQuery);
</script>
EOMclsPublicJs;
}
}
if (is_admin()) Wdcp_Mcls_Admin_Pages::serve();
else Wdcp_Mcls_Public_Pages::serve();<file_sep><?php
/*
Author: <NAME>, Feast LLC
URL: http://www.wearefeast.com
Modification of Bones Theme
URL: http://themble.com/bones/
This is where you can drop your custom functions or
just edit things like thumbnail sizes, header images,
sidebars, comments, ect.
*/
/************* INCLUDE NEEDED FILES ***************/
/*
1. library/bones.php
- head cleanup (remove rsd, uri links, junk css, ect)
- enqueueing scripts & styles
- theme support functions
- custom menu output & fallbacks
- related post function
- page-navi function
- removing <p> from around images
- customizing the post excerpt
- custom google+ integration
- adding custom fields to user profiles
*/
require_once('library/bones.php'); // if you remove this, bones will break
/*
2. library/custom-post-type.php
- an example custom post type
- example custom taxonomy (like categories)
- example custom taxonomy (like tags)
*/
require_once('library/custom-post-type.php'); // you can disable this if you like
/*
3. library/admin.php
- removing some default WordPress dashboard widgets
- an example custom dashboard widget
- adding custom login css
- changing text in footer of admin
*/
// require_once('library/admin.php'); // this comes turned off by default
/*
4. library/translation/translation.php
- adding support for other languages
*/
// require_once('library/translation/translation.php'); // this comes turned off by default
/*
5. library/script-loader.php
- one place for all enqueue/registering
*/
require_once('library/script-loader.php'); // ADDED BY FEAST - VITAL!!! BEWARE SLOPPY PLUGINS (LOOKING AT YOU COMMENTS PLUS)
/************* FEAST MODIFICATIONS *************/
// if statement is required, otherwise CMS will not load after ACF plugin upgrades
include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
if( is_plugin_active('advanced-custom-fields/acf.php') ) {
// UNCOMMENT IF NEEDED
//register_field('NextGen_Field', dirname(__File__) . '/fields/nextgen.php');
//include_once( WP_PLUGIN_DIR . '/advanced-custom-fields-location-field-add-on/location-field.php' );
}
// Limit character count in Contact Form 7
add_filter( 'wpcf7_validate_textarea', 'character_length_validation_filter', 11, 2 );
add_filter( 'wpcf7_validate_textarea*', 'character_length_validation_filter', 11, 2 );
function character_length_validation_filter( $result, $tag ) {
$name = $tag['name'];
if ( !$result['valid'] )
return $result;
$max_words = 500;
$word_count = strlen( $_POST[$name] );
if ( $max_words < $word_count ) {
$difference = $word_count - $max_words;
$result['valid'] = false;
$result['reason'][$name] = "Please shorten your comments by " . $difference . " characters.";
}
return $result;
}
// If custom excerpt lengths are required
function custom_excerpt_length( $length ) {
return 15;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
// JetPack is cool, but kind of a douche
function jptweak_remove_share() {
remove_filter( 'the_content', 'sharing_display',19 );
remove_filter( 'the_excerpt', 'sharing_display',19 );
}
add_action( 'loop_end', 'jptweak_remove_share' );
function jptweak_remove_admin_share() {
remove_meta_box( 'sharing_meta' , 'page' , 'advanced' );
}
add_action( 'add_meta_boxes', 'jptweak_remove_admin_share', 99 );
// I hate nag messages, but I'm not sure if this works, oh well
remove_action( 'admin_notices', 'show_nag_messages', 11);
// Makes draft posts visiable by adding ?key=foryoureyesonly to preview URLs
add_filter( 'posts_results', 'wpse46014_peek_into_private', null, 2 );
function wpse46014_peek_into_private( $posts, &$query ) {
if ( sizeof( $posts ) != 1 ) return $posts; /* not interested */
$status = get_post_status( $posts[0] );
$post_status_obj = get_post_status_object( $status );
if ( $post_status_obj->public ) return $posts; /* it's public */
if ( !isset( $_GET['key'] ) || $_GET['key'] != 'foryoureyesonly' )
return $posts; /* not for your eyes */
$query->_my_private_stash = $posts; /* stash away */
add_filter( 'the_posts', 'wpse46014_inject_private', null, 2 );
}
function wpse46014_inject_private( $posts, &$query ) {
/* do only once */
remove_filter( 'the_posts', 'wpse46014_inject_private', null, 2 );
return $query->_my_private_stash;
}
// TEST
// Grant authors the ability to add html to posts
function feast_disable_kses_content() {
remove_filter('content_save_pre', 'wp_filter_post_kses', 10);
}
add_action('init','feast_disable_kses_content',20);
// Keep WordPress from stripping HTML tags out of the Menu Descriptions
remove_filter('nav_menu_description', 'strip_tags');
function cus_wp_setup_nav_menu_item($menu_item) {
$menu_item->description = apply_filters('nav_menu_description', $menu_item->post_content );
return $menu_item;
}
add_filter( 'wp_setup_nav_menu_item', 'cus_wp_setup_nav_menu_item' );
function feast_register_menus() {
//unregister_nav_menu( 'main_nav' );
//unregister_nav_menu( 'footer_links' );
register_nav_menus(
array(
'Social Links' => __( 'Social Links' ),
'Mobile Nav' => __( 'Mobile Nav' ),
'Subnav: Locations' => __( 'Subnav: Locations' )
)
);
}
add_action( 'init', 'feast_register_menus' );
/************* THUMBNAIL SIZE OPTIONS *************/
// Thumbnail sizes
add_image_size( 'feast-thumb-600', 600, 150, true );
add_image_size( 'feast-thumb-300', 300, 100, true );
add_theme_support( 'post-thumbnails' );
/*
to add more sizes, simply copy a line from above
and change the dimensions & name. As long as you
upload a "featured image" as large as the biggest
set width or height, all the other sizes will be
auto-cropped.
To call a different size, simply change the text
inside the thumbnail function.
For example, to call the 300 x 300 sized image,
we would use the function:
<?php the_post_thumbnail( 'bones-thumb-300' ); ?>
for the 600 x 100 image:
<?php the_post_thumbnail( 'bones-thumb-600' ); ?>
You can change the names and dimensions to whatever
you like. Enjoy!
*/
/************* ACTIVE SIDEBARS ********************/
// Sidebars & Widgetizes Areas
function bones_register_sidebars() {
register_sidebar(array(
'id' => 'sidebar1',
'name' => __('Sidebar', 'feasttheme'),
'description' => __('The primary sidebar.', 'feasttheme'),
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h4 class="widgettitle">',
'after_title' => '</h4>',
));
/*
to add more sidebars or widgetized areas, just copy
and edit the above sidebar code. In order to call
your new sidebar just use the following code:
Just change the name to whatever your new
sidebar's id is, for example:
register_sidebar(array(
'id' => 'sidebar2',
'name' => __('Sidebar 2', 'feasttheme'),
'description' => __('The second (secondary) sidebar.', 'feasttheme'),
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h4 class="widgettitle">',
'after_title' => '</h4>',
));
To call the sidebar in your template, you can just copy
the sidebar.php file and rename it to your sidebar's name.
So using the above example, it would be:
sidebar-sidebar2.php
*/
} // don't remove this bracket!
/************* COMMENT LAYOUT *********************/
// Comment Layout
function bones_comments($comment, $args, $depth) {
$GLOBALS['comment'] = $comment; ?>
<li <?php comment_class(); ?>>
<article id="comment-<?php comment_ID(); ?>" class="clearfix">
<header class="comment-author vcard">
<?php
/*
this is the new responsive optimized comment image. It used the new HTML5 data-attribute to display comment gravatars on larger screens only. What this means is that on larger posts, mobile sites don't have a ton of requests for comment images. This makes load time incredibly fast! If you'd like to change it back, just replace it with the regular wordpress gravatar call:
echo get_avatar($comment,$size='32',$default='<path_to_url>' );
*/
?>
<!-- custom gravatar call -->
<?php
// create variable
$bgauthemail = get_comment_author_email();
?>
<img data-gravatar="http://www.gravatar.com/avatar/<?php echo md5($bgauthemail); ?>?s=32" class="load-gravatar avatar avatar-48 photo" height="32" width="32" src="<?php echo get_template_directory_uri(); ?>/library/images/nothing.gif" />
<!-- end custom gravatar call -->
<?php printf(__('<cite class="fn">%s</cite>', 'feasttheme'), get_comment_author_link()) ?>
<time datetime="<?php echo comment_time('Y-m-j'); ?>"><a href="<?php echo htmlspecialchars( get_comment_link( $comment->comment_ID ) ) ?>"><?php comment_time(__('F jS, Y', 'feasttheme')); ?> </a></time>
<?php edit_comment_link(__('(Edit)', 'feasttheme'),' ','') ?>
</header>
<?php if ($comment->comment_approved == '0') : ?>
<div class="alert info">
<p><?php _e('Your comment is awaiting moderation.', 'feasttheme') ?></p>
</div>
<?php endif; ?>
<section class="comment_content clearfix">
<?php comment_text() ?>
</section>
<?php comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => $args['max_depth']))) ?>
</article>
<!-- </li> is added by WordPress automatically -->
<?php
} // don't remove this bracket!
/************* SEARCH FORM LAYOUT *****************/
// Search Form
function bones_wpsearch($form) {
$form = '<form role="search" method="get" id="searchform" action="' . home_url( '/' ) . '" >
<label class="screen-reader-text" for="s">' . __('Search for:', 'feasttheme') . '</label>
<input type="text" value="' . get_search_query() . '" name="s" id="s" placeholder="'.esc_attr__('Search the Site...','feasttheme').'" />
<input type="submit" id="searchsubmit" value="'. esc_attr__('Search') .'" />
</form>';
return $form;
} // don't remove this bracket!
?>
<file_sep><?php
/*
* Advanced Custom Fields - New field template
*
* Create your field's functionality below and use the function:
* register_field($class_name, $file_path) to include the field
* in the acf plugin.
*
* Documentation:
* functions.php : register_field('NextGen_Field', dirname(__File__) . '/fields/nextgen.php');
*
*/
class NextGen_Field extends acf_Field {
/*--------------------------------------------------------------------------------------
*
* Constructor
* - This function is called when the field class is initalized on each page.
* - Here you can add filters / actions and setup any other functionality for your field
*
* @author <NAME>
* @since 2.2.0
*
*-------------------------------------------------------------------------------------*/
function __construct($parent) {
// do not delete!
parent::__construct($parent);
// set name / title
$this->name = 'nextgen';
// variable name (no spaces / special characters / etc)
$this->title = __("NextGen Gallery Select", 'acf');
// field label (Displayed in edit screens)
}
/*--------------------------------------------------------------------------------------
*
* create_options
* - this function is called from core/field_meta_box.php to create extra options
* for your field
*
* @params
* - $key (int) - the $_POST obejct key required to save the options to the field
* - $field (array) - the field object
*
* @author <NAME>
* @since 1.0.0
*
*-------------------------------------------------------------------------------------*/
function create_options($key, $field) {
// defaults
$field['allow_null'] = isset($field['allow_null']) ? $field['allow_null'] : '0';
?>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Allow Null?",'acf'); ?></label>
</td>
<td>
<?php
$this->parent->create_field(array(
'type' => 'radio',
'name' => 'fields['.$key.'][allow_null]',
'value' => $field['allow_null'],
'choices' => array(
'1' => __("Yes",'acf'),
'0' => __("No",'acf'),
),
'layout' => 'horizontal',
));
?>
</td>
</tr>
<?php
}
/*--------------------------------------------------------------------------------------
*
* pre_save_field
* - this function is called when saving your acf object. Here you can manipulate the
* field object and it's options before it gets saved to the database.
*
* @author <NAME>
* @since 2.2.0
*
*-------------------------------------------------------------------------------------*/
function pre_save_field($field) {
// do stuff with field (mostly format options data)
return parent::pre_save_field($field);
}
/*--------------------------------------------------------------------------------------
*
* create_field
* - this function is called on edit screens to produce the html for this field
*
* @author <NAME>
* @since 1.0.0
*
*-------------------------------------------------------------------------------------*/
function create_field($field) {
// defaults
$field['allow_null'] = isset($field['allow_null']) ? $field['allow_null'] : false;
$selected_value = $field['value'];
$is_selected = '';
global $ngg;
global $nggdb;
$gallerylist = $nggdb->find_all_galleries($order_by = 'title', $order_dir = 'ASC');
?>
<select id="<?php echo $field['name'] ?>" class="<?php echo $field['class'] ?>"
name="<?php echo $field['name'] ?>">
<?php
// null
if($field['allow_null'] == '1')
{
echo '<option value="null"> - None - </option>';
}
foreach($gallerylist as $gallery) :
$name = ( empty($gallery->title) ) ? $gallery->name : $gallery->title;
if ($gallery->gid == $selected_value) {
$is_selected = 'selected="selected"';
} else {
$is_selected = '';
} ?>
<option value="<?php echo $gallery->gid ?>" <?php echo $is_selected ?>><?php echo $name ?></option>
<?php endforeach ?>
</select>
<?php
}
/*--------------------------------------------------------------------------------------
*
* admin_head
* - this function is called in the admin_head of the edit screen where your field
* is created. Use this function to create css and javascript to assist your
* create_field() function.
*
* @author <NAME>
* @since 2.2.0
*
*-------------------------------------------------------------------------------------*/
function admin_head() {
}
/*--------------------------------------------------------------------------------------
*
* admin_print_scripts / admin_print_styles
* - this function is called in the admin_print_scripts / admin_print_styles where
* your field is created. Use this function to register css and javascript to assist
* your create_field() function.
*
* @author <NAME>
* @since 3.0.0
*
*-------------------------------------------------------------------------------------*/
function admin_print_scripts() {
}
function admin_print_styles() {
}
/*--------------------------------------------------------------------------------------
*
* update_value
* - this function is called when saving a post object that your field is assigned to.
* the function will pass through the 3 parameters for you to use.
*
* @params
* - $post_id (int) - usefull if you need to save extra data or manipulate the current
* post object
* - $field (array) - usefull if you need to manipulate the $value based on a field option
* - $value (mixed) - the new value of your field.
*
* @author <NAME>
* @since 2.2.0
*
*-------------------------------------------------------------------------------------*/
function update_value($post_id, $field, $value) {
// do stuff with value
//wp_set_object_terms($post_id, array(1), 'category', FALSE);
// save value
parent::update_value($post_id, $field, $value);
}
/*--------------------------------------------------------------------------------------
*
* get_value
* - called from the edit page to get the value of your field. This function is useful
* if your field needs to collect extra data for your create_field() function.
*
* @params
* - $post_id (int) - the post ID which your value is attached to
* - $field (array) - the field object.
*
* @author <NAME>
* @since 2.2.0
*
*-------------------------------------------------------------------------------------*/
function get_value($post_id, $field) {
// get value
$value = parent::get_value($post_id, $field);
// format value
// return value
return $value;
}
/*--------------------------------------------------------------------------------------
*
* get_value_for_api
* - called from your template file when using the API functions (get_field, etc).
* This function is useful if your field needs to format the returned value
*
* @params
* - $post_id (int) - the post ID which your value is attached to
* - $field (array) - the field object.
*
* @author <NAME>
* @since 3.0.0
*
*-------------------------------------------------------------------------------------*/
function get_value_for_api($post_id, $field) {
// get value
$value = $this->get_value($post_id, $field);
if($value == 'null')
{
$value = false;
}
// return value
return $value;
}
}
?><file_sep><?php
/*
Plugin Name: Social Discussion
Description: Synchronizes the relevant discussion from social networks in a separate tab on your page. <br /><strong>Requires <em>Custom Comments Template</em> add-on to be activated.</strong>
Plugin URI: http://premium.wpmudev.org/project/comments-plus
Version: 1.0
Author: <NAME> (Incsub)
*/
/**
* Handles admin pages, settings and procedures.
*/
class Wdcp_Sd_AdminPages {
private $_data;
private function __construct () {
$this->_data = new Wdcp_Options;
}
public static function serve () {
$me = new Wdcp_Sd_AdminPages;
$me->_add_hooks();
}
private function _add_hooks () {
add_action('wdcp-options-plugins_options', array($this, 'register_settings'));
$services = $this->_data->get_option('sd_services');
$services = $services ? $services : array();
if (in_array('facebook', $services)) {
add_action('wdcp-remote_comment_posted-facebook', array($this, 'handle_facebook_comment_sent'), 10, 3);
}
if (in_array('twitter', $services)) {
add_action('wdcp-remote_comment_posted-twitter', array($this, 'handle_twitter_comment_sent'), 10, 3);
}
}
/* ----- Comments posted handlers -----*/
function handle_facebook_comment_sent ($comment_id, $result, $data) {
$this->_handle_comment_sent($comment_id, 'facebook', $result['id'], $data);
}
function handle_twitter_comment_sent ($comment_id, $result, $data) {
$this->_handle_comment_sent($comment_id, 'twitter', @$result->id_str, $data);
}
/**
* Adds Social Discussion root entry.
*/
private function _handle_comment_sent ($comment_id, $type, $remote_id, $data) {
if (!$remote_id) return false;
$post = array(
'post_content' => $data['comment_content'],
'post_type' => 'wdcp_social_discussion_root',
'post_status' => 'publish',
);
$post_id = wp_insert_post($post);
$meta = array(
'sd_type' => $type,
'remote_id' => $remote_id,
);
update_post_meta($post_id, 'wdcp_sd_meta', $meta);
add_comment_meta($comment_id, 'wdcp_sd_root', $post_id) ;
}
/* ----- Settings ----- */
function register_settings () {
add_settings_section('wdcp_sd_settings', __('Social Discussion', 'wdcp'), array($this, 'check_cct_presence'), 'wdcp_options');
if (!class_exists('Wdcp_Cct_Admin_Pages')) return false;
add_settings_field('wdcp_sd_services', __('Sync discussions from these services', 'wdcp'), array($this, 'create_services_box'), 'wdcp_options', 'wdcp_sd_settings');
add_settings_field('wdcp_sd_default_service', __('Default discussion tab', 'wdcp'), array($this, 'create_default_service_box'), 'wdcp_options', 'wdcp_sd_settings');
add_settings_field('wdcp_sd_schedule', __('Schedule', 'wdcp'), array($this, 'create_schedule_box'), 'wdcp_options', 'wdcp_sd_settings');
add_settings_field('wdcp_sd_override_theme', __('Appearance', 'wdcp'), array($this, 'create_override_theme_box'), 'wdcp_options', 'wdcp_sd_settings');
}
function check_cct_presence () {
if (class_exists('Wdcp_Cct_Admin_Pages')) return true;
echo '<div class="error below-h2"><p>' . __('Please, activate the <b>Custom Comments Template</b> add-on.', 'wdcp') . '</p></div>';
}
function create_services_box () {
$_services = array(
'facebook' => __('Facebook', 'wdcp'),
'twitter' => __('Twitter', 'wdcp'),
);
$services = $this->_data->get_option('sd_services');
$services = $services ? $services : array();
foreach ($_services as $service => $label) {
$checked = in_array($service, $services) ? 'checked="checked"' : '';
echo '' .
"<input type='checkbox' name='wdcp_options[sd_services][]' value='{$service}' id='sd_services-{$service}' {$checked} />" .
' ' .
"<label for='sd_services-{$service}'>{$label}</label>" .
"<br />";
}
echo '<div><small>' . __('Please select service(s) you wish to sync social discussion with.', 'wdcp') . '</small></div>';
}
function create_default_service_box () {
$_services = array(
'facebook' => __('Facebook', 'wdcp'),
'twitter' => __('Twitter', 'wdcp'),
'comments' => __('WordPress Comments', 'wdcp'),
);
$default = $this->_data->get_option('sd_default_service');
$default = $default ? $default : 'comments';
foreach ($_services as $service => $label) {
$checked = ($service == $default) ? 'checked="checked"' : '';
echo '' .
"<input type='radio' name='wdcp_options[sd_default_service]' value='{$service}' id='sd_default_service-{$service}' {$checked} />" .
' ' .
"<label for='sd_default_service-{$service}'>{$label}</label>" .
"<br />";
}
echo '<div><small>' . __('The discussion panel you select here will be open by default on page load.', 'wdcp') . '</small></div>';
}
function create_schedule_box () {
$_schedules = array(
'0' => __('Hourly', 'wdcp'),
'10800' => __('Every 3 hours', 'wdcp'),
'21600' => __('Every 6 hours', 'wdcp'),
'43200' => __('Every 12 hours', 'wdcp'),
'86400' => __('Daily', 'wdcp'),
);
$default = $this->_data->get_option('wdcp_sd_poll_interval');
echo '<select name="wdcp_options[wdcp_sd_poll_interval]">';
foreach ($_schedules as $lag => $lbl) {
$sel = ($lag == $default) ? 'selected="selected"' : '';
echo "<option value='{$lag}' {$sel}>{$lbl} </option>";
}
echo '</select>';
echo '<div><small>' . __('Discussions from your selected networks will be synced this often with your other comments.', 'wdcp') . '</small></div>';
// Limit
$_limits = array(1, 5, 10, 15, 20, 25, 30, 40, 50);
$limit = (int)$this->_data->get_option('sd_limit');
$limit = $limit ? $limit : Wdcp_Sd_Importer::PROCESSING_SCOPE_LIMIT;
echo '<label for="wdcp-sd_limit">' . __('Limit import to this many latest comments:', 'wdcp') . '</label> ';
echo '<select name="wdcp_options[sd_limit]" id="wdcp-sd_limit">';
foreach ($_limits as $lim) {
$sel = ($lim == $limit) ? 'selected="selected"' : '';
echo "<option value='{$lim}' {$sel}>{$lim}</option>";
}
echo '</select>';
echo '<div><small>' . __('Discussion import takes time, so it is a good idea to limit its scope.', 'wdcp') . '</small></div>';
echo '<div><small>' . __('This option lets you choose how many of your latest social comments will be polled for discussion updates.', 'wdcp') . '</small></div>';
}
function create_override_theme_box () {
$checked = $this->_data->get_option('sd_theme_override') ? 'checked="checked"' : '';
echo '' .
'<input type="hidden" name="wdcp_options[sd_theme_override]" value="" />' .
"<input type='checkbox' name='wdcp_options[sd_theme_override]' id='wdcp-sd_theme_override' value='1' {$checked} />" .
' ' .
'<label for="wdcp-sd_theme_override">' . __('Do not load styles - my theme already has all the styles I need', 'wdcp') . '</label>' .
'<div><small>' . __('If you check this option, no social discussion style will be loaded.', 'wdcp') . '</small></div>' .
'';
}
}
/**
* Handles public pages - appearance and requests.
*/
class Wdcp_Sd_PublicPages {
private $_data;
private $_db;
private $_services;
private function __construct () {
global $wpdb;
$this->_data = new Wdcp_Options;
$this->_db = $wpdb;
$services = $this->_data->get_option('sd_services');
$services = $services ? $services : array();
$services[] = 'comments';
$this->_services = $services;
}
public static function serve () {
$me = new Wdcp_Sd_PublicPages;
$me->_add_hooks();
}
private function _add_hooks () {
add_filter('wdcp-wordpress_custom_icon_selector', array($this, 'add_custom_icon_selector'));
add_action('wdcp-load_scripts-public', array($this, 'js_load_scripts'));
add_action('wdcp-load_styles-public', array($this, 'css_load_styles'));
add_action('wdcp-cct-comments_top', array($this, 'comments_top'));
add_action('wdcp-cct-comments_bottom', array($this, 'comments_bottom'));
}
function add_custom_icon_selector ($selector) {
$sd_selector = "#wdcp-sd-discussion_switcher li a#wdcp-sd-discussion-comments-switch";
return $selector ? "{$selector}, {$sd_selector}" : $sd_selector;
}
function js_load_scripts () {
$default = $this->_data->get_option('sd_default_service');
$default = $default ? $default : 'comments';
printf(
'<script type="text/javascript">
var _wdcp_sd = {
"default_service": "%s"
};
</script>',
$default
);
wp_enqueue_script('wdcp-sd-discussion', WDCP_PLUGIN_URL . '/js/discussion.js', array('jquery'));
}
function css_load_styles () {
$override = $this->_data->get_option('sd_theme_override');
if (!current_theme_supports('wdcp-sd-discussion') && !$override) {
wp_enqueue_style('wdcp-sd-discussion', WDCP_PLUGIN_URL . '/css/discussion.css');
}
}
function comments_top ($post_id) {
echo '<ul id="wdcp-sd-discussion_switcher">';
foreach ($this->_services as $service) {
echo "<li><a href='#discussion-{$service}' data-discussion_service='{$service}' id='wdcp-sd-discussion-{$service}-switch'><span>" . ucfirst($service) . '</span></a></li>';
}
echo '</ul>';
echo '<div style="clear:left"></div>';
echo '<div id="wdcp-sd-discussion-comments" class="wdcp-sd-discussion">';
}
function comments_bottom ($post_id) {
echo '</div>'; // #wdcp-sd-discussion-comments
foreach ($this->_services as $service) {
if ('comments' == $service) continue;
echo "<div id='wdcp-sd-discussion-{$service}' class='wdcp-sd-discussion'>";
$this->_get_discussion_for_service($post_id, $service);
echo '</div>';
}
}
private function _get_discussion_for_service ($post_id, $service) {
$post_id = (int)$post_id;
if (!$post_id) return false;
$root_ids = $this->_db->get_col("SELECT meta_value FROM {$this->_db->comments} AS c, {$this->_db->commentmeta} AS mc WHERE mc.meta_key = 'wdcp_sd_root' AND c.comment_post_ID={$post_id} AND c.comment_ID = mc.comment_id");
$root_ids = $root_ids ? $root_ids : array();
switch ($service) {
case 'facebook': return $this->_get_facebook_discussion($root_ids);
case 'twitter': return $this->_get_twitter_discussion($root_ids);
}
return false;
}
private function _get_facebook_discussion ($post_ids) {
foreach ($post_ids as $post_id) {
$post = get_post($post_id);
$meta = get_post_meta($post_id, 'wdcp_sd_meta', true);
if ('facebook' != $meta['sd_type']) continue;
$comments = $this->_db->get_results(
"SELECT * FROM {$this->_db->comments} AS c, {$this->_db->commentmeta} AS mc WHERE mc.meta_key='wdcp_sd_facebook_remote_id' AND c.comment_post_ID={$post_id} AND c.comment_ID=mc.comment_id"
);
$this->_show_post_as_comment($post, 'facebook', $comments);
}
}
private function _get_twitter_discussion ($post_ids) {
foreach ($post_ids as $post_id) {
$post = get_post($post_id);
$meta = get_post_meta($post_id, 'wdcp_sd_meta', true);
if ('twitter' != $meta['sd_type']) continue;
$comments = $this->_db->get_results(
"SELECT * FROM {$this->_db->comments} AS c, {$this->_db->commentmeta} AS mc WHERE mc.meta_key='wdcp_sd_twitter_remote_id' AND c.comment_post_ID={$post_id} AND c.comment_ID=mc.comment_id"
);
$this->_show_post_as_comment($post, 'twitter', $comments);
}
}
private function _show_post_as_comment ($post, $type, $comments) {
$post_id = (int)$post->ID;
$comment = $this->_db->get_row("SELECT * FROM {$this->_db->comments} AS c, {$this->_db->commentmeta} AS mc WHERE mc.meta_key='wdcp_sd_root' AND mc.meta_value={$post_id} AND c.comment_ID=mc.comment_id");
$meta = get_comment_meta($comment->comment_ID, 'wdcp_comment', true);
if ('facebook' == $type) {
$uid = $meta['wdcp_fb_author_id'];
$avatar = "<img class='avatar avatar-40 photo' width='40' height='40' src='http://graph.facebook.com/{$uid}/picture' />";
} else if ('twitter' == $type) {
$url = $meta['wdcp_tw_avatar'];
$avatar = "<img class='avatar avatar-40 photo' width='40' height='40' src='{$url}' />";
}
echo '<ul><li>';
include WDCP_PLUGIN_BASE_DIR . '/lib/forms/wdcp-social_discussion_root_comment.php';
echo '<ul>';
if ('facebook' == $type) {
foreach ($comments as $comment) {
$uid = get_comment_meta($comment->comment_ID, 'wdcp_fb_author_id', true);
$avatar = "<img class='avatar avatar-40 photo' width='40' height='40' src='http://graph.facebook.com/{$uid}/picture' />";
include WDCP_PLUGIN_BASE_DIR . '/lib/forms/wdcp-social_discussion_comment.php';
}
} else if ('twitter' == $type) {
foreach ($comments as $comment) {
$url = esc_url(get_comment_meta($comment->comment_ID, 'wdcp_tw_avatar', true));
$avatar = "<img class='avatar avatar-40 photo' width='40' height='40' src='{$url}' />";
include WDCP_PLUGIN_BASE_DIR . '/lib/forms/wdcp-social_discussion_comment.php';
}
}
echo '</ul>';
echo '</li></ul>';
}
}
/**
* Handles comments import from supported social networks.
*/
class Wdcp_Sd_Importer {
const PROCESSING_SCOPE_LIMIT = 10;
private $_data;
private $_db;
private $_services;
private function __construct () {
global $wpdb;
$this->_data = new Wdcp_Options;
$this->_db = $wpdb;
}
public static function serve () {
$me = new Wdcp_Sd_Importer;
add_action('wdcp-sd_import_comments', array($me, 'import'));
if (!wp_next_scheduled('wdcp-sd_import_comments')) wp_schedule_event(time()+600, 'hourly', 'wdcp-sd_import_comments');
return $me;
}
public function import () {
$services = $this->_data->get_option('sd_services');
$services = $services ? $services : array();
$this->_services = $services;
$limit = (int)$this->_data->get_option('sd_limit');
$limit = $limit ? $limit : self::PROCESSING_SCOPE_LIMIT;
$post_ids = $this->_db->get_col("SELECT DISTINCT meta_value FROM {$this->_db->comments} AS c, {$this->_db->commentmeta} AS mc WHERE mc.meta_key = 'wdcp_sd_root' AND c.comment_ID = mc.comment_id ORDER BY c.comment_date LIMIT {$limit}");
foreach ($post_ids as $post_id) {
$this->_process_discussion($post_id);
}
}
private function _process_discussion ($post_id) {
$post_id = (int)$post_id;
if (!$post_id) return false;
$now = time();
$meta = get_post_meta($post_id, 'wdcp_sd_meta', true);
if (!isset($meta['sd_type']) || !in_array($meta['sd_type'], $this->_services)) return false; // Don't sync this
$last_polled = (int)get_post_meta($post_id, 'wdcp_sd_last_polled', true);
if ($last_polled + (int)$this->_data->get_option('wdcp_sd_poll_interval') > $now) return false; // No need to poll this item
$this->_fetch_discussion($post_id, $meta['remote_id'], $meta['sd_type']);
update_post_meta($post_id, 'wdcp_sd_last_polled', $now);
}
private function _fetch_discussion ($post_id, $remote_id, $type) {
switch ($type) {
case "facebook": return $this->_fetch_facebook_discussion($post_id, $remote_id);
case "twitter": return $this->_fetch_twitter_discussion($post_id, $remote_id);
}
return false;
}
private function _fetch_facebook_discussion ($post_id, $item_id) {
if (!$item_id) return false;
$token = WDCP_APP_ID . '|' . WDCP_APP_SECRET;
$res = wp_remote_get("https://graph.facebook.com/{$item_id}/comments?access_token={$token}", array(
'method' => 'GET',
'timeout' => '5',
'redirection' => '5',
'user-agent' => 'wdcp-sd',
'blocking' => true,
'compress' => false,
'decompress' => true,
'sslverify' => false
));
if (is_wp_error($res)) return false; // Request fail
if ((int)$res['response']['code'] != 200) return false; // Request fail
$body = @json_decode($res['body']);
if (empty($body->data)) return false; // No data found
foreach ($body->data as $item) {
if ($this->_comment_already_imported($item->id, 'facebook')) continue; // We already have this comment, continue.
$data = array(
'comment_post_ID' => $post_id,
'comment_author' => $item->from->name,
'comment_author_url' => 'http://www.facebook.com/profile.php?id=' . $item->from->id,
'comment_content' => $item->message,
'comment_type' => 'wdcp_sd_imported',
'comment_date' => date('Y-m-d H:i:s', strtotime($item->created_time)),
);
$meta = array (
'wdcp_fb_author_id' => $item->from->id,
'wdcp_sd_facebook_remote_id' => $item->id,
);
$comment_id = wp_insert_comment($data);
if (!$comment_id) continue;
foreach ($meta as $mkey => $mval) add_comment_meta($comment_id, $mkey, $mval);
}
}
private function _fetch_twitter_discussion ($post_id, $item_id) {
if (!$item_id) return false;
$res = wp_remote_get(
"http://api.twitter.com/1/statuses/show.json?id={$item_id}", array(
'method' => 'GET',
'timeout' => '5',
'redirection' => '5',
'user-agent' => 'wdcp-sd',
'blocking' => true,
'compress' => false,
'decompress' => true,
'sslverify' => false
)
);
if (is_wp_error($res)) return false; // Request fail
if ((int)$res['response']['code'] != 200) return false; // Request fail
$tweet = @json_decode($res['body']);
$user = $tweet->user->name;
$res = wp_remote_get(
"http://search.twitter.com/search.json?q=to:{$user}", array(
'method' => 'GET',
'timeout' => '5',
'redirection' => '5',
'user-agent' => 'wdcp-sd',
'blocking' => true,
'compress' => false,
'decompress' => true,
'sslverify' => false
)
);
if (is_wp_error($res)) return false; // Request fail
if ((int)$res['response']['code'] != 200) return false; // Request fail
$body = @json_decode($res['body']);
$results = @$body->results ? array_reverse($body->results) : array();
foreach ($results as $item) {
if ($this->_comment_already_imported($item->id_str, 'twitter')) continue; // We already have this comment, continue.
$data = array(
'comment_post_ID' => $post_id,
'comment_author' => $item->from_user,
'comment_author_url' => 'http://www.twitter.com/' . $item->from_user,
'comment_content' => $item->text,
'comment_type' => 'wdcp_sd_imported',
'comment_date' => date('Y-m-d H:i:s', strtotime($item->created_at)),
);
$meta = array (
'wdcp_tw_avatar' => $item->profile_image_url,
'wdcp_sd_twitter_remote_id' => $item->id_str,
);
$comment_id = wp_insert_comment($data);
if (!$comment_id) continue;
foreach ($meta as $mkey => $mval) add_comment_meta($comment_id, $mkey, $mval);
}
}
private function _comment_already_imported ($remote_id, $type) {
$id_str = "wdcp_sd_{$type}_remote_id";
$remote_id = esc_sql($remote_id);
return $this->_db->get_var("SELECT comment_id FROM {$this->_db->commentmeta} WHERE meta_key='{$id_str}' AND meta_value='{$remote_id}'");
}
}
Wdcp_Sd_Importer::serve();
if (is_admin()) Wdcp_Sd_AdminPages::serve();
else Wdcp_Sd_PublicPages::serve();
<file_sep><?php
/**
* Handles generic public functionality
* and delegates to the worker.
*/
class Wdcp_PublicPages {
var $worker;
var $data;
function Wdcp_PublicPages () { $this->__construct(); }
function __construct () {
if ($this->_load_dependencies()) {
$this->data = new Wdcp_Options;
$this->worker = new Wdcp_CommentsWorker;
} // else...
}
function _load_dependencies () {
if (!class_exists('Wdcp_CommentsWorker')) require_once WDCP_PLUGIN_BASE_DIR . '/lib/class_wdcp_comments_worker.php';
return (class_exists('Wdcp_CommentsWorker'));
}
/**
* Main entry point.
*
* @static
*/
function serve () {
$me = new Wdcp_PublicPages;
$me->add_hooks();
}
function js_load_scripts () {
printf(
'<script type="text/javascript">var _wdcp_ajax_url="%s";</script>',
admin_url('admin-ajax.php')
);
do_action('wdcp-load_scripts-public');
}
function css_load_styles () {
do_action('wdcp-load_styles-public');
}
function check_if_wordpress_provider_allowed ($comment) {
$skips = (array)$this->data->get_option('skip_services');
if (!in_array('wordpress', $skips)) return $comment;
if (!isset($comment['_wdcp_provider'])) return array();
return $comment;
}
function reset_preferred_provider ($data) {
//if (!isset($_COOKIE["wdcp_preferred_provider"])) return $data;
setcookie("wdcp_preferred_provider", "comment-provider-wordpress", strtotime("+1 year"), "/");
return $data;
}
public function get_footer_hook () {
$hook = defined('WDCP_FOOTER_DEPENDENCIES_HOOK') && WDCP_FOOTER_DEPENDENCIES_HOOK
? WDCP_FOOTER_DEPENDENCIES_HOOK
: 'get_footer'
;
return apply_filters('wdcp-core-hooks-footer_dependencies', $hook);
}
function add_hooks () {
//add_action('wp_print_scripts', array($this, 'js_load_scripts'));
//add_action('wp_print_styles', array($this, 'css_load_styles'));
add_action('wp_enqueue_scripts', array($this, 'js_load_scripts'));
add_action('wp_enqueue_scripts', array($this, 'css_load_styles'));
// Bind worker handlers
//add_action('wp_print_scripts', array($this->worker, 'js_load_scripts'));
//add_action('wp_print_styles', array($this->worker, 'css_load_styles'));
add_action('wp_enqueue_scripts', array($this->worker, 'js_load_scripts'));
add_action('wp_enqueue_scripts', array($this->worker, 'css_load_styles'));
add_filter('preprocess_comment', array($this, 'check_if_wordpress_provider_allowed'));
add_filter('preprocess_comment', array($this, 'reset_preferred_provider'));
$start_hook = $this->data->get_option('begin_injection_hook');
$end_hook = $this->data->get_option('finish_injection_hook');
$begin_injection_hook = $start_hook ? $start_hook : 'comment_form_before';
$finish_injection_hook = $end_hook ? $end_hook : 'comment_form_after';
add_action('wp_head', array($this->worker, 'header_dependencies'));
add_filter($begin_injection_hook, array($this->worker, 'begin_injection'));
add_filter($finish_injection_hook, array($this->worker, 'finish_injection'));
add_action($this->get_footer_hook(), array($this->worker, 'footer_dependencies'));
add_filter('get_avatar', array($this->worker, 'replace_avatars'), 10, 2);
}
}<file_sep><?php
/*
Plugin Name: Fake Twitter Email
Description: Twitter doesn't allow access to users' emails, which may cause comment approval issues with WordPress. This add-on will associate unique fake email addresses with Twitter commenters to help with this issue.
Plugin URI: http://premium.wpmudev.org/project/comments-plus
Version: 1.0
Author: <NAME> (Incsub)
*/
class Wdcp_Fte_AdminPages {
private function __construct () {}
public static function serve () {
$me = new Wdcp_Fte_AdminPages;
$me->_add_hooks();
}
private function _add_hooks () {
add_filter('wdcp-comment_data-twitter', array($this, 'process_data'));
}
function process_data ($data) {
$uid = @$data['comment_author'];
if (!$uid) return $data;
$uid = preg_replace('/[^-_a-zA-Z0-9]/', '', $uid);
$domain = preg_replace('/www\./', '', parse_url(site_url(), PHP_URL_HOST));
@$data['comment_author_email'] = "{$uid}@twitter.{$domain}";
return $data;
}
}
if (is_admin()) Wdcp_Fte_AdminPages::serve();
<file_sep><div class="wrap">
<h2><?php __('Comments Plus settings', 'wdcp');?></h2>
<?php if (WP_NETWORK_ADMIN) { ?>
<form action="settings.php" method="post">
<?php } else { ?>
<form action="options.php" method="post">
<?php } ?>
<?php settings_fields('wdcp'); ?>
<?php do_settings_sections('wdcp_options'); ?>
<p class="submit">
<input name="Submit" type="submit" class="button-primary" value="<?php esc_attr_e('Save Changes'); ?>" />
</p>
</form>
</div>
<script type="text/javascript">
(function ($) {
$(function () {
// ----- More help -----
$(".wdcp-more_help-fb").live('click', function () {
if ($(this).parents(".wdcp-setup-pointer").length) $(this).parents(".wdcp-setup-pointer").remove();
$("#contextual-help-link").click();
$("#tab-link-wdcp-fb-setup a").click();
$(window).scrollTop(0);
return false;
});
/**
* Handle tutorial resets.
*/
$(".wdcp-restart_tutorial").click(function () {
var $me = $(this);
// Change UI
$me.after(
'<img src="<?php echo WDCP_PLUGIN_URL;?>/img/loading.gif" />'
).remove();
// Do call
$.post(ajaxurl, {
"action": "wdcp_restart_tutorial"
}, function () {
window.location.reload();
});
return false;
});
<?php do_action('wdcp-plugin_settings-javascript_init'); ?>
});
})(jQuery);
</script>
<file_sep><?php
function register_these_scripts(){
wp_register_script('modernizr', get_template_directory_uri().'/library/js/modernizr.full.min.js', array(), '2.0', true);
wp_enqueue_script( 'modernizr' );
wp_dequeue_script('sitepress');
wp_deregister_script( 'jquery' );
wp_register_script( 'jquery', get_template_directory_uri().'/library/js/libs/jquery-1.7.1.min.js');
wp_enqueue_script( 'jquery' );
wp_register_script( 'scripts', get_template_directory_uri().'/library/js/scripts.js', array( 'modernizr' ));
wp_enqueue_script( 'scripts' );
wp_register_script( 'colorbox', get_template_directory_uri().'/library/js/jquery.colorbox-min.js', array('jquery'));
wp_enqueue_script('colorbox');
//default stylesheet
wp_register_style( 'webfontkit', get_template_directory_uri().'/library/webfontkit/stylesheet.css');
wp_enqueue_style( 'webfontkit' );
wp_register_style( 'normalize', get_template_directory_uri().'/library/css/normalize.css');
wp_enqueue_style( 'normalize' );
wp_register_style( 'colorbox-css', get_template_directory_uri().'/library/css/colorbox.css');
wp_enqueue_style('colorbox-css');
wp_register_script('razor-common', get_template_directory_uri().'/library/js/razor-common.js', array(), '1.1');
wp_enqueue_script( 'razor-common' );
wp_register_script('cookie', get_template_directory_uri().'/library/js/jquery.cookie.js', array('jquery'), '');
wp_enqueue_script( 'cookie' );
//for scripts that are needed in wp-admin
if( !is_admin()){
//NextGEN Gallery
wp_dequeue_script( 'thickbox' );
wp_dequeue_style( 'thickbox' );
wp_dequeue_script( 'ngg-slideshow' );
wp_dequeue_script( 'shutter' );
wp_dequeue_style( 'NextGEN' );
wp_dequeue_style( 'shutter' );
//Login with Ajax
wp_dequeue_script( 'login-with-ajax' );
wp_dequeue_style( 'login-with-ajax' );
/*
Comments Plus Plugin v 1.42
Feast hacked the plugin files to make dequeueing work. The plug was use wp_print_styles, which is bad form.
line 62+ /plugins/comments-plus/lib/class_wdcp_public_pages.php
*/
wp_dequeue_script( 'wdcp_comments' );
wp_dequeue_script( 'wdcp_twitter' );
wp_dequeue_script( 'wdcp_facebook' );
wp_dequeue_script( 'wdcp_google' );
wp_dequeue_script( 'facebook-all' );
wp_dequeue_script( 'twitter-anywhere' );
wp_dequeue_script( 'wdcp-sd-discussion' );
wp_dequeue_style( 'wdcp_comments' );
wp_dequeue_style( 'wdcp_comments-specific' );
wp_dequeue_style( 'wdcp-cct_theme' );
wp_dequeue_style( 'wdcp-sd-discussion' );
wp_dequeue_style( 'wdcp_comments-css' );
wp_dequeue_style( 'wdcp_comments-specific-css' );
}
if ( is_rtl() ) {
wp_enqueue_style( 'style-rtl', get_template_directory_uri().'/library/css/rtl.css' );
}
//conditional loading onto page template
global $post;
$post_type = get_post_type( $post );
if (is_front_page()) {
wp_register_script('homepage-js', get_bloginfo('stylesheet_directory').'/library/js/razor-homepage.js', array('jquery'));
wp_enqueue_script('homepage-js');
wp_register_style( 'homepage-css', get_template_directory_uri().'/library/css/homepage.css');
wp_enqueue_style( 'homepage-css' );
}
if (is_single() && $post_type != 'products' && $post_type != 'recalls' ) {
//NextGEN Gallerywp_enqueue_style('NextGEN');
wp_enqueue_script('thickbox');
wp_enqueue_style('thickbox');
wp_register_script('jquery-cycle', NGGALLERY_URLPATH .'js/jquery.cycle.all.min.js', array('jquery'), '2.88');
wp_enqueue_script('ngg-slideshow', NGGALLERY_URLPATH .'js/ngg.slideshow.min.js', array('jquery-cycle'), '1.05');
wp_enqueue_script( 'shutter' );
wp_enqueue_style( 'shutter' );
//Login with Ajax
wp_enqueue_script( 'login-with-ajax' );
wp_enqueue_style( 'login-with-ajax' );
/*
Comments Plus Plugin v 1.42
Feast hacked the plugin files to make dequeueing work. The plug was use wp_print_styles, which is bad form.
line 62+ /plugins/comments-plus/lib/class_wdcp_public_pages.php
*/
wp_enqueue_script( 'wdcp_comments' );
wp_enqueue_script( 'wdcp_twitter' );
wp_enqueue_script( 'wdcp_facebook' );
wp_enqueue_script( 'wdcp_google' );
wp_enqueue_script( 'facebook-all' );
wp_enqueue_script( 'twitter-anywhere' );
wp_enqueue_script( 'wdcp-sd-discussion' );
wp_enqueue_style( 'wdcp_comments' );
wp_enqueue_style( 'wdcp_comments-specific' );
wp_enqueue_style( 'wdcp-cct_theme' );
wp_enqueue_style( 'wdcp-sd-discussion' );
wp_enqueue_style( 'wdcp_comments-css' );
wp_enqueue_style( 'wdcp_comments-specific-css' );
}
if (is_single() && $post_type == 'products') {
//wp_enqueue_style('NextGEN');
//wp_register_script('jquery-cycle', NGGALLERY_URLPATH .'js/jquery.cycle.all.min.js', array('jquery'), '2.88');
//wp_enqueue_script('ngg-slideshow', NGGALLERY_URLPATH .'js/ngg.slideshow.min.js', array('jquery-cycle'), '1.05');
wp_enqueue_script('jquery-easing', get_template_directory_uri().'/library/js/jquery-ui-1.8.2-easing-min.js', array('jquery'), '1.8.2', false);
wp_enqueue_script('colorbox');
wp_enqueue_style( 'colorbox-css' );
//wp_enqueue_script('youtube-feed-manager', get_template_directory_uri().'/library/js/razor-youtube-feed-manager.js', array(), '');
wp_enqueue_script('product-page-js', get_template_directory_uri().'/library/js/razor-product-page.js', array(), '');
wp_enqueue_style('product-page-css', get_template_directory_uri().'/library/css/product-page.css');
wp_enqueue_script( 'razor_voter', get_bloginfo('stylesheet_directory').'/library/js/razor-voter.js', array('jquery'), '' );
wp_localize_script( 'razor_voter', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
}
if (is_single() && $post_type == 'recalls') {
//wp_enqueue_script( 'httpclient', get_bloginfo('stylesheet_directory').'/library/js/HttpClient.js', array('jquery'), '' );
//wp_enqueue_script( 'submitform', get_bloginfo('stylesheet_directory').'/library/js/submitform.js', array('jquery'), '' );
}
if(is_page_template('page-service-locator.php')){
//wp_enqueue_script('jquery-easing', get_template_directory_uri().'/library/js/jquery-ui-1.8.2-easing-min.js', array('jquery'), '1.8.2', false);
wp_register_script( 'black-white', get_template_directory_uri().'/library/js/BlackAndWhite.js', array('jquery'));
wp_enqueue_script( 'black-white' );
}
if(is_page_template('page-service-locator.php') || is_page_template('page-where-to-buy.php')){
//wp_register_script( 'locator-map', get_template_directory_uri().'/library/js/razor-locator-map.js', array('jquery'), '', true);
//wp_enqueue_script( 'locator-map' );
wp_register_style( 'locator-map-css', get_template_directory_uri().'/library/css/locator-map.css');
wp_enqueue_style( 'locator-map-css' );
}
}
add_action('wp_enqueue_scripts', 'register_these_scripts');
?><file_sep><?php
/*
Plugin Name: Facebook Featured post image
Description: Forces featured image to always show next to the posts on Facebook instead of relying on defaults. Also allows you to choose the image(s) used when there is no featured image available.
Plugin URI: http://premium.wpmudev.org/project/comments-plus
Version: 1.0
Author: <NAME> (Incsub)
*/
class Wdcp_Ffpi_AdminPages {
private $_data;
private function __construct () {
$this->_data = new Wdcp_Options;
}
public static function serve () {
$me = new Wdcp_Ffpi_AdminPages;
$me->_add_hooks();
}
private function _add_hooks () {
add_action('wdcp-options-plugins_options', array($this, 'register_settings'));
add_filter('wdcp-post_to_facebook-data', array($this, 'process_data'), 10, 2);
}
function process_data ($data, $post_id) {
$post_id = (int)$post_id;
if (!$data || !$post_id) return $data;
$forced_img = $this->_data->get_option('ffpi_forced_image');
if ($forced_img) {
$data['picture'] = $forced_img;
return $data;
}
$img = false;
$raw = wp_get_attachment_image_src(get_post_thumbnail_id($post_id));
$img = $raw ? @$raw[0] : false;
$img = $img ? $img : $this->_data->get_option('ffpi_fallback_image');
if ($img) $data['picture'] = $img;
return $data;
}
function register_settings () {
add_settings_section('wdcp_ffpi_settings', __('Facebook Featured Post Image', 'wdcp'), create_function('', ''), 'wdcp_options');
add_settings_field('wdcp_ffpi_image', __('Settings', 'wdcp'), array($this, 'create_settings_box'), 'wdcp_options', 'wdcp_ffpi_settings');
}
function create_settings_box () {
$forced_img = $this->_data->get_option('ffpi_forced_image');
$fallback_img = $this->_data->get_option('ffpi_fallback_image');
$checked = $featured_img ? 'checked="checked"' : '';
echo '' .
'<label for="wdcp-ffpi-fallback_image">' . __('Fallback image', 'wdcp') . ':</label>' .
"<input type='text' name='wdcp_options[ffpi_fallback_image]' class='widefat' id='wdcp-ffpi-fallback_image' value='{$fallback_img}' />" .
'<div><small>' . __('By default, we will attempt to use post featured image for Facebook publishing.', 'wdcp') . '</small></div>' .
'<div><small>' . __('If that fails, this is the image that will be used instead. Please, use full URL to image (e.g. <code>http://example.com/images/example.jpg</code>).', 'wdcp') . '</small></div>' .
'';
echo '<p><strong>' . __('…or…', 'wdcp') . '</strong></p>';
echo '' .
'<label for="wdcp-ffpi-forced_image">' . __('Always use this image', 'wdcp') . ':</label>' .
"<input type='text' name='wdcp_options[ffpi_forced_image]' id='wdcp-ffpi-forced_image' class='widefat' value='{$forced_img}' />" .
'<div><small>' . __('Please, use full URL to image (e.g. <code>http://example.com/images/example.jpg</code>). If set, this image will <b>always</b> be used.', 'wdcp') . '</small></div>' .
'';
}
}
if (is_admin()) Wdcp_Ffpi_AdminPages::serve();<file_sep><?php
/**
* Handles rendering of form elements for plugin Options page.
*/
class Wdcp_AdminFormRenderer {
var $_opts;
function Wdcp_AdminFormRenderer () { $this->__construct(); }
function __construct () {
$this->_opts = WP_NETWORK_ADMIN ? get_site_option('wdcp_options') : get_option('wdcp_options');
}
function _get_option ($name) {
return @$this->_opts[$name];
}
function _create_text_box ($name, $value) {
return "<input type='text' class='widefat' name='wdcp_options[{$name}]' id='{$name}' value='{$value}' />";
}
function _create_small_text_box ($name, $value) {
return "<input type='text' name='wdcp_options[{$name}]' id='{$name}' size='3' value='{$value}' />";
}
function _create_checkbox ($name, $value) {
return "<input type='hidden' name='wdcp_options[{$name}]' value='0' />" .
"<input type='checkbox' name='wdcp_options[{$name}]' id='{$name}' value='1' " . ($value ? 'checked="checked" ' : '') . " /> ";
}
function create_facebook_app_box () {
$site_opts = get_site_option('wdcp_options');
$has_creds = WP_NETWORK_ADMIN ? false : $site_opts['fb_network_only'];
if (!$has_creds) {
printf(__(
'<p><b>You must make a Facebook Application to start using Comments Plus.</b></p>' .
'<p>Before we begin, you need to <a target="_blank" href="https://developers.facebook.com/apps">create a Facebook Application</a>.</p>' .
'<p>To do so, follow these steps:</p>' .
'<ol>' .
'<li><a target="_blank" href="https://developers.facebook.com/apps">Create your application</a></li>' .
'<li>Look for <strong>Site URL</strong> field in the <em>Website</em> tab and enter your site URL in this field: <code>%s</code></li>' .
'<li>After this, go to the <a target="_blank" href="https://developers.facebook.com/apps">Facebook Application List page</a> and select your newly created application</li>' .
'<li>Copy the values from these fields: <strong>App ID</strong>/<strong>API key</strong>, and <strong>Application Secret</strong>, and enter them here:</li>' .
'</ol>',
'wdcp'),
get_bloginfo('siteurl')
);
echo '<label for="fb_app_id">' . __('App ID/API key', 'wdcp') . '</label> ' .
$this->_create_text_box('fb_app_id', $this->_get_option('fb_app_id')) .
'<br />';
echo '<label for="fb_app_secret">' . __('App Secret', 'wdcp') . '</label> ' .
$this->_create_text_box('fb_app_secret', $this->_get_option('fb_app_secret')) .
'<br />';
echo '<p><a href="#wdcp-more_help-fb" class="wdcp-more_help-fb">' . __('More help', 'wdcp') . '</a></p>';
} else {
_e('<p><i>Your Network Admin already set this up for you</i></p>', 'wdcp');
}
if (WP_NETWORK_ADMIN) {
echo ''.
$this->_create_checkbox('fb_network_only', $this->_get_option('fb_network_only')) .
' <label for="fb_network_only">' . __('I want to use this app on all subsites too', 'wdcp') . '</label>' .
'<div><small>' . __('Please, do <b>NOT</b> check this option if any of your sites use domain mapping.', 'wdcp') . '</small></div>' .
'<br />';
}
}
function create_skip_facebook_init_box () {
echo
$this->_create_checkbox('fb_skip_init', $this->_get_option('fb_skip_init')) .
'<label for="fb_skip_init">' . __('Pages on my website already use javascript from Facebook', 'wdcp') . '</label> ' .
"";
echo "<p><small>" . __('If you already use a plugin or custom script to interact with Facebook, check this option', 'wdcp') . '</small></p>';
}
function create_twitter_app_box () {
$site_opts = get_site_option('wdcp_options');
$has_creds = WP_NETWORK_ADMIN ? false : $site_opts['tw_network_only'];
if (!$has_creds) {
printf(__(
'<p><b>You must make a Twitter Application to start using Comments Plus.</b></p>' .
'<p>Before we begin, you need to <a target="_blank" href="https://dev.twitter.com/apps/new">create a Twitter Application</a>.</p>' .
'<p>To do so, follow these steps:</p>' .
'<ol>' .
'<li><a target="_blank" href="https://dev.twitter.com/apps/new">Create your application</a></li>' .
'<li>Look for <strong>Callback URL</strong> field and enter your site URL in this field: <code>%s</code></li>' .
'<li>Make sure you enable Read & Write access level</li>' .
'<li>After this, go to the <a target="_blank" href="https://dev.twitter.com/apps">Twitter Application List page</a> and select your newly created application</li>' .
'<li>Copy the values from these fields: <strong>Consumer Key</strong> and <strong>Consumer Secret</strong>, and enter them here:</li>' .
'</ol>',
'wdcp'),
get_bloginfo('siteurl')
);
echo '<label for="tw_api_key">' . __('Consumer key', 'wdcp') . '</label> ' .
$this->_create_text_box('tw_api_key', $this->_get_option('tw_api_key')) .
'<br />';
echo '<label for="tw_app_secret">' . __('Consumer secret', 'wdcp') . '</label> ' .
$this->_create_text_box('tw_app_secret', $this->_get_option('tw_app_secret')) .
'<br />';
} else {
_e('<p><i>Your Network Admin already set this up for you</i></p>', 'wdcp');
}
if (WP_NETWORK_ADMIN) {
echo ''.
$this->_create_checkbox('tw_network_only', $this->_get_option('tw_network_only')) .
' <label for="tw_network_only">' . __('I want to use this app on all subsites too', 'wdcp') . '</label>' .
'<div><small>' . __('Please, do <b>NOT</b> check this option if any of your sites use domain mapping.', 'wdcp') . '</small></div>' .
'<br />';
}
}
function create_skip_twitter_init_box () {
echo
$this->_create_checkbox('tw_skip_init', $this->_get_option('tw_skip_init')) .
'<label for="tw_skip_init">' . __('Pages on my website already use javascript from Twitter', 'wdcp') . '</label> ' .
"";
echo "<p><small>" . __('If you already use a plugin or custom script to interact with Twitter, check this option', 'wdcp') . '</small></p>';
}
function create_hooks_section () {
_e(
"<p>If you do not see Comments Plus on your pages, it is likely that your theme doesn't use the hooks we need to display our interface.</p><p>It's not a problem, though - here you can specify the hooks your theme does use.</p>",
'wdcp');
}
function create_start_hook_box () {
$value = $this->_get_option('begin_injection_hook');
$value = $value ? $value : 'comment_form_before';
echo $this->_create_text_box('begin_injection_hook', $value);
echo '<div><small>' . __('This is the hook that starts your comments form interface. By default, we\'re using <code>comment_form_before</code>. To reset to default, delete all contents of this field and save changes.', 'wdcp') . '</small></div>';
}
function create_end_hook_box () {
$value = $this->_get_option('finish_injection_hook');
$value = $value ? $value : 'comment_form_after';
echo $this->_create_text_box('finish_injection_hook', $value);
echo '<div><small>' . __('This is the hook that ends your comments form interface. By default, we\'re using <code>comment_form_after</code>. To reset to default, delete all contents of this field and save changes.', 'wdcp') . '</small></div>';
}
function create_wp_icon_box () {
echo '<label for="wp_icon">' . __('Icon URL:', 'wdcp') . '</label>' .
$this->_create_text_box('wp_icon', $this->_get_option('wp_icon')) .
"";
echo '<div><small>' . __('Full URL of the icon you wish to use for your WP comments instead of the default one', 'wdcp') . '</small></div>';
echo '<div><small>' . __('For best results, use a 16x16px image.', 'wdcp') . '</small></div>';
echo
$this->_create_checkbox('show_instructions', $this->_get_option('show_instructions')) .
'<label for="show_instructions">' . __('Attempt to show or hide allowed tags text for WordPress comments', 'wdcp') . '</label> ' .
"";
}
function create_skip_services_box () {
$services = array (
'wordpress' => __('WordPress', 'wdcp'),
'twitter' => __('Twitter', 'wdcp'),
'facebook' => __('Facebook', 'wdcp'),
'google' => __('Google', 'wdcp'),
);
$skips = $this->_get_option('skip_services');
$skips = $skips ? $skips : array();
foreach ($services as $key=>$label) {
$checked = in_array($key, $skips) ? 'checked="checked"' : '';
echo "" .
"<input type='checkbox' name='wdcp_options[skip_services][]' id='wdcp-skip-{$key}' value='$key' {$checked} />" .
" " .
"<label for='wdcp-skip-{$key}'>{$label}</label>" .
"<br />" .
"";
}
echo '<br />';
echo
$this->_create_checkbox('stretch_tabs', $this->_get_option('stretch_tabs')) .
'<label for="stretch_tabs">' . __('Shrink or stretch provider selector tabs?', 'wdcp') . '</label> ' .
"";
echo '<br />';
echo
$this->_create_checkbox('dont_select_social_sharing', $this->_get_option('dont_select_social_sharing')) .
'<label for="dont_select_social_sharing">' . __('Don\'t pre-select social comments sharing', 'wdcp') . '</label> ' .
"";
}
function create_style_box () {
echo '' .
$this->_create_checkbox('skip_color_css', $this->_get_option('skip_color_css')) .
' ' .
'<label for="skip_color_css">' . __('Let my theme determine colors', 'wdcp') . '</label>' .
'<div><small>' . __('Use this option if your theme already has color definitions needed for Comments Plus in its\' stylesheets', 'wdcp') . '</small></div>' .
'';
}
function create_plugins_box () {
$all = Wdcp_PluginsHandler::get_all_plugins();
$active = Wdcp_PluginsHandler::get_active_plugins();
$sections = array('thead', 'tfoot');
echo "<table class='widefat'>";
foreach ($sections as $section) {
echo "<{$section}>";
echo '<tr>';
echo '<th width="30%">' . __('Add-on name', 'wdcp') . '</th>';
echo '<th>' . __('Add-on description', 'wdcp') . '</th>';
echo '</tr>';
echo "</{$section}>";
}
echo "<tbody>";
foreach ($all as $plugin) {
$plugin_data = Wdcp_PluginsHandler::get_plugin_info($plugin);
if (!@$plugin_data['Name']) continue; // Require the name
$is_active = in_array($plugin, $active);
echo "<tr>";
echo "<td width='30%'>";
echo '<b id="' . esc_attr($plugin) . '">' . $plugin_data['Name'] . '</b>';
echo "<br />";
echo ($is_active
?
'<a href="#deactivate" class="wdcp_deactivate_plugin" wdcp:plugin_id="' . esc_attr($plugin) . '">' . __('Deactivate', 'wdcp') . '</a>'
:
'<a href="#activate" class="wdcp_activate_plugin" wdcp:plugin_id="' . esc_attr($plugin) . '">' . __('Activate', 'wdcp') . '</a>'
);
echo "</td>";
echo '<td>' .
$plugin_data['Description'] .
'<br />' .
sprintf(__('Version %s', 'wdcp'), $plugin_data['Version']) .
' | ' .
sprintf(__('by %s', 'wdcp'), '<a href="' . $plugin_data['Plugin URI'] . '">' . $plugin_data['Author'] . '</a>') .
'</td>';
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
echo <<<EOWdcpPluginJs
<script type="text/javascript">
(function ($) {
$(function () {
$(".wdcp_activate_plugin").click(function () {
var me = $(this);
var plugin_id = me.attr("wdcp:plugin_id");
$.post(ajaxurl, {"action": "wdcp_activate_plugin", "plugin": plugin_id}, function (data) {
window.location = window.location;
});
return false;
});
$(".wdcp_deactivate_plugin").click(function () {
var me = $(this);
var plugin_id = me.attr("wdcp:plugin_id");
$.post(ajaxurl, {"action": "wdcp_deactivate_plugin", "plugin": plugin_id}, function (data) {
window.location = window.location;
});
return false;
});
});
})(jQuery);
</script>
EOWdcpPluginJs;
}
}<file_sep><div id="cse" style="width: 100%;"><?php _e("Loading", "bonestheme"); ?></div>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script src="<?php echo get_template_directory_uri(); ?>/library/js/google-cse.js" type="text/javascript"></script>
<script type="text/javascript">
google.load('search', '1', {language : 'en', style : google.loader.themes.MINIMALIST});
google.setOnLoadCallback(function() {
var customSearchControl = new google.search.CustomSearchControl('006825650897633400644:my_4436dxeq');
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
var options = new google.search.DrawOptions();
options.setAutoComplete(true);
customSearchControl.draw('cse', options);
customSearchControl.execute('<?php
// Reads the URL to find a keyword then searches for that keyword
// For example, http://www.website.com/404 will run a Google custom search for "404"
$url = $_SERVER["REQUEST_URI"];
$path_parts = pathinfo( $url );
$extension = "." . $path_parts[ "extension" ];
$page = basename( $url, $extension );
echo $page;
?>');
}, true);
</script><file_sep><?php
/**
* Contextual help implementation.
*/
class Wdcp_ContextualHelp {
private $_help;
private $_pages = array(
'list', 'edit', 'get_started', 'settings',
);
private $_sidebar = '';
private function __construct () {
if (!class_exists('WpmuDev_ContextualHelp')) require_once WDCP_PLUGIN_BASE_DIR . '/lib/external/class_wd_contextual_help.php';
$this->_help = new WpmuDev_ContextualHelp();
$this->_set_up_sidebar();
}
public static function serve () {
$me = new Wdcp_ContextualHelp;
$me->_initialize();
}
private function _set_up_sidebar () {
$this->_sidebar = '<h4>' . __('Comments Plus', 'wdcp') . '</h4>';
if (defined('WPMUDEV_REMOVE_BRANDING') && constant('WPMUDEV_REMOVE_BRANDING')) {
$this->_sidebar .= '<p>' . __('The Comments Plus Plugin effectively allows you to combine comments from Facebook, Twitter and Google services with your standard WordPress comments, rather than picking just one.', 'wdcp') . '</p>';
} else {
$this->_sidebar .= '<ul>' .
'<li><a href="http://premium.wpmudev.org/project/comments-plus" target="_blank">' . __('Project page', 'wdcp') . '</a></li>' .
'<li><a href="http://premium.wpmudev.org/project/comments-plus/installation/" target="_blank">' . __('Installation and instructions page', 'wdcp') . '</a></li>' .
'<li><a href="http://premium.wpmudev.org/forums/tags/comments-plus" target="_blank">' . __('Support forum', 'wdcp') . '</a></li>' .
'</ul>' .
'';
}
}
private function _initialize () {
foreach ($this->_pages as $page) {
$method = "_add_{$page}_page_help";
if (method_exists($this, $method)) $this->$method();
}
$this->_help->initialize();
}
private function _add_settings_page_help () {
$help_items = array(
array(
'id' => 'wdcp-intro',
'title' => __('Intro', 'wdcp'),
'content' => '<p>' . __('This is where you configure <b>Comments Plus</b> plugin for your site', 'wdcp') . '</p>',
),
array(
'id' => 'wdcp-general',
'title' => __('General Info', 'wdcp'),
'content' => '' .
'<p>' . __('The Comments Plus Plugin effectively allows you to combine comments from Facebook, Twitter and Google services with your standard WordPress comments, rather than picking just one', 'wdcp') . '</p>' .
''
),
array(
'id' => 'wdcp-fb-setup',
'title' => __('Setting Facebook API settings', 'wdcp'),
'content' => '' .
'<p>' . __('Follow these steps to set up <em>App ID/API key</em> and <em>App Secret</em> fields', 'wdcp') . '</p>' .
'<ol>' .
'<li>' . __('<a target="_blank" href="https://developers.facebook.com/apps">Create a Facebook Application</a>', 'wdcp') . '</li>' .
'<li>' . sprintf(__('Your Facebook App setup should look similar to this:<br /><img src="%s" />', 'wdcp'), WDCP_PLUGIN_URL . '/img/fb-setup.png') . '</li>' .
'</ol>' .
''
),
array(
'id' => 'wdcp-tutorial',
'title' => __('Tutorial', 'wdcp'),
'content' => '' .
'<p>' .
__('Tutorial dialogs will guide you through the important bits.', 'wdcp') .
'</p>' .
'<p><a href="#" class="wdcp-restart_tutorial">' . __('Restart the tutorial', 'wdcp') . '</a></p>',
),
);
$this->_help->add_page('settings_page_wdcp', $help_items, $this->_sidebar, true);
$this->_help->add_page('settings_page_wdcp-network', $help_items, $this->_sidebar, true);
}
}
<file_sep><?php
/*
Plugin Name: Mention me
Description: Adds a pre-configured Twitter username to all messages posted to Twitter. You can set up the username in plugin settings.
Plugin URI: http://premium.wpmudev.org/project/comments-plus
Version: 1.0
Author: <NAME> (Incsub)
*/
class Wdcp_Twmm_AdminPages {
private $_data;
private function __construct () {
$this->_data = new Wdcp_Options;
}
public static function serve () {
$me = new Wdcp_Twmm_AdminPages;
$me->_add_hooks();
}
private function _add_hooks () {
add_action('wdcp-options-plugins_options', array($this, 'register_settings'));
add_filter('wdcp-remote_post_data-twitter', array($this, 'process_data'));
}
function process_data ($data) {
$username = $this->_data->get_option('twmm_username');
if (!$username) return $data;
$username = preg_match('/^@/', $username) ? $username : "@{$username}";
$comment = $username . ' ' . $data['status'];
$data = array(
'status' => substr($comment, 0, 140),
);
return $data;
}
function register_settings () {
add_settings_section('wdcp_twmm_settings', __('Mention me', 'wdcp'), create_function('', ''), 'wdcp_options');
add_settings_field('wdcp_twmm_username', __('Twitter username', 'wdcp'), array($this, 'create_username_box'), 'wdcp_options', 'wdcp_twmm_settings');
}
function create_username_box () {
$username = esc_attr($this->_data->get_option('twmm_username'));
echo "@<input type='text' name='wdcp_options[twmm_username]' size='16' value='{$username}' />";
echo '<div><small>' . __('This is the Twitter username that will be prepended to all outgoing Tweets.', 'wdcp') . '</small></div>';
}
}
if (is_admin()) Wdcp_Twmm_AdminPages::serve();
<file_sep><?php
/*
Plugin Name: Short URLs
Description: Integrates an URL shortening service call to your outgoing URLs.
Plugin URI: http://premium.wpmudev.org/project/comments-plus
Version: 1.0
Author: <NAME> (Incsub)
*/
class Wdcp_Ussc_AdminPages {
private $_data;
private $_processor;
private $_services = array(
'facebook' => 'Facebook',
'twitter' => 'Twitter',
);
private function __construct () {
$this->_data = new Wdcp_Options;
}
public static function serve () {
$me = new Wdcp_Ussc_AdminPages;
$me->_add_hooks();
}
private function _add_hooks () {
add_action('wdcp-options-plugins_options', array($this, 'register_settings'));
$processor_class = $this->_data->get_option('ussc_process_with');
if (!class_exists($processor_class)) return false; // Stop binding right now, nothing to do.
if (!is_subclass_of($processor_class, 'Wdcp_Ussc_BaseProvider')) return false; // o.0
$this->_processor = new $processor_class;
if ($this->_data->get_option('ussc_no_cache')) {
$this->_processor->set_no_caching();
}
$services = $this->_get_services();
foreach ($this->_services as $service => $label) {
if (!in_array($service, $services)) continue;
add_filter("wdcp-remote_post_data-{$service}-post_url", array($this, 'process_data'), 10, 2);
}
}
function process_data ($original, $post_id) {
$url = $this->_processor->get_short_url($original, $post_id);
return $url ? $url : $original;
}
function register_settings () {
add_settings_section('wdcp_ussc_settings', __('URL shortening', 'wdcp'), create_function('', ''), 'wdcp_options');
add_settings_field('wdcp_ussc_use_on_service', __('Process URLs posted to', 'wdcp'), array($this, 'create_use_on_box'), 'wdcp_options', 'wdcp_ussc_settings');
add_settings_field('wdcp_ussc_process_with_service', __('Process with', 'wdcp'), array($this, 'create_process_with_box'), 'wdcp_options', 'wdcp_ussc_settings');
}
function create_use_on_box () {
$sel = $this->_get_services();
foreach ($this->_services as $service => $label) {
$checked = in_array($service, $sel) ? 'checked="checked"' : '';
echo "<input type='checkbox' name='wdcp_options[ussc_use_on][{$service}]' id='wdcp-ussc_use_on-{$service}' value='{$service}' {$checked} />" .
" " .
"<label for='wdcp-ussc_use_on-{$service}'>{$label}</label>" .
"<br />";
}
}
function create_process_with_box () {
$service = $this->_data->get_option('ussc_process_with');
$all_classes = get_declared_classes();
foreach ($all_classes as $class) {
if (!is_subclass_of($class, 'Wdcp_Ussc_BaseProvider')) continue;
$key = strtolower($class);
$label = call_user_func(array($class, 'get_name'));
$checked = ($service == $key) ? 'checked="checked"' : '';
echo "<input type='radio' name='wdcp_options[ussc_process_with]' id='wdcp-ussc_process_with-{$key}' value='{$key}' {$checked} />" .
" " .
"<label for='wdcp-ussc_process_with-{$key}'>{$label}</label>" .
"<br />";
}
// Caching
$cache = $this->_data->get_option('ussc_no_cache');
$checked = $cache ? 'checked="checked"' : '';
echo "<input type='hidden' name='wdcp_options[ussc_no_cache]' value='' />" .
"<input type='checkbox' name='wdcp_options[ussc_no_cache]' id='wdcp-ussc_no_cache' value='1' {$checked} />" .
" " .
"<label for='wdcp-ussc_no_cache'>" . __('Prevent shortened URL caching', 'wdcp') . "</label>";
echo '<p>' .
"<label for='wdcp-ussc_bitly_username'>" . __('Your bit.ly Username', 'wdcp') . "</label>" .
"<input type='text' class='widefat' name='wdcp_options[ussc_bitly_username]' id='wdcp-ussc_bitly_username' value='" . esc_attr($this->_data->get_option("ussc_bitly_username")) . "' />" .
"<br />" .
"<label for='wdcp-ussc_bitly_key'>" . __('Your bit.ly API Key', 'wdcp') . "</label>" .
"<input type='text' class='widefat' name='wdcp_options[ussc_bitly_key]' id='wdcp-ussc_bitly_key' value='" . esc_attr($this->_data->get_option("ussc_bitly_key")) . "' />" .
'<br />' . sprintf(__('Get your bit.ly API info <a href="%s">here</a>', 'wdcp'), 'http://bitly.com/a/your_api_key');
'</p>';
}
private function _get_services () {
$services = $this->_data->get_option('ussc_use_on');
return $services ? $services : array();
}
}
abstract class Wdcp_Ussc_BaseProvider {
protected $_http_args = array(
"method" => "GET",
"timeout" => 5,
"redirection" => 5,
"user-agent" => "wdcp-ussc",
"sslverify" => false,
);
private $_use_cache = true;
private $_cache_key = 'wdcp-ussc-short_url';
public function set_no_caching () {
$this->_use_cache = false;
}
public function parse_response ($body) { return $body; }
public function get_short_url ($url, $post_id) { return $this->_remote_request(urlencode($url), $post_id); }
public static function get_name () { throw new Exception('Child class needs to implement this'); }
abstract public function get_service_url ();
protected function _remote_request ($url, $post_id) {
// First, check cache
if ($this->_use_cache) {
$cached = get_post_meta($post_id, $this->_cache_key, true);
if ($cached) return $cached;
}
// No cache - request fresh url
$url = sprintf($this->get_service_url(), $url);
$page = wp_remote_request($url, $this->_http_args);
if(is_wp_error($page)) return false; // Request fail
if ((int)$page['response']['code'] != 200) return false; // Request fail
$short = $this->parse_response($page['body']);
// All good - update cache, and return
if ($this->_use_cache && $short) update_post_meta($post_id, $this->_cache_key, $short);
return $short;
}
}
class Wdcp_Ussc_IsGdProvider extends Wdcp_Ussc_BaseProvider {
public static function get_name () { return 'is.gd'; }
public function get_service_url () { return 'http://is.gd/create.php?format=simple&url=%s'; }
}
class Wdcp_Ussc_BitLyProvider extends Wdcp_Ussc_BaseProvider {
private $_data;
public function __construct () { $this->_data = new Wdcp_Options; }
public static function get_name () { return 'bit.ly'; }
public function get_service_url () {
return sprintf(
'http://api.bitly.com/v3/shorten?login=o_3f15m2diqp&apiKey=R_a35cd0f711f1fa44c6d39ecd48b571ac',
$this->_data->get_option('ussc_bitly_username'),
$this->_data->get_option('ussc_bitly_key')
) . '&longUrl=%s';
}
public function parse_response ($body) {
if (!$body) return false;
$resp = @json_decode($body, true);
if (200 != @$resp['status_code']) return false;
return @$resp['data']['url'];
}
}
if (is_admin()) Wdcp_Ussc_AdminPages::serve();
<file_sep><?php
class Wdcp_Model {
var $twitter;
var $facebook;
var $_facebook_user_cache = false;
var $_twitter_user_cache = false;
var $_google_user_cache = false;
function Wdcp_Model () { $this->__construct(); }
function __construct () {
if ($this->_load_dependencies()) {
if (!(defined('WDCP_FACEBOOK_SSL_CERTIFICATE') && WDCP_FACEBOOK_SSL_CERTIFICATE)) {
if (isset(Facebook::$CURL_OPTS)) {
Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYHOST] = 0;
Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYPEER] = 0;
}
}
$this->facebook = new Facebook(array(
'appId' => WDCP_APP_ID,
'secret' => WDCP_APP_SECRET,
'cookie' => true,
));
$this->twitter = new TwitterOAuth(WDCP_CONSUMER_KEY, WDCP_CONSUMER_SECRET);
$this->openid = new LightOpenID;
$this->_initialize();
} // else...
}
function _load_dependencies () {
if (!class_exists('TwitterOAuth')) require_once WDCP_PLUGIN_BASE_DIR . '/lib/external/twitter/twitteroauth.php';
if (!class_exists('Facebook')) require_once WDCP_PLUGIN_BASE_DIR . '/lib/external/facebook/facebook.php';
if (!class_exists('LightOpenID')) require_once WDCP_PLUGIN_BASE_DIR . '/lib/external/lightopenid/openid.php';
return (
class_exists('Facebook') &&
class_exists('TwitterOAuth') &&
class_exists('LightOpenID')
);
}
/**
* Initializes external API handlers
*
* @access private
*/
function _initialize () {
session_start();
// Facebook
try {
if ($this->facebook->getUser()) {
$_SESSION['wdcp_facebook_user_cache'] = isset($_SESSION['wdcp_facebook_user_cache'])
? $_SESSION['wdcp_facebook_user_cache'] : $this->facebook->api('/me');
$this->_facebook_user_cache = $_SESSION['wdcp_facebook_user_cache'];
}
} catch (Exception $e) {}
// Google
$this->openid->identity = 'https://www.google.com/accounts/o8/id';
$this->openid->required = array('namePerson/first', 'namePerson/last', 'contact/email');
if (!empty($_REQUEST['openid_ns'])) {
$cache = $this->openid->getAttributes();
if (isset($cache['namePerson/first']) || isset($cache['namePerson/last']) || isset($cache['contact/email'])) {
$_SESSION['wdcp_google_user_cache'] = $cache;
}
}
$this->_google_user_cache = $_SESSION['wdcp_google_user_cache'];
// Twitter
if (isset($_REQUEST['oauth_verifier']) && !isset($_SESSION['wdcp_twitter_user_cache']['_done'])) {
$_SESSION['wdcp_twitter_user_cache']['token']['oauth_token'] = $_REQUEST['oauth_token'];
$verifier = $_REQUEST['oauth_verifier'];
$token = $_SESSION['wdcp_twitter_user_cache']['token'];
$this->twitter = new TwitterOAuth(WDCP_CONSUMER_KEY, WDCP_CONSUMER_SECRET, $token['oauth_token'], $token['oauth_token_secret']);
$_SESSION['wdcp_twitter_user_cache']['access_token'] = $this->twitter->getAccessToken($verifier);
$_SESSION['wdcp_twitter_user_cache']['verifier'] = $verifier;
$response = $this->twitter->get('account/verify_credentials');
if ($response->id_str) {
$_SESSION['wdcp_twitter_user_cache']['user'] = array (
'id' => $response->id_str,
'name' => $response->name,
'username' => $response->screen_name,
'url' => $response->url,
'image' => $response->profile_image_url,
);
$this->_twitter_user_cache = @$_SESSION['wdcp_twitter_user_cache']['user'];
}
$_SESSION['wdcp_twitter_user_cache']['_done'] = true;
} else if ($_SESSION['wdcp_twitter_user_cache']['access_token']) {
$token = $_SESSION['wdcp_twitter_user_cache']['access_token'];
$this->twitter = new TwitterOAuth(WDCP_CONSUMER_KEY, WDCP_CONSUMER_SECRET, $token['oauth_token'], $token['oauth_token_secret']);
$this->_twitter_user_cache = @$_SESSION['wdcp_twitter_user_cache']['user'];
}
}
function current_user_logged_in ($provider) {
$provider = esc_html(trim(strtolower($provider)));
switch ($provider) {
case "wordpress":
return is_user_logged_in();
case "facebook":
return $this->facebook->getUser() ? true : false;
case "twitter":
return isset($_SESSION['wdcp_twitter_user_cache']['access_token']) ? true : false;
case "google":
return isset($_SESSION['wdcp_google_user_cache']) ? true : false;
}
return false;
}
function current_user_id ($provider) {
$provider = esc_html(trim(strtolower($provider)));
switch ($provider) {
case "wordpress":
global $current_user;
return $current_user->ID;
case "facebook":
return @$this->facebook->getUser();
case "twitter":
return $this->_twitter_user_cache['id'];
case "google":
return $this->openid->identity;
}
return false;
}
function current_user_name ($provider) {
$provider = esc_html(trim(strtolower($provider)));
switch ($provider) {
case "wordpress":
global $current_user;
return $current_user->user_login;
case "facebook":
return @$this->_facebook_user_cache['name'];
case "twitter":
return $this->_twitter_user_cache['name'];
case "google":
return @$this->_google_user_cache['namePerson/first'] . ' ' . @$this->_google_user_cache['namePerson/last'];
}
return false;
}
function current_user_username ($provider) {
$provider = esc_html(trim(strtolower($provider)));
switch ($provider) {
case "wordpress":
global $current_user;
return $current_user->user_login;
case "facebook":
return @$this->_facebook_user_cache['email'];
case "twitter":
return $this->_twitter_user_cache['username'];
case "google":
return @$this->_google_user_cache['contact/email'];
}
return false;
}
function current_user_email ($provider) {
$provider = esc_html(trim(strtolower($provider)));
switch ($provider) {
case "wordpress":
global $current_user;
return $current_user->user_email;
case "facebook":
return @$this->_facebook_user_cache['email'];
case "twitter":
return '';
case "google":
return @$this->_google_user_cache['contact/email'];
}
}
function current_user_url ($provider) {
$provider = esc_html(trim(strtolower($provider)));
switch ($provider) {
case "wordpress":
return site_url();
case "facebook":
return 'http://www.facebook.com/profile.php?id=' . $this->current_user_id('facebook');
case "twitter":
return $this->_twitter_user_cache['url'];
}
return false;
}
function facebook_logout_user () {
$_SESSION['wdcp_facebook_user_cache'] = false;
$this->facebook->destroySession();
unset($_SESSION['wdcp_facebook_user_cache']);
}
function get_google_auth_url ($url) {
$this->openid->returnUrl = $url;
$this->openid->realm = WDCP_PROTOCOL . $_SERVER['HTTP_HOST'];
return $this->openid->authUrl();
}
function google_logout_user () {
$_SESSION['wdcp_google_user_cache'] = false;
unset($_SESSION['wdcp_google_user_cache']);
}
function twitter_avatar () {
return $this->_twitter_user_cache['image'];
}
function get_twitter_auth_url ($url) {
if (isset($_SESSION['wdcp_twitter_user_cache']['oauth_url'])) return $_SESSION['wdcp_twitter_user_cache']['oauth_url'];
$tw_token = $this->twitter->getRequestToken($url);
$tw_url = $this->twitter->getAuthorizeURL($tw_token['oauth_token']);
$_SESSION['wdcp_twitter_user_cache']['token'] = $tw_token;
$_SESSION['wdcp_twitter_user_cache']['oauth_url'] = $tw_url;
return $tw_url;
}
function twitter_logout_user () {
$_SESSION['wdcp_twitter_user_cache'] = false;
unset($_SESSION['wdcp_twitter_user_cache']);
}
/*** Posting ***/
function post_to_facebook ($data) {
$fb_uid = $this->current_user_id('facebook');
$post_id = (int)$_POST['post_id'];
$post = get_post($post_id);
$data['comment'] = stripslashes($data['comment']); // Forcing stripslashes
$send = apply_filters('wdcp-post_to_facebook-data', array(
'caption' => substr($data['comment'], 0, 999),
'message' => substr($data['comment'], 0, 999),
'link' => apply_filters('wdcp-remote_post_data-post_url', apply_filters('wdcp-remote_post_data-facebook-post_url', get_permalink($post_id), $post_id), $post_id),
'name' => $post->post_title,
'description' => get_option('blogdescription'),
), $post_id);
try {
$ret = $this->facebook->api('/' . $fb_uid . '/feed/', 'POST', $send);
} catch (Exception $e) {
return false;
}
return $ret; // $ret['id']
}
function post_to_twitter ($data) {
$post_id = (int)$data['post_id'];
$link = apply_filters('wdcp-remote_post_data-post_url', apply_filters('wdcp-remote_post_data-twitter-post_url', get_permalink($post_id), $post_id), $post_id);
$send = apply_filters('wdcp-remote_post_data-twitter', array(
'status' => substr($link . ' ' . $data['comment'], 0, 140),
), $data);
try {
$ret = $this->twitter->post('statuses/update', $send);
} catch (Exception $e) {
return false;
}
return $ret; // $ret->id_str
}
}
|
65489aa7add1f7dc406e637a6fb7dcfc369dce61
|
[
"JavaScript",
"PHP"
] | 24 |
PHP
|
cgaubuchon/private-pooch
|
bd385c793e94eb60c6dbf027ec42023f72a34fe4
|
20a02cb8c97a539c379cd51ece9d1ff08eea44e9
|
refs/heads/master
|
<repo_name>gulpjs/docs<file_sep>/website/siteConfig.js
const siteConfig = {
disableHeaderTitle: true,
disableHeaderTagline: true,
url: 'https://gulpjs.com/docs/',
baseUrl: '/',
organizationName: 'gulpjs',
projectName: 'docs',
customDocsPath: 'converted-docs',
headerLinks: [
{href: './', label: 'Docs'},
{href: 'https://gulpjs.com/plugins', label: 'Plugins'},
{href: 'https://twitter.com/gulpjs', label: 'Twitter'},
{href: 'https://github.com/gulpjs/gulp/blob/master/CONTRIBUTING.md', label: 'Contribute'},
],
headerIcon: 'img/gulp.svg',
footerIcon: 'img/gulp.svg',
favicon: 'img/favicon.png',
colors: {
primaryColor: '#cf4647',
secondaryColor: '#cf4647',
},
copyright: `Copyright © ${new Date().getFullYear()} GulpJS`,
highlight: {
theme: 'tomorrow-night',
},
scripts: ['https://buttons.github.io/buttons.js'],
repoUrl: 'https://github.com/gulpjs/gulp',
};
module.exports = siteConfig;
<file_sep>/gulpfile.js
'use strict';
// This file is only for generating the docs
// No need to use any of this if working on the main website
const { src, dest, series } = require('gulp');
const path = require('path');
const pump = require('pump');
const through2 = require('through2');
const frontMatter = require('gray-matter');
const download = require('github-download-directory');
// Exports for task registration
exports.default = series(fetchDocs, convertComments);
const owner = 'gulpjs';
const repo = 'gulp';
const directory = 'docs';
const outDirectory = 'converted-docs';
const fmOptions = {
delimiters: ['<!-- front-matter', '-->']
};
function fetchDocs() {
return download(owner, repo, directory, { sha: "wip-docs" });
}
function convertComments(cb) {
pump([
// Only process markdown files in the directory we fetched
src('**/*.md', { cwd: directory }),
pluginless(convertToDocusaurus),
// Overwrite the markdown files we fetched
dest(outDirectory)
], cb)
}
/* utils */
function convertToDocusaurus(file) {
var config = frontMatter(file.contents, fmOptions);
// This fixes the problem with more than 1 file being named README.md
if (config.data.id) {
file.stem = config.data.id;
} else {
console.error(`File missing front-matter. Path: ${file.path}`);
return; // Filter out any file without frontmatter
}
file.base = path.dirname(file.path);
file.contents = Buffer.from(config.stringify());
return file;
}
function pluginless(fn) {
return through2.obj(handler);
function handler(file, _, cb) {
try {
cb(null, fn(file));
} catch(err) {
cb(err);
}
}
}
|
7b9634e8bf42e1497038ad34d6264e86027dcc52
|
[
"JavaScript"
] | 2 |
JavaScript
|
gulpjs/docs
|
d1beb2e2290ce13965381a501aa750062a7ca565
|
ccfa7f1337facb2f663165bdabd578c117a59c0c
|
refs/heads/master
|
<file_sep>package persistence
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
func init() {
createTable()
}
func connect() *sql.DB {
user, password, host, database := "admin", "root", "127.0.0.1:32768", "dev_logger"
db, err := sql.Open("mysql", user+":"+password+"@tcp("+host+")/"+database+"?parseTime=true")
checkError(err)
return db
}
func createTable() {
db := connect()
defer db.Close()
stm, err := db.Prepare(`
CREATE TABLE IF NOT EXISTS blackjacks(
id INT AUTO_INCREMENT PRIMARY KEY,
dealer_hand TEXT,
player_hand TEXT,
dealer_score INT,
player_score INT,
bet INT,
credit INT,
result INT,
created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
`)
checkError(err)
_, err = stm.Exec()
checkError(err)
}
func insert(bj Blackjack) int {
db := connect()
defer db.Close()
stm, err := db.Prepare(`
INSERT INTO blackjacks (
dealer_hand,
player_hand,
dealer_score,
player_score,
bet,
credit,
result
) VALUES (
?, ?, ?, ?, ?, ?, ?
)
`)
checkError(err)
res, err := stm.Exec(bj.dealerHand, bj.playerHand, bj.dealerScore, bj.playerScore, bj.bet, bj.credit, bj.result)
checkError(err)
id, err := res.LastInsertId()
checkError(err)
return int(id)
}
func selectId() {
db := connect()
defer db.Close()
}
<file_sep>package blackjack
import (
"fmt"
"log"
"strconv"
)
type Ai interface {
Bet(gs *GameState)
Play(gs *GameState)
Result(gs *GameState)
}
type HumanAi struct{}
func (ai *HumanAi) Bet(gs *GameState) {
var input string
fmt.Println("\nCredit left: " + strconv.FormatInt(int64(gs.Credit), 10))
fmt.Println("How much do you want to bet?")
fmt.Scanf("%s\n", &input)
amount, err := strconv.Atoi(input)
if err != nil {
log.Panic(err)
}
Bet(gs, amount)
}
func (ai *HumanAi) Play(gs *GameState) {
var input string
fmt.Println("\nPlayer: " + gs.Player.ShowFinal())
fmt.Println("Score: " + strconv.FormatInt(int64(gs.Player.Score()), 10))
fmt.Println("Dealer: " + gs.Dealer.ShowPartial())
fmt.Println("Score: " + strconv.FormatInt(int64(gs.Dealer.Score()), 10))
fmt.Println("What will you do? (h)it, (s)tand or (d)ouble")
fmt.Scanf("%s\n", &input)
switch input {
case "h":
MoveHit(gs)
case "s":
MoveStand(gs)
case "d":
MoveDouble(gs)
}
}
func (ai *HumanAi) Result(gs *GameState) {
var result string
switch {
case gs.Player.Score() == 21:
result = "You won with Blackjack"
case gs.Player.Score() > 21:
result = "You busted"
case gs.Dealer.Score() > 21:
result = "Dealer busted"
case gs.Player.Score() == gs.Dealer.Score():
result = "Draw"
case gs.Player.Score() > gs.Dealer.Score():
result = "You won"
case gs.Player.Score() < gs.Dealer.Score():
result = "You lost"
}
fmt.Println("\nPlayer cards: " + fmt.Sprintf("%v", gs.Player.ShowFinal()))
fmt.Println("Player score: " + fmt.Sprintf("%v", gs.Player.Score()))
fmt.Println("Dealer cards: " + fmt.Sprintf("%v", gs.Dealer.ShowFinal()))
fmt.Println("Dealer score: " + fmt.Sprintf("%v", gs.Dealer.Score()))
fmt.Println(result)
}
type ComputerAi struct {
seen int
score int
}
func (ai *ComputerAi) Bet(gs *GameState) {
if ai.seen >= 52 {
ai.seen = 0
ai.score = 0
}
switch {
case ai.score > 4:
Bet(gs, 1000)
case ai.score < 0:
Bet(gs, 10)
default:
Bet(gs, 100)
}
// fmt.Println(ai.seen)
}
func (ai *ComputerAi) Play(gs *GameState) {
// if gs.Player.Score() < 16 || (gs.Player.Score() == 17 && gs.Player.MinScore() != 17) {
// MoveHit(gs)
// } else {
// MoveStand(gs)
// }
if gs.Player.Score() < 16 {
MoveDouble(gs)
} else {
MoveStand(gs)
}
}
func (ai *ComputerAi) Result(gs *GameState) {
for _, card := range gs.Dealer.GetCards() {
switch {
case card.Rank < 6:
ai.score++
case card.Rank <= 9:
case card.Rank > 9:
ai.score--
}
ai.seen++
}
for _, card1 := range gs.Player.GetCards() {
switch {
case card1.Rank < 6:
ai.score++
case card1.Rank <= 9:
case card1.Rank > 9:
ai.score--
}
ai.seen++
}
}
<file_sep>package blackjack
import (
"deckofcards/deck"
"go-blackjack/persistence"
"log"
)
type Turn int
const (
ShuffleStage Turn = iota
BetStage
DealCards
PlayerTurn
DealerTurn
ScoreStage
GameOver
)
type GameResult int
const (
Draw GameResult = iota
Blackjack
DealerWon
PlayerWon
DealerBust
PlayerBust
)
type GameState struct {
Rounds int
Deck deck.Deck
Turn
Player Hand
Dealer Hand
Bet int
Credit int
Logger persistence.Logger
}
type Options struct {
Rounds int
Credit int
Logger persistence.Logger
}
func (gs *GameState) CurrentPlayer() *Hand {
var ret *Hand
switch gs.Turn {
case PlayerTurn:
ret = &gs.Player
case DealerTurn:
ret = &gs.Dealer
default:
log.Panic("Not player turn")
}
return ret
}
func New(options Options) *GameState {
return &GameState{
Turn: ShuffleStage,
Credit: options.Credit,
Rounds: options.Rounds,
Logger: options.Logger,
}
}
func (gs *GameState) Play(ai Ai) int {
for gs.Turn != GameOver {
Shuffle(gs)
// Betting stage
ai.Bet(gs)
Deal(gs)
// Player turn
for gs.Turn == PlayerTurn {
ai.Play(gs)
}
// Dealer turn
for gs.Turn == DealerTurn {
if gs.Dealer.Score() < 16 || (gs.Dealer.Score() == 17 && gs.Dealer.MinScore() != 17) {
MoveHit(gs)
} else {
MoveStand(gs)
}
}
EndGame(gs)
ai.Result(gs)
}
return gs.Credit
}
func Deal(gs *GameState) {
if gs.Turn != DealCards {
log.Panic("Game is not in DealCards")
}
gs.Player.Deck = *deck.NewFromCards(gs.Deck.DrawHand(2))
gs.Dealer.Deck = *deck.NewFromCards(gs.Deck.DrawHand(2))
if gs.Player.Score() == 21 {
gs.Turn = DealerTurn
} else {
gs.Turn = PlayerTurn
}
}
func Shuffle(gs *GameState) {
if gs.Turn != ShuffleStage {
log.Panic("Game is not in ShuffleStage")
}
if len(gs.Deck.GetCards()) < 10 {
gs.Deck = *deck.New()
gs.Deck.Shuffle()
}
gs.Turn = BetStage
}
func MoveHit(gs *GameState) {
hand := gs.CurrentPlayer()
hand.Add(gs.Deck.Draw())
if hand.Score() >= 21 {
MoveStand(gs)
}
}
func MoveStand(gs *GameState) {
gs.Turn++
}
func MoveDouble(gs *GameState) {
if len(gs.Player.GetCards()) == 2 {
gs.Bet = gs.Bet * 2
MoveHit(gs)
MoveStand(gs)
}
}
func EndGame(gs *GameState) {
if gs.Turn != ScoreStage {
log.Panic("The game turn is not ScoreStage")
}
var result GameResult
switch {
case gs.Player.Score() == 21:
result = Blackjack
gs.Credit += gs.Bet + int(float64(gs.Bet)*1.5)
case gs.Player.Score() > 21:
result = PlayerBust
gs.Credit -= gs.Bet
case gs.Dealer.Score() > 21:
result = DealerBust
gs.Credit += gs.Bet
case gs.Player.Score() == gs.Dealer.Score():
result = Draw
case gs.Player.Score() > gs.Dealer.Score():
result = PlayerWon
gs.Credit += gs.Bet
case gs.Player.Score() < gs.Dealer.Score():
result = DealerWon
gs.Credit -= gs.Bet
}
// Log game
gs.Logger.LogDealerHand(gs.Dealer.GetCards())
gs.Logger.LogPlayerHand(gs.Player.GetCards())
gs.Logger.LogDealerScore(gs.Dealer.Score())
gs.Logger.LogPlayerScore(gs.Player.Score())
gs.Logger.LogBet(gs.Bet)
gs.Logger.LogResult(int(result))
gs.Logger.LogCredit(gs.Credit)
gs.Logger.Persist()
gs.Rounds--
// End game when there is no more credit or when finishing all rounds
// if gs.Rounds == 0 || gs.Credit <= 0 {
if gs.Rounds == 0 {
gs.Turn = GameOver
} else {
gs.Turn = ShuffleStage
}
}
func Bet(gs *GameState, amount int) {
if gs.Turn != BetStage {
log.Panic("The game is not currently in BetStage")
}
gs.Bet = amount
gs.Turn = DealCards
}
<file_sep>package blackjack
import (
"deckofcards/card"
"deckofcards/deck"
"strings"
)
type Hand struct {
deck.Deck
}
func (h *Hand) MinScore() int {
var score int
for _, crd := range h.GetCards() {
score += min(crd.GetRankInt(), 10)
}
return score
}
func (h *Hand) Score() int {
minScore := h.MinScore()
if minScore > 11 {
return minScore
}
for _, crd := range h.GetCards() {
if crd.GetRank() == card.Ace {
minScore += 10
}
}
return minScore
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func (h *Hand) ShowFinal() string {
var playerCards []string
for _, crd := range h.GetCards() {
playerCards = append(playerCards, crd.Display()["full"])
}
return strings.Join(playerCards, ", ")
}
func (h *Hand) ShowPartial() string {
var playerCards []string
for index, crd := range h.GetCards() {
if index == len(h.GetCards())-1 {
playerCards = append(playerCards, "** HIDDEN **")
} else {
playerCards = append(playerCards, crd.Display()["full"])
}
}
return strings.Join(playerCards, ", ")
}
<file_sep>module go-blackjack
go 1.13
require (
deckofcards v0.0.0
github.com/go-sql-driver/mysql v1.4.1
)
replace deckofcards => ./../deckofcards
<file_sep>package main
import (
"fmt"
"go-blackjack/blackjack"
"go-blackjack/persistence"
"time"
)
func main() {
game := blackjack.New(blackjack.Options{
Rounds: 1000,
Credit: 5000,
Logger: &persistence.Blackjack{},
})
// ai := blackjack.HumanAi{}
ai := blackjack.ComputerAi{}
start := time.Now()
finalScore := game.Play(&ai)
end := time.Now().Sub(start)
fmt.Printf("Time: %v \n", end)
fmt.Printf("Credit: %v \n", finalScore)
}
<file_sep>package persistence
import (
"deckofcards/card"
"encoding/json"
"time"
)
type Logger interface {
LogPlayerHand(cards []card.Card)
LogDealerHand(cards []card.Card)
LogPlayerScore(score int)
LogDealerScore(score int)
LogBet(bet int)
LogCredit(credit int)
LogResult(result int)
Persist()
}
type Blackjack struct {
id int
dealerHand string
playerHand string
dealerScore int
playerScore int
bet int
credit int
result int
created time.Time
updated time.Time
}
func (b *Blackjack) StringifyPlayerCards(cardIds []int) {
res, err := json.Marshal(cardIds)
checkError(err)
b.playerHand = string(res)
}
func (b *Blackjack) StringifyDealerCards(cardIds []int) {
res, err := json.Marshal(cardIds)
checkError(err)
b.dealerHand = string(res)
}
func (b *Blackjack) LogPlayerHand(cards []card.Card) {
cardsInt := cardsAsInt(cards)
b.StringifyPlayerCards(cardsInt)
}
func (b *Blackjack) LogDealerHand(cards []card.Card) {
cardsInt := cardsAsInt(cards)
b.StringifyDealerCards(cardsInt)
}
func (b *Blackjack) LogPlayerScore(score int) {
b.playerScore = score
}
func (b *Blackjack) LogDealerScore(score int) {
b.dealerScore = score
}
func (b *Blackjack) LogBet(bet int) {
b.bet = bet
}
func (b *Blackjack) LogCredit(credit int) {
b.credit = credit
}
func (b *Blackjack) LogResult(result int) {
b.result = result
}
func (b *Blackjack) Persist() {
insert(*b)
}
func cardsAsInt(cards []card.Card) []int {
var ret []int
for _, crd := range cards {
ret = append(ret, crd.GetRankInt())
}
return ret
}
|
ac7ce694c17605d9440bbd1d1290943ab0b839e5
|
[
"Go Module",
"Go"
] | 7 |
Go
|
MihaiBlebea/go-blackjack
|
f34ba4d51bae1cce01237377c31a3dc69ee85963
|
0f566ee414a59d23d2e3c8acfd0fda444554632e
|
refs/heads/master
|
<file_sep>messages.welcome=Bienvenue au support. Veuillez vous connectez
<file_sep># Asynchronous message board with Spring 4 and Servlet 3 - Long polling technique
Allows multiple users to connect a chat room and exchange instant messages, using long polling.
Manages timeouts for unactive users and automatically disconnects them.
A request is sent to the server only if a new message is available for the user or if a timeout has occured
Technologies
- Java 8
- Functional programming
- Stream API
- Joda Time
- ArrayBlockingQueue
- ThreadPoolExecutor
- Servlet 3
- Async Enabled
- No web.xml
- Annotation Config
- Spring MVC 4
- Annotation Config
- Async support
- Validation
- Formatting
- JSON Serializer
- locale resolver
- message source
- resource handler
- DeferredResult
<file_sep>package bg.alexander.chat.service;
import java.util.List;
import bg.alexander.chat.model.Message;
import bg.alexander.chat.model.SystemMessage;
import bg.alexander.chat.model.User;
/**
*
* @author Kirilov
*
*/
public interface MessageService {
public Message readMessage(String userId);
public boolean subscribe(User user);
public void broadcastMessage(User fromUser,String message);
public void keepAlive(String userId);
public boolean isUserSubscribed(String userId);
void postMessage(User fromUser, User toUser, String message);
public User getSubscribedUser(String userId);
public User getSubscribedUserByName(String userName);
public List<User> getUserConnections();
/**
* <p>
* Tell all users that a new user has been connected. </br>
* Uses a SystemMessage of type USER_CONNECTION
* </p>
*
* @see SystemMessage
* @param user
*/
public void broadcastUserConnection(User user);
}
<file_sep>user.name.validation.error=error name<file_sep>package bg.alexander.chat.model;
import java.util.concurrent.ArrayBlockingQueue;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* <p>
* A class representing a user connection between the server and the client </br>
* Each user tracks it's own message queue. Uses a blocking queue to make it wait
* </p>
*
* <p>
* {@link Message.EMPTY} represents a keep alive message
* </p>
*
* @author Kirilov
*
*/
public class UserConnection {
private ArrayBlockingQueue<Message> messages;
private User user;
private boolean isWaiting;
private boolean isActive;
private final Logger log = LogManager.getLogger(UserConnection.class);
private int keepAliveRetries; //the number of consecutive times a user can timeout before disc
public UserConnection() {
//TODO externalize application properties https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
messages = new ArrayBlockingQueue<>(30);
isActive = true;
keepAliveRetries=3;
}
/**
* <p>
* This method is called by the client, when he wants to check his messages </br>
* Essentially does messages.take() - blocking queue
* </p>
* <p>
* Reactivates the connection if it has not consumed all of it's timeouts
* </p>
*
* @return the first message of the queue. Waits until one is available
*/
public Message readMessage(){
if(isWaiting){
log.error("Someone else is waiting already for a message on this connection. Attemting to liberate connection");
try {
messages.put(Message.EMPTY);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
isWaiting = true;
//reactivate the connection since there is traffic on it
if(keepAliveRetries>0){
isActive = true;
}
Message message = messages.take();
log.debug("Message taken ["+message+"]");
isWaiting = false;
return message;
} catch (InterruptedException e) {
e.printStackTrace();
isWaiting = false;
}
return null;
}
/**
* This method is called by the server, when someone wants to send a message to the current user
* @param message
* @return
*/
public boolean sendMessage(Message message){
try {
this.messages.put(message);
keepAliveRetries = 3;
return true;
} catch (InterruptedException e) {
e.printStackTrace();
return false;
}
}
/**
* Keep the current connection alive by sending an empty keep alive message <br />
* When keep alive is initiated the connection is set to inactive, until the user actually consumes it
* @see #readMessage(Message)
*/
public void keepAlive(){
keepAliveRetries--;
try {
isActive = false; // on each timeout we deactivate
messages.put(Message.EMPTY);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(keepAliveRetries <= 0){
this.setActive(false);
}
}
public ArrayBlockingQueue<Message> getMessages() {
return messages;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public boolean isActive() {
return isActive;
}
/**
* Are there any timeout retries left ?
* @return <b>true</b> if keepAliveRetries = 0
*/
public boolean isTimeOuted() {
return keepAliveRetries > 0 ? false : true;
}
public void setActive(boolean isActive) {
this.isActive = isActive;
}
public boolean isWaiting() {
return isWaiting;
}
public void setWaiting(boolean isWaiting) {
this.isWaiting = isWaiting;
}
@Override
public String toString(){
return "User connection \n{\n"
+ "\tuser: "+user.getUserName()+"\n"
+ "\tisActive: "+isActive+"\n"
+ "\tisTimeOut: "+isTimeOuted()+"\n"
+ "\tisWaiting: "+isWaiting+"\n"
+ "\tkeepAliveRetries: "+keepAliveRetries+"\n}";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (isActive ? 1231 : 1237);
result = prime * result + (isWaiting ? 1231 : 1237);
result = prime * result + keepAliveRetries;
result = prime * result + ((messages == null) ? 0 : messages.hashCode());
result = prime * result + ((user == null) ? 0 : user.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserConnection other = (UserConnection) obj;
if (isActive != other.isActive)
return false;
if (isWaiting != other.isWaiting)
return false;
if (keepAliveRetries != other.keepAliveRetries)
return false;
if (messages == null) {
if (other.messages != null)
return false;
} else if (!messages.equals(other.messages))
return false;
if (user == null) {
if (other.user != null)
return false;
} else if (!user.equals(other.user))
return false;
return true;
}
}
<file_sep>apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'eclipse-wtp'
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
version = '1.0'
uploadArchives {
repositories {
flatDir {
dirs 'repos'
}
}
}
dependencies {
compile 'commons-lang:commons-lang:2.6'
compile 'javax.servlet:javax.servlet-api:3.1.0'
compile 'org.springframework:spring-webmvc:4.2.2.RELEASE'
compile 'org.thymeleaf:thymeleaf-spring4:2.1.4.RELEASE'
compile 'org.apache.logging.log4j:log4j-core:2.4.1'
compile 'com.fasterxml.jackson.core:jackson-databind:2.6.3'
compile 'org.hibernate:hibernate-validator:5.2.2.Final'
testCompile group: 'junit', name: 'junit', version: '4.12'
}<file_sep>package bg.alexander.chat.spring;
import java.util.Locale;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.format.FormatterRegistry;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
import bg.alexander.chat.controllers.formatters.UserFormatter;
@EnableWebMvc
@ComponentScan(basePackages="bg.alexander.*")
@Configuration
@EnableAsync
@PropertySource("classpath:/config/application.properties")
public class AppConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
super.addViewControllers(registry);
}
@Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
configurer.setDefaultTimeout(50000);
super.configureAsyncSupport(configurer);
}
@Bean(name="messageSource")
public ReloadableResourceBundleMessageSource getMessageResources(){
ReloadableResourceBundleMessageSource messageResource = new ReloadableResourceBundleMessageSource();
messageResource.setBasename("classpath:messages");
messageResource.setDefaultEncoding("UTF-8");
return messageResource;
}
@Bean(name="localeResolver")
public SessionLocaleResolver getSessionLocaleResolver(){
SessionLocaleResolver locale = new SessionLocaleResolver();
locale.setDefaultLocale(new Locale("en"));
return locale;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("locale");
registry.addInterceptor(localeChangeInterceptor);
// registry.addInterceptor(new SecurityInterceptor()).addPathPatterns("/secure/*");
super.addInterceptors(registry);
}
@Bean(name="templateResolver")
public ServletContextTemplateResolver getThymeleafTemplateResolver(){
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5");
templateResolver.setCacheable(false);
return templateResolver;
}
@Bean(name="validator")
public LocalValidatorFactoryBean getLocalValidatorFactoryBean(){
LocalValidatorFactoryBean factory = new LocalValidatorFactoryBean();
return factory;
}
@Bean
public UserFormatter getUserFormatter(){
return new UserFormatter();
}
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addFormatter(getUserFormatter());
}
@Bean(name="templateEngine")
public SpringTemplateEngine getSpringTemplateEngine(){
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(getThymeleafTemplateResolver());
return templateEngine;
}
@Bean
public ThymeleafViewResolver getThymeleafViewResolver(){
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(getSpringTemplateEngine());
return viewResolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(31556926);
}
}
<file_sep>user.name.validation.error=nom errone<file_sep>messages.welcome=Welcome to support. Please login
<file_sep>$(document).ready(function(){
$("#messageTo").keyup(function(event){
if(event.keyCode == 13){
sendMessage();
}
});
$.ajaxSetup({
cache: false,
statusCode: {
403: function() {
appendSystem("No connection to servers");
},
408: function() {
appendSystem("Disconnected due to innactivity");
}
}
});
});
function append(message, userId){
// console.log(message);
var conversation;
if(userId){
conversation = $('.messages#'+userId);
}
else{
conversation = $('.messages.active');
}
conversation.append('<br />'+message);
if(!conversation.hasClass('active')){
$('#'+userId+'.user-button').addClass('flash');
}
var messagesDiv = $('.active');
$('.messages.active').scrollTop(messagesDiv.prop("scrollHeight"));
}
/*<![CDATA[**/
function appendSystem(message){
var sysMessage = "<span class=\'message-system\'>"+message+"</span>";
append(sysMessage);
}
/*]]>*/
function subscribe(){
$.ajax({
method : "POST",
url : "subscribe",
data: {userName:$('#userName').val()}
}).done(function(result) {
appendSystem("Susbribed - "+result);
readMessages();
getConnectedUsers();
});
}
function readMessages() {
$.ajax({
method : "POST",
url : "read-messages",
data: {
user:$('#userName').val()
}
}).done(function(result) {
// console.log(result);
//TODO bug null message printed
if(result){
if(result.message == "USR_LOG"){
addConnectedUser(result.payload);
}
else{
append('<i>['+result.timeStamp+']: '+result.fromUser.userName+'</i>: '+result.message,result.fromUser.userId);
}
}
readMessages();
});
};
function sendMessage(){
$.ajax({
method : "POST",
url : "post-message",
data: {
toUser:$('#sendToUser').val(),
message:$('#messageTo').val()
}
}).done(function(){
var fromUser = $('#userName').val();
var messageTo = $("#messageTo").val();
var d = new Date();
append('<i>['+d.toLocaleTimeString()+']: '+fromUser+'</i>: '+messageTo);
$("#messageTo").val('');
});
};
function choseUser(userButton){
$('#sendToUser').val($(userButton).text());
$('.user-button').removeClass('selected');
$(userButton).addClass('selected');
$('.messages').removeClass('active');
$('.system-messages').removeClass('active');
var id = $(userButton).attr('id');
$('#'+id).addClass('active');
$('#'+id+'.user-button').removeClass('flash');
}
function addConnectedUser(user){
var userName = user.userName;
var userId = user.userId;
$('#connected-users').append('<br /><button class=\"user-button\" id=\"'+userId+'\" onclick=\"choseUser(this)\">'+userName+'</button>');
$('#container').prepend('<div class="messages panel user-messages" id=\"'+userId+'\">Messages:</div>');
}
function getConnectedUsers(){
$.ajax({
method : "GET",
url : "connected-users",
}).done(function(result){
$('#connected-users').html('');
$('.user-messages').remove();
$('.system-messages').addClass('active');
for(var i in result){
addConnectedUser(result[i]);
}
});
}
function broadcast(){
$.ajax({
method : "POST",
url : "broadcast-message",
data: {
message:$('#messageTo').val()
}
});
};<file_sep>package bg.alexander.chat.controllers.formatters;
import java.text.ParseException;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.Formatter;
import org.springframework.stereotype.Component;
import bg.alexander.chat.model.User;
import bg.alexander.chat.service.MessageService;
@Component
public class UserFormatter implements Formatter<User>{
@Autowired
private MessageService messageService;
@Override
public String print(User user, Locale locale) {
return user.toString();
}
@Override
public User parse(String userNameOrId, Locale locale) throws ParseException {
User user = messageService.getSubscribedUser(userNameOrId);
if(user!=null){
return user;
}
user = messageService.getSubscribedUserByName(userNameOrId);
return user;
}
}
|
862daf144ac2ea12ded3d06cea8f51cc3bc59d9a
|
[
"Markdown",
"JavaScript",
"INI",
"Gradle",
"Java"
] | 11 |
INI
|
sashokbg/company-web
|
ab6262a0a6693965ffa2ed6be6e93370d52eac7c
|
bb706ee6c065f1d2ac519cde1b5e06fe51182bc3
|
refs/heads/main
|
<file_sep>import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip, port = "127.0.0.1", 50
client.connect((ip, port))
Client = True
name = input("Nom du joueur ? ")
while Client:
chat = input(f"{name} > ")
client.send(f"{name} > {chat}".encode("utf-8"))
<file_sep>import pygame
class Joueur:
def affichage(self, surface):
pygame.draw.rect(surface, (200, 200, 200), self.rect)
def __init__(self, x, y, size):
self.x = x
self.y = y
self.size = size
self.velocity = 2
self.rect = pygame.Rect(self.x, self.y, self.size[0], self.size[1])
def mouvement(self, vitesse):
self.rect.y += vitesse
def move(self, dirn):
if dirn == 0:
self.x += self.velocity
elif dirn == 1:
self.x -= self.velocity
elif dirn == 2:
self.y -= self.velocity
else:
self.y += self.velocity<file_sep>from math import cos
import socket
import threading
import pygame
import sys
import random
import math
from joueur import Joueur
from ball import Ball
clock=pygame.time.Clock()
class Jeu:
def __init__(self):
self.ecran = pygame.display.set_mode((900, 500))
pygame.display.set_caption('jeu pong')
self.direct = True
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.ip, self.port = '169.254.230.36', 80
self.JoueurX1, self.JoueurY1 = 20, 250
self.JoueurX2, self.JoueurY2 = 860, 250
self.Joueur_size = [20, 80]
self.vitesseY1, self.vitesseY2 = 0, 0
self.Joueur1 = Joueur(self.JoueurX1, self.JoueurY1, self.Joueur_size)
self.Joueur2 = Joueur(self.JoueurX2, self.JoueurY2, self.Joueur_size)
self.rect = pygame.Rect(0, 0, 900, 500)
self.score1, self.score2 = 0, 0
self.ballX, self.ballY = None, None
self.Joueur1Pos = 250
self.recv_data = False
self.ball_direction = [-1, 1]
self.ball = Ball(450, 250, [20, 20], random.choice(self.ball_direction))
self.ball_shot = False
self.ballVx, self.ballVy = 1, 1
def principal(self):
self.client.connect((self.ip, self.port))
self.threadC(self.receive_data)
while self.direct:
clock.tick(400)
for event in pygame.event.get():
if event.type == pygame.quit:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_z:
self.vitesseY2 = -1
if event.key == pygame.K_s:
self.vitesseY2 = 1
if event.key == pygame.K_SPACE:
self.ball_shot = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_z:
self.vitesseY2 = 0
if event.key == pygame.K_s:
self.vitesseY2 = 0
if self.recv_data:
self.ball.rect.x = self.ballX
self.ball.rect.y = self.ballY
self.Joueur1.rect.y = self.Joueur1Pos
self.Joueur1.mouvement(self.vitesseY1)
self.Joueur2.mouvement(self.vitesseY2)
positionYJoueur2 = f" { self.Joueur2.rect.y }"
self.client.send(positionYJoueur2.encode('utf-8'))
self.Joueur1.rect.clamp_ip(self.rect) # Permet au joueur de se déplacer uniquement dans l'espace prévu
self.Joueur2.rect.clamp_ip(self.rect) # Permet au joueur de se déplacer uniquement dans l'espace prévu
self.recv_data = True
self.ecran.fill((50, 50, 50))
self.information('good', f"Ping Pong", [330, 50, 20, 20], (255, 255, 255))
self.information('good', f" { self.score1 } ", [180, 50, 20, 20], (255, 255, 255))
self.information('good', f" { self.score2 } ", [670, 50, 20, 20], (255, 255, 255))
self.ball.affichage(self.ecran)
self.Joueur1.affichage(self.ecran)
self.Joueur2.affichage(self.ecran)
pygame.display.flip()
def receive_data(self):
while True:
data_receive = self.client.recv(128).decode('utf-8')
data_receive = data_receive.split(', ')
self.Joueur1Pos = int(data_receive[0])
self.ballX = int(data_receive[1])
self.ballY = int(data_receive[2])
self.score1 = int(data_receive[3])
self.score2 = int(data_receive[4])
print(data_receive)
def information(self, font, message, messager, color):
if font == 'good':
font = pygame.font.Font('/Users/Okan/Desktop/DevPython/04B_19__.TTF', 50)
message = font.render(message, True, color)
self.ecran.blit(message, messager)
def ball_redirection(self, vitesse, angle):
vitesse = - (vitesse * math.cos(angle))
return vitesse
def threadC(self, cible):
thread = threading.Thread(target=cible)
thread.daemon = True
thread.start()
if __name__ == '__main__':
pygame.init()
Jeu().principal()
pygame.quit()<file_sep>from math import cos
import socket
import threading
import pygame
import sys
import random
import math
from joueur import Joueur
from ball import Ball
clock=pygame.time.Clock()
class Jeu:
def __init__(self):
self.ecran = pygame.display.set_mode((900, 500))
pygame.display.set_caption('jeu pong')
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.ip, self.port = '169.254.230.36', 80
self.client, self.adresse = None, None
self.server.bind((self.ip, self.port))
self.server.listen(1)
self.positionY = 250
self.direct = True
self.JoueurX1, self.JoueurY1 = 20, 250
self.JoueurX2, self.JoueurY2 = 860, 250
self.Joueur_size = [20, 80]
self.vitesseY1, self.vitesseY2 = 0, 0
self.Joueur1 = Joueur(self.JoueurX1, self.JoueurY1, self.Joueur_size)
self.Joueur2 = Joueur(self.JoueurX2, self.JoueurY2, self.Joueur_size)
self.rect = pygame.Rect(0, 0, 900, 500)
self.score1, self.score2 = 0, 0
self.ball_direction = [-1, 1]
self.ball = Ball(450, 250, [20, 20], random.choice(self.ball_direction))
self.ball_shot = False
self.ballVx, self.ballVy = 1, 1
def principal(self):
self.threadC(self.connexion)
while self.direct:
clock.tick(400)
for event in pygame.event.get():
if event.type == pygame.quit:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
self.vitesseY1 = -1
if event.key == pygame.K_DOWN:
self.vitesseY1 = 1
if event.key == pygame.K_z:
self.vitesseY2 = -1
if event.key == pygame.K_s:
self.vitesseY2 = 1
if event.key == pygame.K_SPACE:
self.ball_shot = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
self.vitesseY1 = 0
if event.key == pygame.K_DOWN:
self.vitesseY1 = 0
if event.key == pygame.K_z:
self.vitesseY2 = 0
if event.key == pygame.K_s:
self.vitesseY2 = 0
self.Joueur1.mouvement(self.vitesseY1)
self.Joueur2.rect.y = int(float(self.positionY))
self.Joueur2.mouvement(self.vitesseY2)
self.Joueur1.rect.clamp_ip(self.rect) # Permet au joueur de se déplacer uniquement dans l'espace prévu
self.Joueur2.rect.clamp_ip(self.rect) # Permet au joueur de se déplacer uniquement dans l'espace prévu
if self.ball_shot:
self.ball.mouvement(self.ballVx, self.ballVy)
if self.Joueur2.rect.colliderect(self.ball.rect) or self.Joueur1.rect.colliderect(self.ball.rect):
self.ballVx = self.ball_redirection(self.ballVx, 0)
self.ballVy = self.ball_redirection(self.ballVy, 60)
if self.ball.rect.top <= 0 or self.ball.rect.bottom >= 500:
self.ballVy = self.ball_redirection(self.ballVx, 0)
if self.ball.rect.right >= 901:
self.ball.rect.x, self.ball.rect.y = 450, 250
self.score1 += 1
self.ball_shot = False
if self.ball.rect.left <= 0:
self.ball.rect.x, self.ball.rect.y = 450, 250
self.score2 += 1
self.ball_shot = False
self.ball.rect.clamp_ip(self.rect)
send_data = f" {self.Joueur1.rect.y}, {self.ball.rect.x}, {self.ball.rect.y}, {self.score1}, {self.score2} "
if self.client is not None:
self.client.send(send_data.encode('utf-8'))
self.ecran.fill((50, 50, 50))
self.information('good', f"Ping Pong", [330, 50, 20, 20], (255, 255, 255))
self.information('good', f" { self.score1 } ", [180, 50, 20, 20], (255, 255, 255))
self.information('good', f" { self.score2 } ", [670, 50, 20, 20], (255, 255, 255))
if self.ball_shot is False:
self.information('good', f"Appuyez sur espace", [210, 120, 20, 20], (255, 255, 255))
self.ball.affichage(self.ecran)
self.Joueur1.affichage(self.ecran)
self.Joueur2.affichage(self.ecran)
pygame.display.flip()
def threadC(self, cible):
thread = threading.Thread(target=cible)
thread.daemon = True
thread.start()
def ball_redirection(self, vitesse, angle):
vitesse = - (vitesse * math.cos(angle))
return vitesse
def receive(self):
while True:
self.positionY = self.client.recv(128).decode('utf-8')
def information(self, font, message, messager, color):
if font == 'good':
font = pygame.font.Font('/Users/Okan/Desktop/DevPython/04B_19__.TTF', 50)
message = font.render(message, True, color)
self.ecran.blit(message, messager)
def connexion(self):
self.client, self.adresse = self.server.accept()
self.receive()
if __name__ == '__main__':
pygame.init()
Jeu().principal()
pygame.quit()<file_sep>import socket
import select
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip, port = "127.0.0.1", 50 # Adresse Ip locale ou celle d'un serveur réel
server.bind((ip, port))
server.listen(4)
clientC = True # Condition de démarrage
clientR = [server]
print("Vous pouvez discuter entre joueurs pendant ou après la partie")
while clientC: # Condition en cours
liste_lu, liste_acce_Ecrit, exception = select.select(clientR, [], clientR)
for clientRo in liste_lu:
if clientRo is server:
client, AdresseIP = server.accept()
print(f"Connexion en cours de : {client} - AdresseIP: {AdresseIP}")
clientR.append(client)
else:
donnees_recus = clientRo.recv(128).decode("utf-8")
if donnees_recus:
print(donnees_recus)
else:
clientR.remove(clientRo)
print("quelqu'un est parti")
print(f"Il ne reste plus que {len(clientR) - 1} personne(s)")
<file_sep># Projet-Dev-Logiciel
<NAME> & <NAME>
Il faut tout d'abord installer Python sur vos machines si ce n'est pas fait : https://www.python.org/downloads/
Pour que le jeu fonctionne sur votre machine il faut changer l'adresse IP dans les fichiers "client.py" et "pong.py" (elle se trouve au début du programme)
Pour que la police d'écriture soit prise en compte le projet doit être placé dans votre bureau et vous devez changer le nom d'utilisateur "Okan" par le votre :
- client.py : ligne 118
- pong.py : ligne 154
<file_sep>import pygame
import random
class Ball:
def affichage(self, surface):
pygame.draw.rect(surface, (230,230,230), self.rect)
def __init__(self, x, y, size, direction):
self.x = x
self.y = y
self.direction = direction
self.size = size
self.rect = pygame.Rect(self.x, self.y, self.size[0], self.size[1])
self.vitesse_Yrandom = random.randint(1, 1)
def mouvement(self, vitesseX, vitesseY):
self.vitesseX = 2
self.vitesseY = 3
self.rect.x = (self.rect.x + self.direction * vitesseX)
self.rect.y += self.vitesse_Yrandom * vitesseY
|
141380c502e9427d41b72c02c2af9f9685db597c
|
[
"Markdown",
"Python"
] | 7 |
Python
|
O-58-K/Projet-Dev-Logiciel
|
de014269d04621ab4511c4b89e7693cbb8c21824
|
b799a10da1138771e809916de04b0e9008cd151d
|
refs/heads/master
|
<repo_name>ArseniyZhivyh/test_seus<file_sep>/test_seus/pdf_parse.py
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 23 12:42:14 2020
@author: ars14
"""
import fitz
import pandas as pd
import os
from sqlalchemy import create_engine
import psycopg2
import numpy as np
#перечисление серверов и создание датафрейма
prox = ['172.16.17.32', '192.168.3.11', '172.16.17.32', '192.168.127.12']
df = pd.DataFrame(columns = ['IP', 'document_num', 'Period', 'Name', 'Address', 'Date_reestr', 'Num_reestr', 'INN', 'KPP', 'money', 'aim', 'face1', 'face2' ])
c = 0 #счётчик индексов датафрейма
#для каждого файла в папке для каждого сервера
for i in prox:
directory = './отчёты/'+str(i)
files = os.listdir(directory)
for f in files:
df.loc[c, 'IP'] = i
df.loc[c, 'document_num'] = str(f)
#открытие документа, соединение текста двух страниц, удаление номера страницы 2
pdf_document = directory + '/' + f
doc = fitz.open(pdf_document)
page = doc.loadPage(0)
page_text1 = page.getText("text")
page = doc.loadPage(1)
page_text2 = page.getText("text")
page_text_to_del = page_text2[0:33]
page_text2 = page_text2.replace(page_text_to_del, "")
page_text = page_text1 + page_text2
isp_index = page_text.find('использования')
dot_index = page_text.find('г.')
df.loc[c, 'Period'] = page_text[(isp_index+16):(dot_index+1)] #выделение отчётного периода
full_name_index = page_text.find('(полное')
df.loc[c, 'Name'] = page_text[(dot_index+3):full_name_index] #выделение название организации
adress_index = page_text.find('(адрес') #выеделение адреса организации
df.loc[c, 'Address'] = page_text[(full_name_index+len('полное наименование структурного подразделения')+2):adress_index]
rees_index = page_text.find('Реестровый')
rees_len = len('Реестровый номер структурного подразделения в реестре филиалов и представительств международных организаций и иностранных некоммерческих неправительственных организаций')
df.loc[c, 'Date_reestr'] = page_text[(rees_index+rees_len+1):rees_index+rees_len+11] #выделение даты внесения в реестр
INN_index = page_text.find('ИНН/КПП')
df.loc[c, 'Num_reestr'] = page_text[(rees_index+rees_len+11):INN_index] #выеделение номера в реестре
df.loc[c, 'INN'] = page_text[(INN_index+9):(INN_index+28):2] #выделение ИНН
df.loc[c, 'KPP'] = page_text[(INN_index+31):(INN_index+51):2] #выделение КПП
aim_index = page_text.find('Целевые средства, поступившие в отчетном периоде')
prb_index = page_text.find('\n', (aim_index+49))
df.loc[c, 'money'] = page_text[(aim_index+49):prb_index] #выделение суммы средств
inoe_index = page_text.find('Иное')
df.loc[c, 'aim'] = page_text[(prb_index+1):(inoe_index-3)] #выделение цели
face1 ='руковод<NAME>'
face1_index = page_text.find(face1)
dol ='(фамилия, имя, отчество, занимаемая должность)'
dol1_index = page_text.find(dol)
df.loc[c, 'face1'] = page_text[(face1_index+101):dol1_index] #выделение первого согласующего лица
dol2_index = page_text.rfind(dol)
df.loc[c, 'face2'] = page_text[(dol1_index+128):dol2_index] #выделение второго согласующего лица
c += 1 #увеличение индекса
#удаление нулевых отчётов
df = df.loc[df['money'] != '0']
df = df.loc[df['money'] != '0,00']
#очистка отчётов с неопределёнными ИНН, КПП и датой внесения в реестр и номером
df.loc[df['INN'] == '/1Днжы рдт', 'KPP'] = 0
df.loc[df['INN'] == '/1Днжы рдт', 'INN'] = 0
df.loc[df['Num_reestr'] == '', 'Date_reestr'] = 0
df.loc[df['INN'] == '9909043738', 'Num_reestr'] = 170
df.loc[df['INN'] == '9909025552', 'Num_reestr'] = 0
df.loc[df['INN'] == '9909005997', 'Num_reestr'] = 0
df.loc[df['INN'] == '9909291096', 'Num_reestr'] = 0
df.loc[df['INN'] == '9909195307', 'Num_reestr'] = 0
#подготовка данных для выгрузки в БД
IP_to_db = pd.DataFrame(df['IP'].unique())
company_to_db = df[['Name', 'Address', 'Date_reestr', 'Num_reestr', 'INN', 'KPP']]
company_to_db = df[['Name', 'Address', 'Date_reestr', 'Num_reestr', 'INN', 'KPP']].drop_duplicates()
doc_to_db = df[['document_num', 'IP', 'Name', 'Period', 'money', 'aim', 'face1', 'face2']]
face_to_db = pd.unique(df['face1']).tolist()
face_to_db.extend(pd.unique(df['face2']).tolist())
face_to_db = pd.DataFrame(np.unique(np.array(face_to_db)).tolist())
#выгрузка в БД
engine = create_engine('postgresql://postgres:14011998@localhost:5433/DBparse')
company_to_db.to_sql('company', engine)
IP_to_db.to_sql('IP', engine)
doc_to_db.to_sql('document', engine)
face_to_db.to_sql('face', engine)<file_sep>/test_seus/download_pages.py
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 18 15:07:01 2020
@author: ars14
"""
import time
from selenium import webdriver
import random
import urllib.request
# получение HTML кода
driver = webdriver.Chrome("C:\chromedriver")
driver.get("http://unro.minjust.ru/NKOReports.aspx?request_type=inko")
time.sleep(3)
Vid = driver.find_element_by_css_selector("#filter_nko_form :nth-child(2)")
time.sleep(3)
Vid.click()
time.sleep(3)
dt_from = driver.find_element_by_css_selector("#filter_dt_from :nth-child(2)")
dt_from.click()
time.sleep(3)
btn = driver.find_element_by_css_selector("#b_refresh")
btn.click()
time.sleep(3)
pdg = driver.find_element_by_css_selector(".pdg_count:last-child")
pdg.click()
time.sleep(3)
main_page1 = driver.page_source
btn_next = driver.find_element_by_css_selector("#pdg_next")
btn_next.click()
main_page2 = driver.page_source
time.sleep(3)
driver.quit()
# выделение нужных ID документов
id_index = [i for i in range(len(main_page1)) if main_page1.startswith('pk=', i)]
id_index2 = [i for i in range(len(main_page2)) if main_page2.startswith('pk=', i)]
IDs = []
for id_ind in id_index:
IDs.append(str(main_page1[(id_ind+4):(id_ind+12)]))
for id_ind2 in id_index2:
IDs.append(str(main_page2[(id_ind2+4):(id_ind2+12)]))
# cкачивание файлов
prox = ['192.168.127.12', '172.16.58.3', '172.16.58.3', '172.16.17.32']
err_ex_list = []
err_ex_list2 = []
exep = []
for i in IDs:
try:
page_link = 'http://unro.minjust.ru/Reports/'+str(i)+'.pdf'
a = random.choice(prox)
a_new = 'http://'+a+':8080'
proxies = {'http' : a}
down_link = './отчёты/'+a+'/'+str(i)+'.pdf'
urllib.request.urlretrieve(page_link, down_link)
except Exception:
err_ex_list.append(i)
# вторая попытка
for i in err_ex_list:
try:
page_link = 'http://unro.minjust.ru/Reports/'+str(i)+'.pdf'
a = random.choice(prox)
a_new = 'http://'+a+':8080'
proxies = {'http' : a}
down_link = './отчёты/'+a+'/'+str(i)+'.pdf'
urllib.request.urlretrieve(page_link, down_link)
except Exception as ex:
err_ex_list2.append(i) #запись id отчётов с ошибками
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
message = template.format(type(ex).__name__, ex.args)
exep.append(message)
with open('listfile.txt', 'w') as filehandle:
filehandle.writelines("%s\n" % item for item in err_ex_list2)
<file_sep>/test_seus/pdf_parsing.py
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 22 09:32:54 2020
@author: ars14
"""
import fitz
pdf_document = "./отчёты/8192.168.127.12/18177901.pdf"
doc = fitz.open(pdf_document)
page = doc.loadPage(0)
page_text1 = page.getText("text")
page = doc.loadPage(1)
page_text2 = page.getText("text")
page_text_to_del = page_text2[0:33]
page_text2 = page_text2.replace(page_text_to_del, "")
page_text = page_text1 + page_text2
isp_index = page_text.find('использования')
dot_index = page_text.find('.')
date_otch = page_text[(isp_index+16):dot_index]
full_name_index = page_text.find('(полное')
full_name = page_text[(dot_index+2):full_name_index]
adress_index = page_text.find('(адрес')
adress = page_text[(full_name_index+len('полное наименование структурного подразделения')+2):adress_index]
rees_index = page_text.find('Реестровый')
rees_len = len('Реестровый номер структурного подразделения в реестре филиалов и представительств международных организаций и иностранных некоммерческих неправительственных организаций')
rees_date = page_text[(rees_index+rees_len+1):rees_index+rees_len+11]
INN_index = page_text.find('ИНН/КПП')
rees_num = page_text[(rees_index+rees_len+11):INN_index]
INN_num = page_text[(INN_index+9):(INN_index+28):2]
KPP_num = page_text[(INN_index+31):(INN_index+51):2]
aim_index = page_text.find('Целевые средства, поступившие в отчетном периоде')
prb_index = page_text.find('\n', (aim_index+49))
den_summ = page_text[(aim_index+49):prb_index]
inoe_index = page_text.find('Иное')
aim = page_text[(prb_index+1):(inoe_index-3)]
face1 ='<NAME>'
face1_index = page_text.find(face1)
dol ='(фамилия, имя, отчество, занимаемая должность)'
dol1_index = page_text.find(dol)
face1_dol = page_text[(face1_index+101):dol1_index]
dol2_index = page_text.rfind(dol)
face2_dol = page_text[(dol1_index+128):dol2_index]
stroka = [date_otch, full_name, adress, rees_date, rees_num, INN_num, KPP_num, den_summ, aim, face1_dol, face2_dol]<file_sep>/README.md
# test_seus
Test task for Seuslab
|
2bf7481e2c118cf28d195beeead7e4436daa1583
|
[
"Markdown",
"Python"
] | 4 |
Python
|
ArseniyZhivyh/test_seus
|
261a2eef374485f593c208ae5f65589752544523
|
1b3b10076e2ce6e79deff2aeb69ca86ac4061251
|
refs/heads/master
|
<repo_name>aserv/Roguelike<file_sep>/Assets/Scripts/CameraController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour {
public float leftBound;
public float rightBound;
public float upBound;
public float downBound;
public float lerpPercent;
private float size;
private float z;
// Use this for initialization
void Start() {
size = gameObject.GetComponent<Camera>().orthographicSize;
z = gameObject.transform.position.z;
}
// Update is called once per frame
void Update() {
if (GameController.Instance.player == null) return;
Vector2 lerp = Vector2.Lerp(gameObject.transform.position, GameController.Instance.player.transform.position, lerpPercent);
Vector3 pos = new Vector3(lerp.x, lerp.y, z);
gameObject.transform.position = pos;
}
}<file_sep>/Assets/Scripts/AutoTileWall.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(SpriteRenderer))]
public class AutoTileWall : MonoBehaviour {
enum Place {
Empty,
Floor,
Wall}
;
enum Direction {
Right,
Down,
Left,
Up}
;
public Sprite wallU;
public Sprite wallD;
public Sprite wallL;
public Sprite wallR;
public Sprite wallCornerUL;
public Sprite wallCornerUR;
public Sprite wallCornerDL;
public Sprite wallCornerDR;
public Sprite wallOutCornerUL;
public Sprite wallOutCornerUR;
public Sprite wallOutCornerDL;
public Sprite wallOutCornerDR;
public Sprite wallHorInner;
public Sprite wallHorOuterL;
public Sprite wallHorOuterR;
public Sprite wallVertInner;
public Sprite wallVertOuterU;
public Sprite wallVertOuterD;
public Sprite wallInner;
public Sprite wallLone;
private SpriteRenderer spr;
// Use this for initialization
void Start() {
spr = gameObject.GetComponent<SpriteRenderer>();
Place[] surrounding = new Place[4]{ 0, 0, 0, 0 };
RaycastHit2D[] result = new RaycastHit2D [1];
Vector2 dir;
int r;
// get a direction from r, update array with for loop
for (int i = 0; i < 4; i++) {
dir = new Vector2(Mathf.Cos(Mathf.PI * i / 2), Mathf.Sin(Mathf.PI * i / 2));
//Debug.Log(dir);
r = gameObject.GetComponent<Collider2D>().Raycast(dir, result,
gameObject.GetComponent<Collider2D>().bounds.size.x + 0.1f);
if (r > 0) {
if (result [0].collider.gameObject.CompareTag("Wall")) {
// it sees a wall
surrounding [i] = Place.Wall;
//Debug.Log("Wall seen!");
} else {
// it sees a floor or door
surrounding [i] = Place.Floor;
//Debug.Log("Floor seen!");
}
}
}
switch (surrounding [(int)Direction.Right]) {
case Place.Wall: // wall to the right
if (surrounding [(int)Direction.Down] == Place.Wall) { // wall below, to the right
if (surrounding [(int)Direction.Left] == Place.Wall) { // 3 walls
if (surrounding [(int)Direction.Up] == Place.Floor) { // and a floor
spr.sprite = wallD;
} else { // 4 walls
spr.sprite = wallInner;
}
} else if (surrounding [(int)Direction.Up] == Place.Wall) { // 3 walls
if (surrounding [(int)Direction.Left] == Place.Floor) {
spr.sprite = wallL;
} else {
spr.sprite = wallInner;
}
} else { // exactly one wall below, one to the right
if (surrounding [(int)Direction.Left] == Place.Floor || surrounding [(int)Direction.Up] == Place.Floor) { // floor facing corner
spr.sprite = wallOutCornerDL;
} else { // inner corner
spr.sprite = wallCornerDL;
}
}
} else if (surrounding [(int)Direction.Left] == Place.Wall) { // wall to the left, to the right and not below
if (surrounding [(int)Direction.Up] == Place.Wall) { // wall to the left, to the right, and above
if (surrounding [(int)Direction.Down] == Place.Floor) { // floor below
spr.sprite = wallD;
} else { // 'nothing' below
spr.sprite = wallInner;
}
} else { // wall to the left, to the right, and not below or above
if (surrounding [(int)Direction.Up] == Place.Floor) {
if (surrounding [(int)Direction.Down] == Place.Floor) {
spr.sprite = wallHorInner; // floors on both sides
} else {
spr.sprite = wallU;
}
} else if (surrounding [(int)Direction.Down] == Place.Floor) {
spr.sprite = wallD;
} else {
spr.sprite = wallInner; // should never come up, but if someone screwed up it's here
}
}
} else if (surrounding [(int)Direction.Up] == Place.Wall) { // wall above, to the right and not below or to the left
if (surrounding [(int)Direction.Down] == Place.Floor || surrounding [(int)Direction.Left] == Place.Floor) {
spr.sprite = wallOutCornerUL;
} else {
spr.sprite = wallCornerUL;
}
} else { // only wall is to the right
spr.sprite = wallHorOuterR;
}
break;
default: // empty to the right
switch (surrounding [(int)Direction.Down]) {
case Place.Wall:
if (surrounding [(int)Direction.Left] == Place.Wall) { // wall below and to the left
if (surrounding [(int)Direction.Up] == Place.Wall) { // wall below, to the left, above
if (surrounding [(int)Direction.Right] == Place.Floor) {
spr.sprite = wallL;
} else {
spr.sprite = wallInner;
}
} else if (surrounding [(int)Direction.Up] == Place.Floor) { // floor above
if (surrounding [(int)Direction.Right] == Place.Floor) {
spr.sprite = wallOutCornerDR;
} else {
spr.sprite = wallU;
}
} else { // empty space above
if (surrounding [(int)Direction.Right] == Place.Floor) { // fix this shit to work like the rest
spr.sprite = wallL;
} else {
spr.sprite = wallCornerDR;
}
}
} else if (surrounding [(int)Direction.Up] == Place.Wall) { // wall below and above and not to the left
if (surrounding [(int)Direction.Left] == Place.Floor) {
if (surrounding [(int)Direction.Right] == Place.Floor) {
spr.sprite = wallVertInner; // floors on both sides
} else {
spr.sprite = wallR;
}
} else if (surrounding [(int)Direction.Right] == Place.Floor) {
spr.sprite = wallL;
} else {
spr.sprite = wallInner; // should never come up, but if someone screwed up it's here
}
} else { // just below
spr.sprite = wallVertOuterU;
}
break;
default: // empty to the right and below
switch (surrounding [(int)Direction.Left]) {
case Place.Wall:
if (surrounding [(int)Direction.Up] == Place.Wall) {
if (surrounding [(int)Direction.Right] == Place.Floor || surrounding [(int)Direction.Down] == Place.Floor) {
spr.sprite = wallOutCornerUR;
} else {
spr.sprite = wallCornerUR;
}
} else if (surrounding [(int)Direction.Up] == Place.Floor) {
if (surrounding [(int)Direction.Right] == Place.Floor) {
if (surrounding [(int)Direction.Down] == Place.Floor) {
spr.sprite = wallHorOuterL;
} else {
spr.sprite = wallOutCornerDR;
}
} else {
if (surrounding [(int)Direction.Down] == Place.Floor) {
spr.sprite = wallInner;
} else {
spr.sprite = wallU;
}
}
} else {
spr.sprite = wallInner;
}
break;
default: // empty to the right, left, and below
switch (surrounding [(int)Direction.Up]) {
case Place.Wall:
spr.sprite = wallVertOuterD;
break;
default: // no walls on any sides
if (surrounding [(int)Direction.Right] == Place.Floor ||
surrounding [(int)Direction.Down] == Place.Floor ||
surrounding [(int)Direction.Left] == Place.Floor ||
surrounding [(int)Direction.Up] == Place.Floor) {
spr.sprite = wallLone;
} else {
spr.sprite = wallInner;
}
break;
}
break;
}
break;
}
break;
}
}
}
<file_sep>/Assets/Scripts/UIManager.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIManager : MonoBehaviour {
public UIBar healthBar;
public UIBar expBar;
public Image[] itemIcon = new Image[4];
// Update is called once per frame
void Update () {
PlayerController.PlayerData data = GameController.Instance.data;
if (data == null) return;
healthBar.SetValue((float)data.health / (float)data.maxHealth);
expBar.SetValue(data.exp / data.nextexp);
for (int i = 0; i < 4; i++) {
BaseItem it = data.items[i];
if (it == null || it.Icon == null) {
itemIcon[i].enabled = false;
} else {
itemIcon[i].enabled = true;
itemIcon[i].sprite = it.Icon;
}
}
}
}
<file_sep>/Assets/Scripts/Enemy/EnemyController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class EnemyController : MonoBehaviour {
public float speed;
public int damageOnHit;
public int xp;
public int health;
public float findDistance;
private Rigidbody2D rb;
private Animator animator;
void Start() {
rb = GetComponent<Rigidbody2D>();
animator = this.GetComponent<Animator>();
}
// act as callbacks in the 'ai' of the more specific enemies
public Animator GetAnimator() {
return animator;
}
public void MoveStop()
{
rb.velocity = Vector2.zero;
}
public void SlowDown(float a)
{
rb.velocity = new Vector2(rb.velocity.x * a, rb.velocity.y * a);
}
public void MoveUp() {
MoveDegree(90.0f);
}
public void MoveDown() {
MoveDegree(270.0f);
}
public void MoveRight() {
MoveDegree(0.0f);
}
public void MoveLeft() {
MoveDegree(180.0f);
}
public void MoveDegree(float angle) {
MoveRadian(Mathf.Deg2Rad * angle);
}
public void MoveRadian(float angle) {
rb.MoveRotation((angle * Mathf.Rad2Deg - 90) % 360);
rb.velocity = new Vector2(Mathf.Cos(angle) * speed, Mathf.Sin(angle) * speed);
}
void OnCollisionEnter2D(Collision2D other) {
if (other.gameObject.CompareTag("Player")) {
HurtPlayer(damageOnHit);
}
}
public float pickAngle()
{
Vector2 dir = GameController.Instance.player.GetComponent<Rigidbody2D>().position - GetComponent<Rigidbody2D>().position;
dir.Normalize();
return Mathf.Atan2(dir.y, dir.x);
}
public bool CloseToPlayer(float dist) {
return Vector2.Distance(gameObject.transform.position, GameController.Instance.player.gameObject.transform.position) < dist;
}
public void HurtPlayer(int dmg) {
GameController.Instance.player.TakeDamage(dmg);
}
public void TakeDamage(int dmg) {
health -= dmg;
if (health <= 0) {
Die();
}
}
public void Die() {
GameController.Instance.player.AddExp(xp);
GameObject.Find("DropManager").GetComponent<DropManager>().Drop(transform.position);
Destroy(gameObject);
}
}
<file_sep>/Assets/Scripts/Items/Item.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Linq;
public abstract class BaseItem {
public enum Result {
Ignored,
Consumed,
Charging
};
public Sprite Icon { get; private set; }
public string Name { get; private set; }
public BaseItem(String name, Sprite icon) { Name = name; Icon = icon; }
public virtual BaseItem Clone() { return (BaseItem)this.MemberwiseClone(); }
public abstract Result Use(PlayerController player);
public virtual Result Release(PlayerController player) { return Result.Ignored; }
}
public class Pattern {
public struct FireAction {
public float Time;
public Quaternion Direction;
public bool Relative;
}
public Pattern(IEnumerable<FireAction> a) {
this.actions = a.OrderBy(x => x.Time).ToArray();
}
private FireAction[] actions;
public IEnumerator Begin(Action<Quaternion, bool> action) {
int i = 0;
float time = Time.time;
while (i < actions.Length) {
FireAction a = actions[i];
if (actions[i].Time + time > Time.time) {
yield return new WaitForSeconds(actions[i].Time + time - Time.time);
} else {
action(a.Direction, a.Relative);
i++;
}
}
yield break;
}
}
namespace Items {
public class HealthUpItem : BaseItem {
public int HealthUp { get; private set; }
public HealthUpItem(String name, Sprite icon) : base(name, icon) { HealthUp = 1; }
public override Result Use(PlayerController player) {
player.data.health += HealthUp;
return Result.Consumed;
}
}
public class BasicProjectileItem : BaseItem {
public GameObject Prefab { get; private set; }
private Pattern pattern;
public BasicProjectileItem(String name, Sprite icon, GameObject prefab, Pattern pattern) : base(name, icon) {
Prefab = prefab;
this.pattern = pattern;
}
public override Result Use(PlayerController player) {
player.StartCoroutine(
pattern.Begin((d, r) => {
Vector2 v = player.Facing();
Quaternion rot = r ? Quaternion.Euler(0, 0, Mathf.Rad2Deg * Mathf.Atan2(v.y, v.x)) : Quaternion.identity;
rot *= d;
GameObject.Instantiate(Prefab, player.gameObject.transform.position, rot);
})
);
return Result.Consumed;
}
}
}
<file_sep>/Assets/Scripts/Items/Pickup.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Collider2D))]
public class Pickup : MonoBehaviour {
public BaseItem item;
private void OnTriggerEnter2D(Collider2D collider) {
if (collider.CompareTag("Player")) {
if (collider.GetComponent<PlayerController>().PickupItem(item)) {
Destroy(gameObject);
}
}
}
}
<file_sep>/Assets/Scripts/PlayerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
[RequireComponent(typeof(Rigidbody2D))]
public class PlayerController : MonoBehaviour {
[Serializable]
public class PlayerData {
public float moveSpeed;
public int health;
public int maxHealth;
public int exp;
public int nextexp;
public int lvl;
public BaseItem[] items = new BaseItem[4];
}
public PlayerData data = new PlayerController.PlayerData();
public float punchDistance;
public int punchStrength;
private int nextItem = 0;
private Rigidbody2D rb;
private Vector2 facing;
private Animator animator;
// Use this for initialization
void Start() {
rb = this.GetComponent<Rigidbody2D>();
animator = this.GetComponent<Animator>();
}
void Update() {
if (data.items [0] != null && Input.GetButtonDown("Use1")) {
UseItem(0);
}
if (data.items [1] != null && Input.GetButtonDown("Use2")) {
UseItem(1);
}
if (data.items [2] != null && Input.GetButtonDown("Use3")) {
UseItem(2);
}
if (data.items [3] != null && Input.GetButtonDown("Use4")) {
UseItem(3);
}
if (Input.GetButtonDown("Attack")) {
Attack();
}
}
// Update is called once per frame
void FixedUpdate() {
Vector2 input= Snap(new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")));
rb.velocity = input * data.moveSpeed;
if (input != Vector2.zero) {
facing = input;
animator.SetFloat("X", facing.x);
animator.SetFloat("Y", facing.y);
}
}
public Vector2 Facing() {
return facing;
}
public void AddExp(int xp) {
data.exp += xp;
}
public bool PickupItem(BaseItem i) {
if (nextItem == -1)
return false;
data.items [nextItem] = i;
for (int n = 3; n >= 0; n--) {
if (data.items [n] == null)
nextItem = n;
}
return true;
}
public BaseItem GetItemAt(int i) {
return data.items [i];
}
private void UseItem(int i) {
if (data.items [i] == null) return;
animator.SetTrigger("UseItem");
BaseItem.Result res = data.items [i].Use(this);
if (res == BaseItem.Result.Consumed) {
if (nextItem == -1 || nextItem > i)
nextItem = i;
data.items [i] = null;
}
}
public void TakeDamage(int dmg) {
data.health -= dmg;
if (data.health <= 0)
GameController.Instance.KillPlayer();
}
public void Attack() {
animator.SetTrigger("Attack");
RaycastHit2D[] results = new RaycastHit2D[1];
int r = gameObject.GetComponent<Collider2D>().Cast(facing, results, punchDistance);
if (r > 0 && results [0].rigidbody != null && results [0].rigidbody.gameObject.CompareTag("Enemy")) {
results [0].rigidbody.gameObject.GetComponent<EnemyController>().TakeDamage(punchStrength);
}
}
private const float sqrt2over2 = 0.707106781186f;
private static Vector2 Snap(Vector2 v) {
float abx = Mathf.Abs(v.x);
float aby = Mathf.Abs(v.y);
float sx = v.x == 0 ? 0 : Mathf.Sign(v.x);
float sy = v.y == 0 ? 0 : Mathf.Sign(v.y);
if (abx > 2 * aby) {
return new Vector2(sx, 0);
} else if (aby > 2 * abx) {
return new Vector2(0, sy);
} else {
return new Vector2(sx * sqrt2over2, sy * sqrt2over2);
}
}
}
<file_sep>/Assets/Scripts/Enemy/SlimeController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SlimeController : EnemyController {
// Update is called once per frame
void FixedUpdate() {
if (GameController.Instance.player != null && CloseToPlayer(findDistance)) {
MoveRadian(pickAngle());
}
}
private float pickAngle() {
Vector2 dir = GameController.Instance.player.GetComponent<Rigidbody2D>().position - GetComponent<Rigidbody2D>().position;
dir.Normalize();
return Mathf.Atan2(dir.y, dir.x);
}
}
<file_sep>/README.md
Roguelike (Name Pending)
-------
[Link to setup YAML Merge](https://docs.unity3d.com/Manual/SmartMerge.html)
<file_sep>/Assets/Scripts/Projectile.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class Projectile : MonoBehaviour {
public float speed;
public int damage;
// Use this for initialization
void Start () {
this.GetComponent<Rigidbody2D>().velocity = this.transform.right * speed;
}
void OnCollisionEnter2D(Collision2D collision) {
PlayerController p = collision.gameObject.GetComponent<PlayerController>();
if (p != null) {
p.TakeDamage(damage);
}
EnemyController e = collision.gameObject.GetComponent<EnemyController>();
if (e != null) {
e.TakeDamage(damage);
}
Destroy(gameObject);
}
}
<file_sep>/Assets/Scripts/RaiseGateOnDead.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RaiseGateOnDead : MonoBehaviour {
public GameObject raiseOnKill;
void Update() {
if (raiseOnKill == null /*&& GameObject.FindWithTag("Enemy") == null*/) {
gameObject.GetComponent<Animator>().SetBool("shouldMoveUp", true);
}
}
}
<file_sep>/Assets/Scripts/GameController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.SceneManagement;
public class GameController : MonoBehaviour {
public string[] scenelist;
public GameObject playerPrefab;
public PlayerController.PlayerData data { get; private set; }
private Scene startScene;
public PlayerController player { get; private set; }
void Awake() {
Instance = this;
DontDestroyOnLoad(gameObject);
SceneManager.sceneLoaded += OnSceneLoad;
GameObject go = GameObject.Find("Player");
if (go != null) {
player = go.GetComponent<PlayerController>();
data = player.data;
}
startScene = SceneManager.GetActiveScene();
}
void OnSceneLoad(Scene scene, LoadSceneMode mode) {
if (scene != startScene) {
GameObject sp = GameObject.Find("PlayerSpawn");
GameObject go = Instantiate(playerPrefab, sp.transform.position, Quaternion.identity);
player = go.GetComponent<PlayerController>();
player.data = data;
}
foreach (LevelTrigger lt in GameObject.FindObjectsOfType<LevelTrigger>()) {
if (!lt.isActiveAndEnabled) continue;
lt.onHit = scenelist[UnityEngine.Random.Range(0, scenelist.Length - 1)];
}
}
void OnDisable() {
SceneManager.sceneLoaded -= OnSceneLoad;
}
public void KillPlayer() {
Destroy(player.gameObject);
player = null;
}
public static GameController Instance { get; private set; }
}
<file_sep>/Assets/Scripts/Items/ItemTable.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Xml;
using System.IO;
using System.Reflection;
public class ItemTable {
private class DropList {
private struct DropRateElement {
public BaseItem item;
public int rate;
public int sum;
};
private int total = 0;
private int count = 0;
private DropRateElement[] items = null;
private void Resize(int size = 0) {
if (items == null) {
items = new DropRateElement[8];
} else {
if (size == 0) { size = items.Length * 2; } else if (size <= items.Length) { return; }
DropRateElement[] nitems = new DropRateElement[size];
items.CopyTo(nitems, 0);
items = nitems;
}
}
public void Add(BaseItem item, int rate) {
if (items == null || items.Length == count) { Resize(); }
total += rate;
items[count++] = new DropRateElement() { item = item, rate = rate, sum = total };
}
public BaseItem RandomDrop(int val = -1) {
if (val == -1) {
val = Random.Range(0, total);
}
int s = 0, e = count;
while (s < e) {
int mid = (s + e) / 2;
if (items[mid].sum < val) {
s = mid + 1;
} else if (items[mid].sum - items[mid].rate < val) {
return items[mid].item;
} else {
e = mid - 1;
}
}
return items[s].item;
}
};
private ItemTable() { }
public ItemTable(int tiers) {
droptiers = new DropList[tiers];
for (int i = 0; i < tiers; i++) {
droptiers[i] = new DropList();
}
itemlist = new Dictionary<string, BaseItem>();
}
private Dictionary<string, BaseItem> itemlist;
private DropList[] droptiers;
public BaseItem this[string name] {
get { return itemlist[name]; }
}
public void AddItem(BaseItem item, int tier, int rate) {
itemlist.Add(item.Name, item);
droptiers[tier].Add(item, rate);
}
public BaseItem RandomDrop(int mintier, int maxtier, float promote = 0.25f) {
mintier = Mathf.Min(mintier, droptiers.Length - 1);
maxtier = Mathf.Min(maxtier, droptiers.Length - 1);
int t = mintier;
while (t < maxtier && Random.Range(0, 1) < promote) { ++t; }
if (t < 0) { return null; }
return droptiers[t].RandomDrop();
}
private static bool ReadTo(XmlReader reader, XmlNodeType type, string name) {
while (reader.Read()) {
if (reader.NodeType == type && reader.Name == name)
return true;
}
return false;
}
private static BaseItem LoadItem(XmlReader reader, Dictionary<string, Pattern> patterns) {
reader.MoveToContent();
ArrayList args = new ArrayList();
string typeName = reader.GetAttribute("name");
try {
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "item") break;
if (reader.NodeType == XmlNodeType.Element) {
string n = reader.Name;
if (n == "name") {
args.Add(reader.ReadElementContentAsString());
} else if (n == "icon") {
Object[] res = Resources.LoadAll(reader.ReadElementContentAsString(), typeof(Sprite));
args.Add(res.Length == 0 ? null : res[0]);
} else if (n == "prefab") {
args.Add(Resources.Load(reader.ReadElementContentAsString(), typeof(GameObject)) as GameObject);
} else if (n == "pattern") {
args.Add(patterns[reader.ReadElementContentAsString()]);
} else {
Debug.LogFormat("Ignoring item argument {0}", reader.Name);
}
}
}
System.Type runtimeType = Assembly.GetExecutingAssembly().GetType(typeName);
BaseItem it = System.Activator.CreateInstance(runtimeType, args.ToArray()) as BaseItem;
return it;
} catch (System.Exception e) {
Debug.Log(e.Message);
return null;
}
}
private static Pattern LoadPattern(XmlReader reader) {
List<Pattern.FireAction> actions = new List<Pattern.FireAction>();
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "pattern") break;
if (reader.NodeType == XmlNodeType.Element) {
Pattern.FireAction act = new Pattern.FireAction();
float angle;
if (reader.Name == "absolute") {
act.Relative = false;
} else if (reader.Name == "relative") {
act.Relative = true;
} else {
continue;
}
if (float.TryParse(reader.GetAttribute("time"), out act.Time) && float.TryParse(reader.ReadElementContentAsString(), out angle)) {
act.Direction = Quaternion.Euler(0, 0, angle);
}
actions.Add(act);
}
}
return new Pattern(actions);
}
public static ItemTable Load(string resource) {
ItemTable table = new ItemTable();
table.itemlist = new Dictionary<string, BaseItem>();
XmlReader reader = XmlReader.Create(new FileStream(resource, FileMode.Open));
Dictionary<string, Pattern> patterns = new Dictionary<string, Pattern>();
reader.MoveToContent();
if (!reader.ReadToDescendant("patterns")) {
Debug.Log("XML Has no patterns");
return null;
}
if (reader.ReadToDescendant("pattern")) {
do {
string name = reader.GetAttribute("name");
Pattern p = LoadPattern(reader.ReadSubtree());
if (p != null) patterns.Add(name, p);
} while (reader.ReadToNextSibling("pattern"));
}
if (!reader.ReadToNextSibling("items")) {
Debug.Log("XML Has no items");
return null;
}
if (reader.ReadToDescendant("item")) {
do {
BaseItem it = LoadItem(reader.ReadSubtree(), patterns);
if (it != null) {
table.itemlist.Add(it.Name, it);
} else {
Debug.Log("Failed to Load Item");
}
} while (reader.ReadToNextSibling("item"));
}
if (!reader.ReadToNextSibling("droptable")) {
Debug.Log("XML Has no droptable");
return null;
}
int tiers = 0;
if (System.Int32.TryParse(reader.GetAttribute("tiers"), out tiers)) {
table.droptiers = new DropList[tiers];
for (int i = 0; i < tiers; i++) table.droptiers[i] = new DropList();
} else {
Debug.Log("Droplist has no tiers attribute");
return null;
}
if (reader.ReadToDescendant("drop")) {
do {
string name;
int t, r;
name = reader.GetAttribute("item");
if (!System.Int32.TryParse(reader.GetAttribute("tier"), out t) ||
!System.Int32.TryParse(reader.GetAttribute("rate"), out r)) {
continue;
}
if (t >= tiers) {
Debug.LogFormat("Tier {0} for is out of range {1}", t, name);
continue;
}
BaseItem it = table.itemlist[name];
if (it == null) {
Debug.LogFormat("Item {0} not found", name);
continue;
}
table.droptiers[t].Add(it, r);
} while (reader.ReadToNextSibling("drop"));
}
return table;
}
}<file_sep>/Assets/Scripts/UIBar.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIBar : MonoBehaviour {
public Image foreground;
public Image background;
private float value;
public void SetValue(float portion) {
portion = Mathf.Clamp(portion, 0, 1);
Vector2 anchor = foreground.rectTransform.anchorMin;
anchor.x = 1 - portion;
foreground.rectTransform.anchorMin = anchor;
}
}
<file_sep>/Assets/Scripts/DropManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class DropManager : MonoBehaviour {
public GameObject pickup;
public GameObject[] prefabs;
private ItemTable table = null;
void Start() {
try {
table = ItemTable.Load("Assets/resources/items.xml");
} catch (System.Exception e) {
Debug.Log(e);
}
//table.AddItem(new HealthUpItem("Mutton", null), 0, 10);
//table.AddItem(new BasicProjectileItem("Fireball", null, prefabs.First(x => x.name == "Fireball")), 0, 5);
}
public void Drop(Vector2 location) {
BaseItem i = table.RandomDrop(0, 0);
if (i == null) return;
GameObject go = Instantiate(pickup, location, Quaternion.identity);
go.GetComponent<Pickup>().item = i.Clone();
}
}
|
c6d3780d24b43f854285e27f503f419da6f85d3a
|
[
"Markdown",
"C#"
] | 15 |
C#
|
aserv/Roguelike
|
2671653eb653a4e8de2bb4098bfd768a208092d3
|
7d2734862918fbe44ecbf5cf5843875f0ffdae62
|
refs/heads/main
|
<repo_name>ishitajain99/musicperk<file_sep>/README.md
# musicperk
internship task
<file_sep>/ticker.py
from datetime import datetime
import mysql.connector as SQL
import pandas as pd
conn = SQL.connect(user="root", passwd="", host="localhost",
database="musicperk")
cur = conn.cursor()
df = pd.read_excel("HINDALCO_1D.xlsx",engine='openpyxl')
date_time = df['datetime']
close = df['close']
high = df['high']
low = df['low']
open = df['open']
volume = df['volume']
instrument = df['instrument']
query = '''
INSERT INTO ticker_symbol (date,close,high,low,open,volume,instrument)
value(%s,%s,%s,%s,%s,%s,%s);
'''
for d,c,h,l,o,v,i in zip(date_time,close,high,low,open,volume,instrument):
date,time=str(d).split(" ")
yyyy,mm,dd = date.split('-')
h,m,s = time.split(':')
d = datetime(int(yyyy),int(mm),int(dd),int(h),int(m),int(s))
cur.execute(query,(d,c,h,l,o,v,i))
conn.commit()
|
0a78a1ce2e98145f215ed20779b6c30a26d1500a
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
ishitajain99/musicperk
|
a604cb912bcf583ab289abff4317bf4a8b96d7e6
|
3019fedb70369c712c80927986a31c4b44ed780d
|
refs/heads/master
|
<file_sep>bl_info = {
"name": "Texture Retriever",
"author": "Quaddy9779",
"version": (1, 1),
"blender": (2, 77, 0),
"location": "View3D > Tool Shelf > TexRet",
"description": "Copies all your textures and paste it to a target Directory",
"warning": "",
"wiki_url": "",
"category": "Copy Texture",
}
import bpy_extras
import os
import shutil
import os.path
import bpy
from bpy.props import (StringProperty,
PointerProperty,
)
from bpy.types import (Panel,
Operator,
AddonPreferences,
PropertyGroup,
)
#-----------
# DEF
#-----------
def main(context):
#body
scn = context.scene
filepath = bpy.data.filepath
directory = filepath
targetdir = scn.my_tool.path
a = -1
os.system("cls")
if not os.path.isdir(targetdir):
b = targetdir.split("..")
if ".." in targetdir:
for x in b:
a += 1
directory = os.path.dirname(directory)
targetdir = targetdir.replace("//..", "")
targetdir = targetdir.replace("\..", "")
elif "//" in targetdir:
directory = os.path.dirname(directory)
targetdir = targetdir.replace("//", "\\")
print("Copying files.... \n")
for ob in bpy.data.objects:
for mat_slot in ob.material_slots:
for mtex_slot in mat_slot.material.texture_slots:
if mtex_slot and mtex_slot.use == 1:
if hasattr(mtex_slot.texture , 'image'):
if(mtex_slot.texture is not None):
CurImage = mtex_slot.texture.image.filepath
directory = filepath
a = -1
b = CurImage.split("..")
if ".." in CurImage:
for x in b:
a += 1
directory = os.path.dirname(directory)
CurImage = CurImage.replace("//..", "")
CurImage = CurImage.replace("\..", "")
elif "//" in CurImage:
directory = os.path.dirname(directory)
CurImage = CurImage.replace("//", "\\")
if os.path.isfile(directory + CurImage):
print(directory + CurImage)
shutil.copy(directory + CurImage, targetdir)
elif os.path.isfile(CurImage):
print(CurImage)
shutil.copy(CurImage, targetdir)
list = os.listdir(targetdir)
total_files = len(list)
print("\nTotal files that is in the folder: " + str(total_files - 1) + ". Note: Ignore duplicate ones in the log")
#print(directory + targetdir)
#print("total is:" + str(a))
# ------------------------------------------------------------------------
# ui
# ------------------------------------------------------------------------
class MySettings(PropertyGroup):
path = StringProperty(
name="",
description="Path to Directory",
default="",
maxlen=1024,
subtype='DIR_PATH')
bb = ""
class MainTexRet(bpy.types.Operator):
"""Tooltip"""
bl_idname = "myops.get_textures"
bl_label = "Get Texture"
def execute(self, context):
bb = self
scn = context.scene
targetdir = scn.my_tool.path
if(targetdir == ""):
self.report({'ERROR'}, "Please fill up the target directory properly")
return {'FINISHED'}
else:
main(context)
return {'FINISHED'}
class OBJECT_PT_my_panel(Panel):
bl_idname = "OBJECT_PT_texret"
bl_label = "TexRet Panel"
bl_space_type = "VIEW_3D"
bl_region_type = "TOOLS"
bl_category = "TexRet"
bl_context = "objectmode"
def draw(self, context):
layout = self.layout
scn = context.scene
col = layout.column(align=True)
col.prop(scn.my_tool, "path", text="Target Location")
row = layout.row()
row.operator("myops.get_textures")
# print the path to the console
#print (scn.my_tool.path)
#filepath = bpy.data.filepath
#directory = os.path.dirname(os.path.dirname(filepath))
#print(directory)
# ------------------------------------------------------------------------
# register and unregister functions
# ------------------------------------------------------------------------
def register():
bpy.utils.register_module(__name__)
bpy.types.Scene.my_tool = PointerProperty(type=MySettings)
def unregister():
bpy.utils.unregister_module(__name__)
del bpy.types.Scene.my_tool
if __name__ == "__main__":
register()
<file_sep># TexRet
Texture retriever for blender.
Useful if you have different parts of a model and if you're unsure what texture is used.
Changelog:
* 1.0
* Added Initial Script.
* 1.1
* Fixed where it keeps fetching textures that is not used.
* Fixed file path locations. (Report to me if you encounter something with this)
Requirements:
1. Different Models with different textures. (Still can be used with a single model)
1. It is better to run Blender as Admin (Win8 and Win10)
Credits:
* Crantisz (Really helped me alot)
If you have suggestions or better improvement for the script.
Dm me at discord (Quaddy#6969)
Happy Sculpting! ~Quaddy
|
7302fc1473603fe4b6c126dc12e126eb056974f3
|
[
"Markdown",
"Python"
] | 2 |
Python
|
quadlegacy/TexRet
|
40a49fb33bba5a854c9cb7848a19c301780a27d3
|
bd8cc19e2072bda6f367329f4f01c121dc245bce
|
refs/heads/master
|
<file_sep># Generated by Django 2.2.7 on 2019-11-27 14:17
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('todo', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='todoitem',
name='content',
field=models.TextField(default=django.utils.timezone.now),
preserve_default=False,
),
]
<file_sep># **Django project**
### **Creating virtual env with pipenv**
* create Folder, cd to it,
* pip3 install pipenv
* pipenv shell - to activate it inside the Project folder
* exit or Ctrl D to deactivate
### **Installing Django**
* pipenv install django - make sure you are in the project folder
* django-admin startproject DjangoProject .
* ls to see if the django files have been created, go to: 127.0.0.1:8000
### **Configuring Django**
* python manage.py runserver - to start Django server
* control C to quit
* python manage.py startapp hello - start Django app within the project
* settings.py - add hello app to INSTALLED_APPS list
* view.py - create view for target URL - def view as a function
* urls.py - add path to urlpaterns list
### **Create todo app with Django**
* python manage.py startapp todo
* add app in the settings.py
* create a func in todo\views.py (import HttpResponse)
* add path in urlpatters for the view
* create templates folder and .html file in there
* add it to views
* add [os.path.join(BASE_DIR,'templates')], to TEMPLATES/DIRS in settings.py
* create TodoItem class in models.py
* migrate class to the database:
* python manage.py makemigrations - creates migration file
* python manage.py migrate - changing config of our db - adding todo model
* python manage.py shell - storing objects in the database:
from todo.models import TodoItem
a = TodoItem(content='todo item AA')
a.save()
b = TodoItem(content='todo item B')
c = TodoItem(content='todo item C')
b.save()
c.save()
all_todo_items = TodoItem.objects.all()
all_todo_items[1].content
* edit views.py import TodoItem from .models , retriev all todo items from the db, add third argument to the render func - add all_todo_items to todo.html template - assign name all_items to it
* edit todo.html add for loop to loop through all_items
* add input form to the todo.html
* create a new todo item in views.py
* add a path in the urls.py
* Add delete button in the todo.html - inside the for loop (for each item)
|
758edaf6ce5f578b59b9feb8df85322dc81a0505
|
[
"Markdown",
"Python"
] | 2 |
Python
|
greenszpila/DjangoProject
|
7c52d17ec86872c5f46cb57422cdc249c3d821f2
|
61a02189b3887100cef147e1e1f4b6e36726b279
|
refs/heads/master
|
<repo_name>bventel/django-deployment-example<file_sep>/learning_users/basic_app/urls.py
from django.conf.urls import url
from basic_app import views
from django.urls import path
# TEMPLATE_URLS
app_name = 'basic_app'
urlpatterns = [
url(r'^register/$', views.register, name='register'),
path('user_login/',views.user_login,name='user_login'),
]
|
c04882208e4f3d6d755016cb918b2b6158deda2a
|
[
"Python"
] | 1 |
Python
|
bventel/django-deployment-example
|
aa7e4dd36b2d41536a0d786c02b526f2a85e903f
|
83d507dda6b5ef0f673e303643519f4d940d05fb
|
refs/heads/master
|
<file_sep>/*
* 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.
*/
package com.salsamobi.university.repository;
import com.salsamobi.university.daoimpl.Student;
import java.util.HashMap;
/**
*
* @author adrianduran
*/
public class StudentRepository {
private HashMap<Long, Student> studentList;
private static StudentRepository studentRepository;
private StudentRepository(){
studentList = new HashMap<Long,Student>();
}
public static StudentRepository getInstance(){
if(studentRepository == null){
studentRepository = new StudentRepository();
}
return studentRepository;
}
public Student getStudent(long id) {
return studentList.get(id);
}
public void addStudent(Student student){
if(this.studentList.get(student.getId()) != null){
throw new RuntimeException("Can't add another student with the same id");
}
studentList.put(student.getId(), student);
}
public HashMap<Long,Student> getStudentList(){
return this.studentList;
}
}
<file_sep>package com.salsamobi.university.service;
import com.salsamobi.university.daoimpl.Student;
import com.salsamobi.university.repository.StudentRepository;
import java.util.HashMap;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("StudentService")
@Transactional
public class StudentService {
StudentRepository studentRepository;
public StudentService(){
super();
studentRepository = StudentRepository.getInstance();
}
public void saveStudent(Student student) {
studentRepository.addStudent(student);
}
public HashMap<Long, Student> getStudentList(){
return studentRepository.getStudentList();
}
}
<file_sep>package com.mountainview.dao;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import org.codehaus.jackson.annotate.JsonIgnore;
@Entity
public class Book implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@OneToMany(mappedBy = "book",cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<ReadedBook> readedbooks;
private String name;
public Book(String name) {
super();
this.name = name;
}
public Book() {
}
public long getId() {
return id;
}
public void setName(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Book [name=" + name + "]";
}
/**
* @return the books
*/
@JsonIgnore
public List<ReadedBook> getBooks() {
return readedbooks;
}
/**
* @param books the books to set
*/
public void setBooks(List<ReadedBook> books) {
this.readedbooks = books;
}
}
<file_sep>package com.mountainview.service;
import com.mountainview.dao.Student;
import com.mountainview.repository.StudentRepository;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("StudentService")
@Transactional
public class StudentService {
@Autowired
StudentRepository studentRepository;
public void saveCustomer(Student customer) {
studentRepository.save(customer);
}
public Student findStudentById(long id){
Student s = studentRepository.findStudentById(id);
return s;
}
public Student authenticateStudent(String username, String password){
Student s = studentRepository.findStudentByUsernameAndPassword(username, password);
return s;
}
public List<Student> listStudents() {
Iterable <Student> c = studentRepository.findAll();
List <Student> customers = new ArrayList<Student>();
Iterator<Student> cos = c.iterator();
while (cos.hasNext()) {
customers.add(cos.next());
}
return customers;
}
}
<file_sep>package com.mountainview.controller;
import com.mountainview.dao.Book;
import com.mountainview.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.RedirectView;
@Controller
public class BookController {
@Autowired
private BookService bookService;
@RequestMapping(value = "/book/save", method = RequestMethod.POST)
public View saveCustomer(@ModelAttribute Book book, ModelMap model) {
bookService.saveBook(book);
return new RedirectView("/customer");
}
}<file_sep>package com.salsamobi.university.controller;
import com.salsamobi.university.dao.Course;
import com.salsamobi.university.daoimpl.Student;
import com.salsamobi.university.daoimpl.Teacher;
import com.salsamobi.university.service.CourseService;
import com.salsamobi.university.service.StudentService;
import com.salsamobi.university.service.TeacherService;
import java.util.ArrayList;
import java.util.HashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.RequestParam;
@Controller
public class MainController {
@Autowired
CourseService courseService;
@Autowired
StudentService studentService;
@Autowired
TeacherService teacherService;
@RequestMapping(value = "/error", method = RequestMethod.GET)
public String error() {
return "/error";
}
@RequestMapping(value = "/createCourse", method = RequestMethod.GET)
public String createCourse(ModelMap model) {
model.addAttribute("availableCourses", courseService.getAvailableCourseTypes());
return "/createCourse";
}
@RequestMapping(value = "/createStudent", method = RequestMethod.GET)
public String createStudent(ModelMap model) {
return "/createStudent";
}
@RequestMapping(value = "/createTeacher", method = RequestMethod.GET)
public String createTeacher(ModelMap model) {
return "/createTeacher";
}
@RequestMapping(value = "/registerCourseStudent", method = RequestMethod.GET)
public String registerCourseStudent(ModelMap model) {
HashMap<Long,Course> courseList = courseService.getCoursesList();
model.addAttribute("courseList", courseList);
if(courseList.isEmpty()){
model.addAttribute("message", "You need to create at least one course first");
return "/error";
}
if(studentService.getStudentList().isEmpty()){
model.addAttribute("message", "You need to create at least one student first");
return "/error";
}
return "/registerCourseStudent";
}
@RequestMapping(value = "/registerCourseTeacher", method = RequestMethod.GET)
public String registerCourseTeacher(ModelMap model) {
HashMap<Long,Course> courseList = courseService.getCoursesList();
model.addAttribute("courseList", courseList);
if(courseList.isEmpty()){
model.addAttribute("message", "You need to create at least one course first");
return "/error";
}
if(teacherService.getTeacherList().isEmpty()){
model.addAttribute("message", "You need to create at least one teacher first");
return "/error";
}
return "/registerCourseTeacher";
}
@RequestMapping(value = "/report", method = RequestMethod.GET)
public String report(ModelMap model) {
model.addAttribute("courseList", courseService.getCoursesList());
return "/report";
}
@RequestMapping(value = "/registerCourseStudent/{courseId}", method = RequestMethod.GET)
public String registerCourseStudentWithCourse(ModelMap model, @PathVariable long courseId) {
Course course = courseService.getCoursesList().get(courseId);
HashMap<Long, Student> studentList = studentService.getStudentList();
ArrayList<Student> studentsOnCourse = new ArrayList<Student>();
ArrayList<Student> studentsFree = new ArrayList<Student>();
for(Student student : studentList.values()){
if(course.getStudentList().get(student.getId()) != null){
studentsOnCourse.add(student);
} else {
studentsFree.add(student);
}
}
model.addAttribute("studentList", studentsFree);
model.addAttribute("studentCourse", studentsOnCourse);
model.addAttribute("course", course);
return "/registerCourseStudent";
}
@RequestMapping(value = "/registerCourseTeacher/{courseId}", method = RequestMethod.GET)
public String registerCourseTeachertWithCourse(ModelMap model, @PathVariable long courseId) {
Course course = courseService.getCoursesList().get(courseId);
ArrayList<Teacher> teacherList = teacherService.getTeacherList();
model.addAttribute("teacherList", teacherList);
model.addAttribute("course", course);
return "/registerCourseTeacher";
}
}<file_sep>package com.mountainview.service;
import com.mountainview.BeanConfiguration;
import com.mountainview.dao.Book;
import com.mountainview.repository.BookRepository;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("BookService")
@Transactional
public class BookService {
@Autowired
BookRepository bookRepository;
public void saveBook(Book book) {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(BeanConfiguration.class);
BookRepository repository = context.getBean(BookRepository.class);
repository.save(book);
}
public Book findBookById(long book_id){
Book b = bookRepository.findBookById(book_id);
return b;
}
public List<Book> listBooks() {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(
BeanConfiguration.class);
BookRepository repository = context
.getBean(BookRepository.class);
Iterable <Book> c = repository.findAll();
List <Book> books = new ArrayList<Book>();
Iterator<Book> cos = c.iterator();
while (cos.hasNext()) {
books.add(cos.next());
}
return books;
}
}
<file_sep>package com.mountainview.dao;
import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import org.codehaus.jackson.annotate.JsonIgnore;
@Entity
public class Student implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@OneToMany(mappedBy = "student",cascade = CascadeType.ALL,fetch = FetchType.EAGER)
private List<ReadedBook> readedbooks;
private String name;
private String password;
private String username;
public Student(String name, String username, String password) {
super();
this.name = name;
this.password = <PASSWORD>;
this.username = username;
}
public Student() {
}
public long getId() {
return id;
}
public void setName(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@JsonIgnore
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "Student [name=" + name + ", address=" + password + "]";
}
/**
* @return the books
*/
@JsonIgnore
public List<ReadedBook> getBooks() {
return readedbooks;
}
/**
* @param books the books to set
*/
public void setBooks(List<ReadedBook> books) {
this.readedbooks = books;
}
/**
* @return the username
*/
public String getUsername() {
return username;
}
/**
* @param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
}
<file_sep>package com.salsamobi.university.service;
import com.salsamobi.university.daoimpl.Teacher;
import com.salsamobi.university.repository.TeacherRepository;
import java.util.ArrayList;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("TeacherService")
@Transactional
public class TeacherService {
TeacherRepository teacherRepository;
public TeacherService() {
super();
teacherRepository = TeacherRepository.getInstance();
}
public void saveTeacher(Teacher student) {
teacherRepository.addTeacher(student);
}
public ArrayList<Teacher> getTeacherList() {
return teacherRepository.getTeacherList();
}
}
<file_sep>package com.mountainview.controller;
import com.mountainview.dao.Book;
import com.mountainview.dao.ReadedBook;
import com.mountainview.dao.Student;
import com.mountainview.service.BookService;
import com.mountainview.service.ReadedBookService;
import com.mountainview.service.StudentService;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.RedirectView;
@Controller
public class ReadedBookController {
@Autowired
private BookService bookService;
@Autowired
private StudentService studentService;
@Autowired
private ReadedBookService readedBookService;
@RequestMapping("/viewBooksJSON")
public @ResponseBody List<ReadedBook> getBooksByStudent(ModelMap model,HttpSession session, @RequestParam("date") String date) {
Student student = (Student) session.getAttribute("currentStudent");
String startDate = date;
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date startDateParsed = null;
try {
startDateParsed = dateFormat.parse(startDate);
} catch (ParseException ex) {
Logger.getLogger(ReadedBookController.class.getName()).log(Level.SEVERE, null, ex);
}
List<ReadedBook> listReadedBooks = readedBookService.listBooksByStudentAndDateRange(student.getId(),startDateParsed);
return listReadedBooks;
}
@RequestMapping("/viewBooks")
public String start(ModelMap model){
return "/mainContent";
}
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public View logout(HttpSession session){
session.removeAttribute("currentStudent");
return new RedirectView("/mountainview/");
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public View login(HttpSession session, @RequestParam("username") String username, @RequestParam("password") String password){
if(studentService.findStudentById(1) == null){
studentService.saveCustomer(new Student("Administrator", "admin", "admin"));
}
Student student = studentService.authenticateStudent(username, password);
if(student != null){
session.setAttribute("currentStudent", student);
} else {
return new RedirectView("/?error=1");
}
return new RedirectView("/mountainview/viewBooks");
}
@RequestMapping(value = "/readedbook/save", method = RequestMethod.POST)
public View saveReadedBook(HttpSession session, @RequestParam("startdate") String startdate, @RequestParam("enddate") String enddate, @RequestParam("bookname") String bookname, ModelMap model) {
Student student = (Student) session.getAttribute("currentStudent");
Book book = new Book(bookname);
bookService.saveBook(book);
String startDate = startdate;
String endDate = enddate;
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date startDateParsed = null, endDateParsed = null;
try {
startDateParsed = dateFormat.parse(startDate);
endDateParsed = dateFormat.parse(endDate);
} catch (ParseException ex) {
Logger.getLogger(ReadedBookController.class.getName()).log(Level.SEVERE, null, ex);
}
ReadedBook readedBook = new ReadedBook(book,student,startDateParsed,endDateParsed);
readedBookService.saveReadedBook(readedBook);
return new RedirectView("/mountainview/viewBooks");
}
}
|
c90093b6fa1ae09932be0b713ee46c234f9b689f
|
[
"Java"
] | 10 |
Java
|
aduranv87/salsamobi
|
6901cb787328c6e0844b22a61a64ff990913c2f3
|
17ef11d88ffb376a30819c3e74d8086bfac7add5
|
refs/heads/first-example
|
<file_sep>export const SET_DATA = 'SET_DATA';
export function setData(data) {
console.log('===== 5 =====')
return {
type: SET_DATA,
data,
};
}<file_sep>import * as actions from './actions';
import { combineReducers } from 'redux';
function ProductInfo(state = {data: 0}, action) {
switch (action.type) {
case actions.SET_DATA: {
console.log('===== 6 =====')
return { ...state, data: action.data };
}
default: {
return state;
}
}
}
const reducer = combineReducers({
ProductInfo,
});
export default reducer;
|
50c9b5c4b189710159fa0f3dd382f50312beb25a
|
[
"JavaScript"
] | 2 |
JavaScript
|
v123582/react-redux-sample
|
381c905b0a5bfd91bb510b16bb7719a57108f34a
|
a0f6b73a933a2c4ccf5928699dbe1d6b75f68365
|
refs/heads/master
|
<file_sep>lista_inicial = ['im1 4,14', 'im2 33,15', 'im3 6,34', 'im4 410,134']
lista_nueva = []
print (lista_inicial)
for i in lista_inicial:
name, space, tupla = i.partition(" ")
x = int(tupla.split(',')[0]) #asignamos a x el primer valor de tupla y lo convertimos a int
y = int(tupla.split(',')[1]) #idem pero con y
tuple = (x,y) #Asignamos una variable tupla
lista_nueva.extend([tuple]) #agregamos tupla a la lista
print('sin orden:' ,lista_nueva)
print(sorted(lista_nueva))
# La dificultad que me surgio en este ejercicio, fue que al momento de comparar los numeros, para ordenarlos,
# solo utilizaba el primer digito, por lo tanto (en este caso), el numero mayor ('410,134') no quedaba en ultimo
# lugar. Entendi que el problema en la comparacion estaba en que el numero no era un entero, sino un string.
# Lo resolvi, copiando los valores dentro de una tupla y conviritiendolos a enteros. De esta forma la comparacion
# se pudo realizar.
|
49ce33f2d8dea71e7dc5dec8963b17640324696f
|
[
"Python"
] | 1 |
Python
|
robolfba/cualquiera
|
22f1033f84d00625641bd48a23a6e3a07f4e6023
|
5cedf40fc7eedee2b279a520e3cae2222519cdac
|
refs/heads/master
|
<repo_name>Xotabu4/api-integration-tests<file_sep>/test/1.ts
import * as chai from 'chai'
import { expect } from 'chai'
import chaiHttp = require('chai-http')
chai.use(chaiHttp);
//TODO: add global .use(errorMiddleware)
let errorMiddleware = function (request: ChaiHttp.Request) {
console.error('ERROR MIDDLEWARE WORKS')
return request.catch(err => {
console.log('GOT ERROR!')
//TODO: prepare nice Error object here.
throw err
})
};
describe('Suite 1', () => {
xit('valid songs', async () => {
var resp = await (chai.request('http://localhost:3032') as any)
.get('/songs?query=test').use(errorMiddleware)
expect(resp).to.have.status(200);
})
it('invalid songs', async () => {
let resp = (chai.request('http://localhost:3032') as any)
.get('/songs')
.use(errorMiddleware)
expect(resp).to.have.status(200);
})
})
|
2ac786bdaeb9af16401ed7fde49abd0744c9641c
|
[
"TypeScript"
] | 1 |
TypeScript
|
Xotabu4/api-integration-tests
|
ed25d04f3082162dc2186661d7e30b3ce1fbc907
|
2aeea011c4499e75853430cec2e726b2dd73b51f
|
refs/heads/master
|
<file_sep>import { Store } from 'redux';
import { Container } from 'inversify';
import {
ILogger,
LoggerFactory,
} from 'ts-smart-logger';
import { IEffectsAction } from './effects.interface';
export class EffectsService {
/**
* @stable [15.03.2020]
* @param {string} actionType
* @param {boolean} override
* @returns {(...args) => void}
*/
public static effects(actionType: string, override = false): (...args) => void {
return (target: { new(...args): void }, propertyKey: string): void => {
if (this.effectsMap.has(actionType)) {
if (override) {
this.logger.debug(`[$EffectsService] An effect does already exist for the action type ${actionType}. Will be overridden..`);
} else {
this.logger.warn(`[$EffectsService] An effect does already exist for the action type ${actionType}. Exit...`);
return;
}
}
this.addEffect(actionType, propertyKey, target);
};
}
/**
* @stable [10.01.2020]
* @param {string} type
* @returns {(...args) => {}}
*/
public static fromEffectsMap(type: string): (...args) => {} {
return this.effectsMap.get(type);
}
/**
* @stable [10.01.2020]
* @param {Container} $IoCContainer
* @param {Store<{}>} store
*/
public static configure($IoCContainer: Container, store: Store<{}>): void {
this.$IoCContainer = $IoCContainer;
this.store = store;
}
private static $IoCContainer: Container;
private static readonly effectsMap = new Map<string, (...args) => {}>();
private static readonly ERROR_ACTION_TYPE = '$$-REP-unhandled.error';
private static readonly logger = LoggerFactory.makeLogger(EffectsService);
private static store: Store<{}>;
/**
* @stable [10.01.2020]
* @param {string} actionType
* @param {string} propertyKey
* @param {{new(...args): void}} target
*/
private static addEffect(actionType: string, propertyKey: string, target: { new(...args): void }): void {
this.effectsMap.set(
actionType,
function(): IEffectsAction | IEffectsAction[] | Promise<IEffectsAction | IEffectsAction[]> {
const proxyObject = EffectsService.$IoCContainer.get(target.constructor);
const effectsFn = Reflect.get(proxyObject, propertyKey) as (...args) => {};
const currentState = EffectsService.store.getState();
const args = [...Array.from(arguments), currentState];
try {
return effectsFn.apply(proxyObject, args);
} catch (error) {
EffectsService.logger.error('[$EffectsService] The error:', error);
return {type: EffectsService.ERROR_ACTION_TYPE, error};
}
}
);
}
}
<file_sep>export * from './effects.action';
export * from './effects.middleware';
export * from './effects.service';
export * from './effects.interface';
export * from './effects-action.builder';
<file_sep>import { IEffectsAction } from './effects.interface';
export class EffectsAction<TData = unknown> implements IEffectsAction {
public static create<TData = unknown>(type: string, data?: TData): EffectsAction {
return new EffectsAction(type, data);
}
public data?: TData;
public error?: unknown;
public initialData?: unknown;
public initialType?: string;
public type: string;
constructor(type: string, data?: TData) {
this.type = type;
this.data = data;
}
public setData(data: TData): EffectsAction {
this.data = data;
return this;
}
public setError(error: unknown): EffectsAction {
this.error = error;
return this;
}
public setInitialData(initialData: unknown): EffectsAction {
this.initialData = initialData;
return this;
}
}
<file_sep>/**
* @stable [10.01.2020]
* @param value
* @returns {boolean}
*/
export const isFn = (value: any): boolean => typeof value === 'function';
/**
* @stable [10.01.2020]
* @param {AnyT} value
* @returns {boolean}
*/
export const isUndef = (value: any): boolean => typeof value === 'undefined';
/**
* @stable [10.01.2020]
* @param value
* @returns {boolean}
*/
export const isNil = (value: any): boolean => value === null;
/**
* @stable [10.01.2020]
* @param value
* @returns {boolean}
*/
export const isDefined = (value: any): boolean => !isNil(value) && !isUndef(value);
/**
* @stable [10.01.2020]
* @param value
* @returns {boolean}
*/
export const isPromiseLike = (value: any): boolean =>
value instanceof Promise || (
isDefined(value) && isFn(value.then) && isFn(value.catch)
);
<file_sep># redux-effects-promise
An implementation of declarative promises effects for redux. The solution is based on **inversify** library.
## Installation
```sh
npm install redux-effects-promise --save
```
## Dependencies
* [inversify](https://www.npmjs.com/package/inversify)
* [redux](https://www.npmjs.com/package/redux)
* [core-js](https://www.npmjs.com/package/core-js)
## Usage
```typescript
import 'reflect-metadata';
import { createStore } from 'redux';
import { Container } from 'inversify';
import { EffectsService, effectsMiddleware } from 'redux-effects-promise';
export const middlewares = [..., effectsMiddleware];
EffectsService.configure(new Container(), createStore(...));
```
```typescript
import { EffectsService } from 'redux-effects-promise';
...
@provide(DashboardListEffects)
export class DashboardListEffects {
...
@EffectsService.effects('dashboard.list.load')
loadProducts(): Promise<IProduct[]> {
return this.api.loadProducts();
}
// Or ...
// @EffectsService.effects('dashboard.list.load')
// loadProducts(): IProduct[] {
// return [{ name: 'Product1', id: 1901 }, { name: 'Product2', id: 1902 }];
// }
}
```
```typescript
import { AnyAction } from 'redux';
import { EffectsAction, EffectsService } from 'redux-effects-promise';
...
@provide(DashboardFormEffects)
export class DashboardFormEffects {
...
@EffectsService.effects('dashboard.form.submit')
saveProduct(action: AnyAction, state: IAppState): Promise<EffectsAction[]> {
return this.api.saveProduct(action.data)
.then(result => {
return [
EffectsAction.create('dashboard.form.submit.done', result),
EffectsAction.create('dashboard.list.update', action.data),
EffectsAction.create('dashboard.back', action.data) // Parameter1=action.data
];
});
}
@EffectsService.effects('dashboard.back')
back(): EffectsAction[] {
// A inheriting of the parameters works finely so input parameter
// "Parameter1" would pass within an action = { type: ..., data: ..., initialData: Parameter1 }
return [
EffectsAction.create('dashboard.list.deselect'),
EffectsAction.create('router.navigate', '/dashboard')
];
}
}
```
## Preview

## License
Licensed under MIT.<file_sep>export class EffectsActionBuilder {
public static buildDoneActionType(type: string): string {
return `${type}.done`;
}
public static buildErrorActionType(type: string): string {
return `${type}.error`;
}
}
<file_sep>import { MiddlewareAPI } from 'redux';
import { EffectsAction } from './effects.action';
import { EffectsActionBuilder } from './effects-action.builder';
import { EffectsService } from './effects.service';
import {
IEffectsAction,
IEffectsMiddlewareAPI,
} from './effects.interface';
import {
isDefined,
isFn,
isPromiseLike,
} from './effects.utils';
/**
* @stable [10.01.2020]
* @param {IEffectsAction} action
* @param result
* @returns {IEffectsAction[]}
*/
const toActions = (action: IEffectsAction, result): IEffectsAction[] => {
const initialData = action.data;
const initialType = action.initialType;
let chainedActions: IEffectsAction[];
if (Array.isArray(result)) {
chainedActions = result
.filter((resultItem) => resultItem instanceof EffectsAction)
.map((resultAction: IEffectsAction): IEffectsAction => ({...resultAction, initialData, initialType}));
if (chainedActions.length > 0) {
// Return chained effects actions
return chainedActions;
}
} else if (result instanceof EffectsAction) {
// Return chained effects action
return [{...result, initialData, initialType}];
}
return [
// Default result done action
{
type: EffectsActionBuilder.buildDoneActionType(action.type),
data: result,
initialData,
initialType,
}
];
};
/**
* @stable [10.01.2020]
* @param {MiddlewareAPI<TState>} payload
* @returns {(next: (action: IEffectsAction) => IEffectsAction) => (initialAction: IEffectsAction) => (IEffectsAction | undefined)}
*/
export const effectsMiddleware = <TState>(payload: MiddlewareAPI<TState>) => (
(next: <TAction extends IEffectsAction>(action: TAction) => TAction) => <TAction extends IEffectsAction>(initialAction: TAction) => {
const {dispatch} = payload as IEffectsMiddlewareAPI;
const proxy = EffectsService.fromEffectsMap(initialAction.type);
if (!isFn(proxy)) {
// Native redux behavior (!)
return next(initialAction);
}
const initialData = initialAction.data;
const initialType = initialAction.type;
const proxyResult = proxy(initialAction);
if (!isDefined(proxyResult)) {
// Stop chaining. An effect does return nothing (!)
return next(initialAction);
}
const nextActionResult = next(initialAction);
const dispatchCallback = ($nextAction: IEffectsAction) => dispatch({...$nextAction, initialData, initialType});
if (isPromiseLike(proxyResult)) {
// Bluebird Promise supporting
// An effect does return a promise object - we should build the async chain (!)
(proxyResult as Promise<{}>)
.then(
(result) => toActions(initialAction, result).forEach(dispatchCallback),
(error) => dispatch({type: EffectsActionBuilder.buildErrorActionType(initialAction.type), error, initialData, initialType})
);
} else {
toActions(initialAction, proxyResult).forEach(dispatchCallback);
}
return nextActionResult;
});
<file_sep>import { Action } from 'redux';
/**
* @stable [23.01.2021]
*/
export interface IEffectsAction<TData = unknown,
TInitialData = unknown,
TError = unknown>
extends Action {
data?: TData;
error?: TError;
initialData?: TInitialData;
initialType?: string;
}
/**
* @stable [23.01.2021]
*/
export interface IEffectsMiddlewareAPI {
dispatch: (action: IEffectsAction) => IEffectsAction;
}
|
0e7f49c6aa522af535acc729117f7836857b8f7a
|
[
"Markdown",
"TypeScript"
] | 8 |
TypeScript
|
apoterenko/redux-effects-promise
|
4998fe6da0df32097623889fc4c6487554c1ddb7
|
db2b5eb44c136de423ee1dd922f2ac04b6963910
|
refs/heads/master
|
<file_sep>package com.fdh.simulator.utils;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.fdh.simulator.Simulator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Utils {
private static final Logger logger = LoggerFactory.getLogger(Simulator.class);
public static final int HEAD_LENGHT = 16;
public static String getNowDate() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
String dateString = formatter.format(currentTime);
return dateString;
}
/**
* BCD字节数组===>String
*
* @param bytes
* @return 十进制字符串
*/
public static String bcd2String(byte[] bytes) {
StringBuilder temp = new StringBuilder(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
// 高四位
temp.append((bytes[i] & 0xf0) >>> 4);
// 低四位
temp.append(bytes[i] & 0x0f);
}
return temp.toString().substring(0, 1).equalsIgnoreCase("0") ? temp.toString().substring(1) : temp.toString();
}
/**
* @param
* @return String
* @Description: TODO
*/
public static String bytesToHexString(byte[] src, int datalength) {
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < datalength; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv).append(" ");
}
return stringBuilder.toString();
}
/**
* 从第start开始到end,包含end计算bcc校验位
* @param data
* @param start
* @param end
* @return
*/
public static byte getBCCByteFromStart2End(byte[] data, int start, int end) {
byte bcc = 0;
if (start >= end) {
return bcc;
}
for (int i = start; i <= end; i++) {
bcc = (byte) (bcc ^ data[i]);
}
return bcc;
}
/**
* 接收消息时转义<br>
*
* <pre>
* 0x7d01 <====> 0x7d
* 0x7d02 <====> 0x7e
* </pre>
*
* @param bs 要转义的字节数组
* @param start 起始索引
* @param end 结束索引
* @return 转义后的字节数组
* @throws Exception
*/
public static byte[] doEscape4Receive(byte[] bs, int start, int end) throws Exception {
if (start < 0 || end > bs.length)
throw new ArrayIndexOutOfBoundsException("doEscape4Receive error : index out of bounds(start=" + start
+ ",end=" + end + ",bytes length=" + bs.length + ")");
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
for (int i = 0; i < start; i++) {
baos.write(bs[i]);
}
for (int i = start; i < end; i++) {
if (bs[i] == 0x7d && bs[i + 1] == 0x01) {
baos.write(0x7d);
i++;
continue;
} else if (bs[i] == 0x7d && bs[i + 1] == 0x02) {
baos.write(0x7e);
i++;
continue;
} else {
baos.write(bs[i]);
continue;
}
}
for (int i = end; i < bs.length; i++) {
baos.write(bs[i]);
}
return baos.toByteArray();
} catch (Exception e) {
throw e;
} finally {
if (baos != null) {
baos.close();
baos = null;
}
}
}
/**
* 字符串==>BCD字节数组
*
* @param str
* @return BCD字节数组
*/
public static byte[] string2Bcd(String str) {
// 奇数,前补零
if ((str.length() & 0x1) == 1) {
str = "0" + str;
}
byte ret[] = new byte[str.length() / 2];
byte bs[] = str.getBytes();
for (int i = 0; i < ret.length; i++) {
byte high = ascII2Bcd(bs[2 * i]);
byte low = ascII2Bcd(bs[2 * i + 1]);
// TODO 只遮罩BCD低四位?
ret[i] = (byte) ((high << 4) | low);
}
return ret;
}
private static byte ascII2Bcd(byte asc) {
if ((asc >= '0') && (asc <= '9'))
return (byte) (asc - '0');
else if ((asc >= 'A') && (asc <= 'F'))
return (byte) (asc - 'A' + 10);
else if ((asc >= 'a') && (asc <= 'f'))
return (byte) (asc - 'a' + 10);
else
return (byte) (asc - 48);
}
/**
*
* 发送消息时转义<br>
*
* <pre>
* 0x7e <====> 0x7d02
* </pre>
*
* @param bs
* 要转义的字节数组
* @param start
* 起始索引
* @param end
* 结束索引
* @return 转义后的字节数组
* @throws Exception
*/
public static byte[] doEscape4Send(byte[] bs, int start, int end) throws Exception {
if (start < 0 || end > bs.length)
throw new ArrayIndexOutOfBoundsException("doEscape4Send error : index out of bounds(start=" + start
+ ",end=" + end + ",bytes length=" + bs.length + ")");
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
for (int i = 0; i < start; i++) {
baos.write(bs[i]);
}
for (int i = start; i < end; i++) {
if(bs[i] == 0x7d){
baos.write(0x7d);
baos.write(0x01);
continue;
}else if (bs[i] == 0x7e) {
baos.write(0x7d);
baos.write(0x02);
continue;
} else {
baos.write(bs[i]);
continue;
}
}
for (int i = end; i < bs.length; i++) {
baos.write(bs[i]);
}
return baos.toByteArray();
} catch (Exception e) {
throw e;
} finally {
if (baos != null) {
baos.close();
baos = null;
}
}
}
}
<file_sep>package com.fdh.simulator;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
public class DemoBeans {
private String demoName;
PropertyChangeSupport listeners = new PropertyChangeSupport(this);
public DemoBeans() {
demoName = "initValue";
}
public String getDemoName() {
return demoName;
}
public void setDemoName(String demoName) {
String oldValue = this.demoName;
this.demoName = demoName;
//发布监听事件
firePropertyChange("demoName", oldValue, demoName);
// new IdleStateHandler(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds)
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
listeners.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener){
listeners.addPropertyChangeListener(listener);
}
/**
* 触发属性改变的事件
*/
protected void firePropertyChange(String prop, Object oldValue, Object newValue) {
listeners.firePropertyChange(prop, oldValue, newValue);
}
} <file_sep>package com.fdh.simulator;
import com.fdh.simulator.utils.SpringContextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.IOException;
import java.util.Scanner;
public class StartSimulator {
private static final Logger logger = LoggerFactory.getLogger(StartSimulator.class);
public static void main(String[] args) {
//加载spring配置文件
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring/spring-base.xml");
ctx.start();
Scanner scanner = new Scanner(System.in);//接收键盘输入的数据
System.out.println("**************请输入数字1开始测试**************");
while (scanner.hasNext()) {//现在有输入数据
int data = scanner.nextInt();
if (data == 1) {
Simulator simulator = SpringContextUtils.getBean("simulator");
simulator.connect();
break;
} else {
System.out.println("输入有误!");
}
}
}
}
<file_sep>/*
* 文件名: IDictsEnumTag.java
*
* 创建日期: 2016年11月28日
*
* Copyright(C) 2016, by <a href="mailto:<EMAIL>">liws</a>.
*
* 原始作者: liws
*
*/
package com.fdh.simulator.constant;
import java.io.Serializable;
/**
* 单字节 枚举 字典类型 接口
*
* @author <a href="mailto:<EMAIL>">liws</a>
*
* @version $Revision$
*
* @since 2016年11月28日
*/
public interface IDictsEnumTag extends Serializable{
String getK();
byte getV();
IDictsEnumTag valueOf(byte pByte);
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.fdh.simulator.utils;
/**
*
* @author wangcz
*/
public class ByteList {
private byte[] array;
private int increaseSize;
protected int _size;
public int getSize() {
return _size;
}
public int getCapacity() {
return array.length;
}
public ByteList() {
this(10, 10);
}
public ByteList(int initialSize, int increaseSize) {
array = new byte[initialSize];
this.increaseSize = increaseSize;
_size = 0;
}
public void add(byte data) {
if (_size >= array.length) {
byte[] arrayN = new byte[array.length + increaseSize];
System.arraycopy(array, 0, arrayN, 0, array.length);
array = arrayN;
}
array[_size++] = data;
}
public final byte get(int index) {
return array[index];
}
public final void clear() {
_size = 0;
}
public byte[] getArray() {
final byte[] a = new byte[_size];
System.arraycopy(array, 0, a, 0, _size);
return a;
}
public void setCapacity(int newCapacity) {
increaseSize = Math.max(increaseSize, newCapacity);
final byte[] newArray = new byte[increaseSize];
_size = Math.min(increaseSize, _size);
System.arraycopy(array, 0, newArray, 0, _size);
array = newArray;
}
public void addArray(byte[] a) {
if (_size + a.length > array.length) {
setCapacity(_size + a.length);
}
System.arraycopy(a, 0, array, _size, a.length);
_size += a.length;
}
public void setArray(byte[] a) {
if (array.length < a.length) {
setCapacity(a.length);
}
System.arraycopy(a, 0, array, 0, a.length);
_size = a.length;
}
@Override
public ByteList clone() {
ByteList a = new ByteList();
a.setArray(this.getArray());
return a;
}
}
<file_sep>package com.fdh.simulator;
import java.util.Timer;
import java.util.TimerTask;
import com.fdh.simulator.utils.BuildPacketService;
import com.fdh.simulator.task.ConnectTask;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
public class Simulator {
private ThreadPoolTaskExecutor taskExecutor;
public static Timer timer;
private String address;
private int port;
private int sendInterval;
private int tcpConnections;
private TimerTask timerTask;
private static final Logger logger = LoggerFactory.getLogger(Simulator.class);
public Simulator() {
}
public void connect() {
logger.info("设置的连接数为:" + tcpConnections);
EventLoopGroup workgroup = new NioEventLoopGroup(60);
for (int i = 0; i < tcpConnections; i++) {
new Thread(new ConnectTask(address, port, i, workgroup)).start();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 处理实时报文发送,等待登陆完成立马发送数据
*/
timer = new Timer();
timer.schedule(timerTask, 0, sendInterval);
}
public ThreadPoolTaskExecutor getTaskExecutor() {
return taskExecutor;
}
public void setTaskExecutor(ThreadPoolTaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
public static Timer getTimer() {
return timer;
}
public static void setTimer(Timer timer) {
Simulator.timer = timer;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public int getSendInterval() {
return sendInterval;
}
public void setSendInterval(int sendInterval) {
this.sendInterval = sendInterval;
}
public int getTcpConnections() {
return tcpConnections;
}
public void setTcpConnections(int tcpConnections) {
this.tcpConnections = tcpConnections;
}
public TimerTask getTimerTask() {
return timerTask;
}
public void setTimerTask(TimerTask timerTask) {
this.timerTask = timerTask;
}
public static Logger getLogger() {
return logger;
}
}
<file_sep>package com.fdh.simulator.model;
import com.fdh.simulator.constant.CommandTagEnum;
import lombok.Data;
/**
* @author fudh
* @ClassNmme Tbox
* @date 2019/1/28 11:28
* @Description: 解析808平台通用应答
*/
public class Tbox {
/**
* 设备号
*/
private String deviceCode;
/**
* 应答命令字
*/
private CommandTagEnum commandTagEnum;
/**
* 应答流水号
*/
private Short serialNum;
/**
* 应答结果
*/
private byte ret;
public String getDeviceCode() {
return deviceCode;
}
public void setDeviceCode(String deviceCode) {
this.deviceCode = deviceCode;
}
public CommandTagEnum getCommandTagEnum() {
return commandTagEnum;
}
public void setCommandTagEnum(CommandTagEnum commandTagEnum) {
this.commandTagEnum = commandTagEnum;
}
public Short getSerialNum() {
return serialNum;
}
public void setSerialNum(Short serialNum) {
this.serialNum = serialNum;
}
public byte getRet() {
return ret;
}
public void setRet(byte ret) {
this.ret = ret;
}
@Override
public String toString() {
return "Tbox{" +
"deviceCode='" + deviceCode + '\'' +
", commandTagEnum=" + commandTagEnum +
", serialNum=" + serialNum +
", ret=" + ret +
'}';
}
}
<file_sep>package com.fdh.simulator.utils;
/**
* @author fudh
* @ClassNmme ByteUtils
* @date 2019/1/19 15:24
* @Description: TODO
*/
public class ByteUtils {
public static byte[] hexToByteArray(String inHex){
int hexlen = inHex.length();
byte[] result;
if (hexlen % 2 == 1){
//奇数
hexlen++;
result = new byte[(hexlen/2)];
inHex="0"+inHex;
}else {
//偶数
result = new byte[(hexlen/2)];
}
int j=0;
for (int i = 0; i < hexlen; i+=2){
result[j]=hexToByte(inHex.substring(i,i+2));
j++;
}
return result;
}
public static byte hexToByte(String inHex){
return (byte)Integer.parseInt(inHex,16);
}
/**
* bcc 异或校验返回byte
*
* @param bytes
* @return
*/
public static byte bccEncode(byte[] bytes) {
byte retByte = 0;
if (bytes == null || bytes.length <= 0) {
return retByte;
}
retByte = bytes[0];
for (int i = 1; i < bytes.length; i++) {
retByte ^= bytes[i];
}
return retByte;
}
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString().toUpperCase();
}
/**
* 根据start和end截取byte数组
*
* @param src
* @param start
* @param end
* @return
*/
public static byte[] subBytes(byte[] src, int start, int end) {
if (src == null || start > end || start < 0 || end > src.length) {
return src;
}
byte[] ret = new byte[end - start];
System.arraycopy(src, start, ret, 0, end - start);
return ret;
}
/**
* 转换short为byte
*
* @param src 需要转换的short
*/
public static byte[] getShortBytes(short src) {
byte[] ret = new byte[2];
ret[0] = (byte) (src >> 8);
ret[1] = (byte) (src >> 0);
return ret;
}
/**
* 通过byte数组取到short
*
* @param b
* @param index 第几位开始取
* @return
*/
public static short getShort(byte[] b, int index) {
return (short) (((b[index + 0] << 8) | b[index + 1] & 0xff));
}
/**
* 转换int为byte数组
*
* @param x
*/
public static byte[] getIntegerByte(Integer x) {
byte[] bb = new byte[4];
bb[0] = (byte) (x >> 24);
bb[1] = (byte) (x >> 16);
bb[2] = (byte) (x >> 8);
bb[3] = (byte) (x >> 0);
return bb;
}
/**
* 通过byte数组取到int
*
* @param bb
* @param index 第几位开始
* @return
*/
public static int getInt(byte[] bb, int index) {
return (int) ((((bb[index + 0] & 0xff) << 24)
| ((bb[index + 1] & 0xff) << 16)
| ((bb[index + 2] & 0xff) << 8) | ((bb[index + 3] & 0xff) << 0)));
}
// public static void main(String[] args) {
// 232307FE 4C4E42534342334658595A313030303031 01 0004 00 00 00 02 C2
// int anInt = getInt(new byte[]{0x07, 0x5B, (byte) 0xCD, 0x15},0);
// System.out.println(anInt);
// }
// public static int parseSerialNum(byte[] packet){
//
// }
/**
* 转换long型为byte数组
*
* @param x
*/
public static byte[] putLong(long x) {
byte[] bb = new byte[8];
bb[0] = (byte) (x >> 56);
bb[1] = (byte) (x >> 48);
bb[2] = (byte) (x >> 40);
bb[3] = (byte) (x >> 32);
bb[4] = (byte) (x >> 24);
bb[5] = (byte) (x >> 16);
bb[6] = (byte) (x >> 8);
bb[7] = (byte) (x >> 0);
return bb;
}
/**
* 通过byte数组取到long
*
* @param bb
* @param index
* @return
*/
public static long getLong(byte[] bb, int index) {
return ((((long) bb[index + 0] & 0xff) << 56)
| (((long) bb[index + 1] & 0xff) << 48)
| (((long) bb[index + 2] & 0xff) << 40)
| (((long) bb[index + 3] & 0xff) << 32)
| (((long) bb[index + 4] & 0xff) << 24)
| (((long) bb[index + 5] & 0xff) << 16)
| (((long) bb[index + 6] & 0xff) << 8) | (((long) bb[index + 7] & 0xff) << 0));
}
public static void main(String[] args) {
// byte[] aa = {0x23, 0x23, 0x07, (byte) 0xFE, 0x4C, 0x4E, 0x42, 0x53, 0x43, 0x42, 0x33, 0x46, 0x58, 0x59, 0x5A, 0x31, 0x30, 0x30, 0x30, 0x30, 0x31, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x02, (byte) 0xC2};
// int bb = getInt(aa, 24);
// byte[] bytes = putLong(System.currentTimeMillis());
// System.out.println(ByteUtils.bytesToHexString(bytes));
// byte[] a = {0x23,0x23, (byte) 0xDC,0x01,0x36,0x36,0x31,0x44,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x32,0x01,0x00,0x0C,
// 0x13,0x01,0x19,0x0E,0x1D,0x09,0x00,0x01,0x00,0x00,0x00,0x00, (byte) 0x87};
// String vin = parseByte2Vin(a);
// System.out.println(vin);
}
}
<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.fdh</groupId>
<artifactId>virtualtbox</artifactId>
<version>0.0.1</version>
<packaging>jar</packaging>
<name>virtualTbox</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring_version>4.3.21.RELEASE</spring_version>
<slf4j.version>1.7.25</slf4j.version>
<log4j.version>2.8.2</log4j.version>
<lombok.version>1.16.20</lombok.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.jodah</groupId>
<artifactId>expiringmap</artifactId>
<version>0.5.8</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.21.Final</version>
</dependency>
<!-- spring相关依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring_version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring_version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring_version}</version>
</dependency>
<!--log4j2相关依赖-->
<!--1、slf4j核心包-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!--2、log4j2的api接口包-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<!--3、log4j2的核心包-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
<!--4、slf4j对应log4j2日志框架的实现包-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- 5、使用异步写日志功能 必须引入此包-->
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>3.3.6</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.10-FINAL</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
</dependencies>
<build>
<resources>
<!-- 先指定 src/main/resources下所有文件及文件夹为资源文件 -->
<resource>
<directory>src/main/resources</directory>
<!--<targetPath>${project.build.directory}/classes</targetPath>-->
<excludes>
<exclude>/**/config.properties</exclude>
</excludes>
<filtering>true</filtering>
</resource>
<!--根据env部署环境值,把对应环境的配置文件拷贝到classes目录-->
<resource>
<directory>src/main/resources/config/</directory>
<targetPath>${project.build.directory}/classes</targetPath>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<!--<plugin>-->
<!--<groupId>org.apache.maven.plugins</groupId>-->
<!--<artifactId>maven-compiler-plugin</artifactId>-->
<!--<version>2.4</version>-->
<!--<configuration>-->
<!--<excludes>-->
<!--<!–注意这玩意从编译结果目录开始算目录结构–>-->
<!--<exclude>/**/*.properties</exclude>-->
<!--</excludes>-->
<!--</configuration>-->
<!--</plugin>-->
<!-- The configuration of maven-assembly-plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.4</version>
<!--The configuration of the plugin-->
<configuration>
<!--Specifies the configuration file of the assembly plugin-->
<descriptors>
<descriptor>src/main/assembly/package.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>appassembler-maven-plugin</artifactId>
<version>1.10</version>
<configuration>
<!-- 生成配置文件路径 -->
<configurationDirectory>bin</configurationDirectory>
<!-- Copy the contents from "/src/main/config" to the target configuration
directory in the assembled application -->
<!-- <copyConfigurationDirectory>true</copyConfigurationDirectory> -->
<!-- repositoryName:依赖包目录,默认repo -->
<repositoryName>lib</repositoryName>
<!-- Include the target configuration directory in the beginning of
the classpath declaration in the bin scripts -->
<includeConfigurationDirectoryInClasspath>true</includeConfigurationDirectoryInClasspath>
<!-- 配置文件的目标目录 -->
<configurationDirectory>conf</configurationDirectory>
<!-- 拷贝配置文件到上面的目录中 -->
<copyConfigurationDirectory>true</copyConfigurationDirectory>
<!-- 从哪里拷贝配置文件 (默认src/main/config) -->
<configurationSourceDirectory>src/main/resources/config</configurationSourceDirectory>
<!-- set alternative assemble directory -->
<assembleDirectory>${project.build.directory}/TBOX-assemble</assembleDirectory>
<!-- Extra JVM arguments that will be included in the bin scripts -->
<extraJvmArguments>-Xms128m</extraJvmArguments>
<binFileExtensions>
<unix>.sh</unix>
</binFileExtensions>
<!-- Generate bin scripts for windows and unix pr default -->
<platforms>
<platform>windows</platform>
<platform>unix</platform>
</platforms>
<programs>
<program>
<mainClass>com.fdh.simulator.StartSimulator</mainClass>
<id>virtualtbox</id>
</program>
</programs>
</configuration>
</plugin>
</plugins>
</build>
</project>
<file_sep>package com.fdh.simulator.task;
import com.fdh.simulator.codec.CustomerDelimiterBasedFrameDecoder;
import com.fdh.simulator.codec.StreamByteDecoder;
import com.fdh.simulator.codec.StreamByteEncoder;
import com.fdh.simulator.handler.SimulatorHandler;
import com.fdh.simulator.NettyChannelManager;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author fudh
* @ClassNmme ConnectTask
* @date 2019/1/15 15:43
* @Description: TODO
*/
public class ConnectTask implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(ConnectTask.class);
private String address;
private int port;
private Integer taskId;
private EventLoopGroup workgroup;
//报文分隔符
ByteBuf delimiter = Unpooled.copiedBuffer(new byte[]{0x7E});
public ConnectTask(String address, int port, Integer taskId, EventLoopGroup workgroup) {
this.address = address;
this.port = port;
this.taskId = taskId;
this.workgroup = workgroup;
}
@Override
public void run() {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(workgroup);
// 指定连接通道类型
bootstrap.channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);// TCP 连接保活机制,2小时监测一次
// 接收缓冲区,最小32直接,初始是1500字节,最大65535字节
bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(32, 1500, 65536));
bootstrap.option(ChannelOption.TCP_NODELAY, true);
bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,15000);
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new StreamByteEncoder());//解码
ch.pipeline().addLast(new CustomerDelimiterBasedFrameDecoder(2048, false, delimiter));//解码
ch.pipeline().addLast(new SimulatorHandler());
}
});
// 异步等待连接成功
ChannelFuture connectFuture = null;
try {
// Start the client.
connectFuture = bootstrap.connect(address, port).sync();
connectFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
logger.error("连接失败!" ,e);
}catch (Exception e){
logger.error("连接或关闭出现异常" ,e);
}
}
}
<file_sep>package com.fdh.simulator;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
//监听属性变化的类
DemoBeans beans = new DemoBeans();
beans.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
System.out.println("OldValue:" + evt.getOldValue());
System.out.println("NewValue:" + evt.getNewValue());
System.out.println("tPropertyName:" + evt.getPropertyName());
}
});
beans.setDemoName("test");
}
}
<file_sep>/*
* 文件名: ReportObjEncoder.java
*
* 创建日期: 2016年11月29日
*
* Copyright(C) 2016, by <a href="mailto:<EMAIL>">liws</a>.
*
* 原始作者: liws
*
*/
package com.fdh.simulator.codec;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
/**
* 上报消息 编码器
*
* @author <a href="mailto:<EMAIL>">liws</a>
*
* @version $Revision$
*
* @since 2016年11月29日
*/
public class StreamByteEncoder extends MessageToByteEncoder<byte[]> {
private static final Logger logger = LoggerFactory.getLogger(StreamByteEncoder.class);
/**
*
* @see io.netty.handler.codec.MessageToByteEncoder#encode(io.netty.channel.ChannelHandlerContext, Object, io.netty.buffer.ByteBuf)
*/
@Override
protected void encode(ChannelHandlerContext ctx, byte[] obj, ByteBuf bytebuf) {
try{
bytebuf.writeBytes(obj);
}catch (Exception e) {
logger.error(e.getMessage(),e);
}finally {
// ReferenceCountUtil.release(bytebuf);
}
}
}
|
0f4770b4c6027b960e58197e8e56ad183908c5c3
|
[
"Java",
"Maven POM"
] | 12 |
Java
|
endlessc/virtualTbox
|
64086854bb3851f86eba6ab9b3b0d856acd23048
|
98d2a9d7d5eaddbb6b4fa360b6ba545a7e287931
|
refs/heads/master
|
<repo_name>Msalpdogan/Asp.Net_Mvc_News_Portal<file_sep>/Models/haber.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace obajans.Models
{
public class haber
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
public string baslik { get; set; }
public string konu { get; set; }
public string resimuri { get; set; }
public string icerik { get; set; }
public DateTime yayıntarihi { get; set; }
public string aciklama { get; set; }
public string kaynak { get; set; }
public string originnew { get; set; }
}
}<file_sep>/Models/datacontext.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace obajans.Models
{
public class datacontext : DbContext
{
public DbSet<haber> haberler { get; set; }
public datacontext()
{
Database.SetInitializer(new Veritabaniolusturucu());
}
}
public class Veritabaniolusturucu : CreateDatabaseIfNotExists<datacontext>
{
protected override void Seed(datacontext context)
{
haber habernesne = new haber();
habernesne.yayıntarihi = DateTime.Now.Date;
habernesne.baslik = "Deneme Baslik";
habernesne.konu = "Deneme Konu";
habernesne.icerik = "deneme icerik";
habernesne.resimuri = "https://www.thesun.co.uk/wp-content/uploads/2018/06/NINTCHDBPICT000415544999.jpg?strip=all&w=960";
habernesne.aciklama = "Deneme aciklama";
habernesne.kaynak = "The sun news";
habernesne.originnew = "https://www.thesun.co.uk/news/6611695/who-muharrem-ince-turkey-challenge-recep-erdogan-2018-election/";
context.haberler.Add(habernesne);
context.SaveChanges();
}
}
}<file_sep>/Controllers/XmlController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace obajans.Controllers
{
public class XmlController : Controller
{
// GET: Xml
public ContentResult Index()
{
string xml = System.IO.File.ReadAllText(Server.MapPath("~/sitemap.xml"));
return Content(xml);
}
}
}<file_sep>/Models/Element.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace obajans.Models
{
public class Element
{
public string GetBeforeElement(HtmlString id)
{
try
{
int tempid = int.Parse(id.ToString());
datacontext db = new datacontext();
// return (db.haberler.Where(p => p.id < Convert.ToInt16(id)).OrderByDescending(p => p.id).FirstOrDefault().id);
return "./"+db.haberler.Where(p => p.id < tempid).OrderByDescending(p => p.id).FirstOrDefault().id.ToString();
}
catch (Exception)
{
return "./1";
throw;
}
}
public int GetFirstElement()
{
try
{
datacontext db = new datacontext();
return db.haberler.OrderBy(p => p.id).FirstOrDefault().id;
}
catch (Exception)
{
return 1;
throw;
}
}
public int GetLastElement()
{
try
{
datacontext db = new datacontext();
return db.haberler.OrderByDescending(p => p.id).FirstOrDefault().id;
}
catch (Exception)
{
return 1;
throw;
}
}
public string GetAfterElement(HtmlString id)
{
try
{
int tempid = int.Parse(id.ToString());
datacontext db = new datacontext();
return "./"+db.haberler.Where(p => p.id > tempid).OrderBy(p => p.id).FirstOrDefault().id.ToString();
}
catch (Exception)
{
//En son elementten sonrası bulunamadı
return "./1";
throw;
}
}
public string GetAfterPic(HtmlString id)
{
try
{
int tempid = int.Parse(id.ToString());
datacontext db = new datacontext();
return db.haberler.Where(p => p.id > tempid).OrderBy(p => p.id).FirstOrDefault().resimuri.ToString();
}
catch (Exception)
{
//En son elementten sonrası bulunamadı
return "~~/Content/images/logo.png";
throw;
}
}
public string GetBeforePics(HtmlString id)
{
try
{
int tempid = int.Parse(id.ToString());
datacontext db = new datacontext();
// return (db.haberler.Where(p => p.id < Convert.ToInt16(id)).OrderByDescending(p => p.id).FirstOrDefault().id);
return db.haberler.Where(p => p.id < tempid).OrderByDescending(p => p.id).FirstOrDefault().resimuri.ToString();
}
catch (Exception)
{
return "~~/Content/images/logo.png";
throw;
}
}
public int[,] Pagelist(int pageNow,int manyPage)
{
manyPage = (manyPage / 14)+1 ;
int ononce = 0;int uconce = 0;int bironce = 0; int birsonra = 0;int ucsonra = 0;int onsonra = 0;
if ((pageNow - 10)>0) { ononce = 1; }
if ((pageNow - 3) > 0) { uconce = 1; }
if ((pageNow - 1) > 0) { bironce = 1; }
if ((pageNow +1 ) <= manyPage) { birsonra = 1; }
if ((pageNow + 3) <= manyPage) { ucsonra = 1; }
if ((pageNow + 10) <= manyPage) { onsonra = 1; }
return new int[,] { { pageNow-10, ononce }, { pageNow - 3, uconce }, { pageNow - 1, bironce }, { (pageNow + 1), birsonra }, { (pageNow + 3), ucsonra }, { (pageNow + 10), onsonra } };
}
}
}<file_sep>/Controllers/ErrorController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace obajans.Controllers
{
public class ErrorController : Controller
{
// GET: Error
public ActionResult PageError()
{
Response.TrySkipIisCustomErrors = true;
return View();
}
public ActionResult NotFound()
{
return View();
}
public ActionResult Page404()
{
Response.StatusCode = 404;
Response.TrySkipIisCustomErrors = true;
return View("PageError");
}
public ActionResult Page403()
{
Response.StatusCode = 403;
Response.TrySkipIisCustomErrors = true;
return View("PageError");
}
public ActionResult Page500()
{
Response.StatusCode = 500;
Response.TrySkipIisCustomErrors = true;
return View("PageError");
}
}
}<file_sep>/Models/ortakmodel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace obajans.Models
{
public class ortakmodel
{
public List<haber> haber { get; set; }
}
}<file_sep>/App_Start/RouteConfig.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace obajans
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{page}",
defaults: new { controller = "default", action = "Index", page=1, category = "asda" }
);
routes.MapRoute(
name: "Default2",
url: "Siyaset/{page}",
defaults: new { controller = "default", action = "Index",category="siyaset" }
);
routes.MapRoute(
name: "Default21",
url: "Spor/{page}",
defaults: new { controller = "default", action = "Index",category="spor" }
);
routes.MapRoute(
name: "Default22",
url: "Para/{page}",
defaults: new { controller = "default", action = "Index" ,category="para" }
);
routes.MapRoute(
name: "Default23",
url: "Farkli/{page}",
defaults: new { controller = "default", action = "Index",category="farkli"}
);
routes.MapRoute(
name: "Default3",
url: "haber/{id}",
defaults: new { controller = "default", action = "haber", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default4",
url: "icerik/hakkimizda",
defaults: new { controller = "default", action = "hakkimizda" }
);
routes.MapRoute(
name: "hata",
url: "error/notfound",
defaults: new { controller = "error", action = "NotFound" }
);
routes.MapRoute(
"NotFound",
"{*url}",
new { controller = "Error", action = "NotFound" }
);
}
}
}
<file_sep>/clas/NewsFinder.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using obajans.Models;
namespace obajans.clas
{
public class NewsFinder
{
public haber getnew(int id1)
{
datacontext db = new datacontext();
return (db.haberler.Where(p => p.id == id1).FirstOrDefault<haber>());
}
}
}<file_sep>/Controllers/DefaultController.cs
using obajans.clas;
using obajans.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace obajans.Controllers
{
[HandleError]
public class DefaultController : Controller
{
public ActionResult hakkimizda()
{
return View();
}
public ActionResult Index(int page,string category)
{
datacontext db = new datacontext();
ortakmodel nesne = new ortakmodel();
if (category.ToLower()=="siyaset")
{
if (page < 1)
{
page = 1;
}
if (page > (db.haberler.Where(q => q.konu=="Siyaset").ToList().Count() / 14) + 1)
{
page = (db.haberler.Where(q => q.konu == "Siyaset").ToList().Count() / 14) + 1;
}
Element eleme = new Element();
int element = (page * 14) - 14;
try
{
nesne.haber = db.haberler.Where(q => q.konu == "Siyaset").OrderByDescending(p => p.id).Skip(element).Take(14).ToList();
}
catch (Exception)
{
nesne.haber = db.haberler.Where(q => q.konu == "Siyaset").OrderByDescending(p => p.id).Take(14).ToList();
// RedirectToAction("Index", beforePage.beforeIndexpage);
}
ViewData["Category"] = "Siyaset";
ViewData["Pagenum"] = eleme.Pagelist(page, db.haberler.Where(q => q.konu == "Siyaset").ToList().Count());
return View(nesne);
}
if (category.ToLower()=="spor")
{
if (page < 1)
{
page = 1;
}
if (page > (db.haberler.Where(q => q.konu == "Spor").ToList().Count() / 14) + 1)
{
page = (db.haberler.Where(q => q.konu == "Spor").ToList().Count() / 14) + 1;
}
Element eleme = new Element();
int element = (page * 14) - 14;
try
{
nesne.haber = db.haberler.Where(q => q.konu == "Spor").OrderByDescending(p => p.id).Skip(element).Take(14).ToList();
}
catch (Exception)
{
nesne.haber = db.haberler.Where(q => q.konu == "Spor").OrderByDescending(p => p.id).Take(14).ToList();
// RedirectToAction("Index", beforePage.beforeIndexpage);
}
ViewData["Category"] = "Spor";
ViewData["Pagenum"] = eleme.Pagelist(page, db.haberler.Where(q => q.konu == "Spor").ToList().Count());
return View(nesne);
}
if (category.ToLower()=="para")
{
if (page < 1)
{
page = 1;
}
if (page > (db.haberler.Where(q => q.konu == "Para").ToList().Count() / 14) + 1)
{
page = (db.haberler.Where(q => q.konu == "Para").ToList().Count() / 14) + 1;
}
Element eleme = new Element();
int element = (page * 14) - 14;
try
{
nesne.haber = db.haberler.Where(q => q.konu == "Para").OrderByDescending(p => p.id).Skip(element).Take(14).ToList();
}
catch (Exception)
{
nesne.haber = db.haberler.Where(q => q.konu == "Para").OrderByDescending(p => p.id).Take(14).ToList();
// RedirectToAction("Index", beforePage.beforeIndexpage);
}
ViewData["Category"] = "Para";
ViewData["Pagenum"] = eleme.Pagelist(page, db.haberler.Where(q => q.konu == "Para").ToList().Count());
return View(nesne);
}
if (category.ToLower() == "farkli")
{
if (page < 1)
{
page = 1;
}
if (page > (db.haberler.Where(q => q.konu == "Farklı").ToList().Count() / 14) + 1)
{
page = (db.haberler.Where(q => q.konu == "Farklı").ToList().Count() / 14) + 1;
}
Element eleme = new Element();
int element = (page * 14) - 14;
try
{
nesne.haber = db.haberler.Where(q => q.konu == "Farklı").OrderByDescending(p => p.id).Skip(element).Take(14).ToList();
}
catch (Exception)
{
nesne.haber = db.haberler.Where(q => q.konu == "Farklı").OrderByDescending(p => p.id).Take(14).ToList();
// RedirectToAction("Index", beforePage.beforeIndexpage);
}
ViewData["Category"] = "Farkli";
ViewData["Pagenum"] = eleme.Pagelist(page, db.haberler.Where(q => q.konu == "Farklı").ToList().Count());
return View(nesne);
}
else
{
if (page < 1)
{
page = 1;
}
if (page > (db.haberler.ToList().Count() / 14) + 1)
{
page = (db.haberler.ToList().Count() / 14) + 1;
}
Element eleme = new Element();
int element = (page * 14) - 14;
try
{
nesne.haber = db.haberler.OrderByDescending(p => p.id).Skip(element).Take(14).ToList();
}
catch (Exception)
{
nesne.haber = db.haberler.OrderByDescending(p => p.id).Take(14).ToList();
// RedirectToAction("Index", beforePage.beforeIndexpage);
}
ViewData["Category"] = "hepsi";
ViewData["Pagenum"] = eleme.Pagelist(page, db.haberler.ToList().Count());
return View(nesne);
}
}
public ActionResult Haber(int id)
{
datacontext db = new datacontext();
ortakmodel nesne = new ortakmodel();
NewsFinder news = new NewsFinder();
try
{
if (news.getnew(id).icerik != "")
{
}
}
catch (Exception)
{
return RedirectToAction("Index");
}
if (news.getnew(id).icerik != "")
{
ViewData["oncehaberler"] = db.haberler.Where(p => p.id < id).OrderByDescending(p => p.id).Take(4).ToList();
ViewData["sonrahaberler"] = db.haberler.Where(p => p.id > id).OrderBy(p => p.id).Take(4).ToList();
ViewData["ilkhaberler"] = db.haberler.OrderBy(p => p.id).Skip(1).Take(4).ToList();
ViewData["sonhaberler"] = db.haberler.OrderBy(p => p.id).Skip(1).Take(4).ToList();
return View(news.getnew(id));
}
else
{
return RedirectToAction("Index");
}
}
}
}
|
28f00e0ad374bce4de2f732d8d31d8b465f76dd2
|
[
"C#"
] | 9 |
C#
|
Msalpdogan/Asp.Net_Mvc_News_Portal
|
cdf270f3cf3ba8e04df99a671f496f1b51e4ffef
|
311005d222648b3313e8a3e194ed645c4c89b26d
|
refs/heads/master
|
<file_sep>print("Penentuan Bilangan Genap dan Ganjil")
def bilgenapganjil(bil):
sisa_pambagian=bil%2
if sisa_pambagian==0:
print("Bilangan ini bilangan Genap")
else:
print("Bilangan ini bilangan Ganjil")
return
nilai_bilangan=int(input("Masukkan bilangan bulat: "))
bilgenapganjil(nilai_bilangan)
<file_sep># Kode Respon Status HTTP
**Sukses**
```
200 OK
201 Request Berhasil dibuat
202 Request berhasil diterima
203 Non-Authoritative Information (since HTTP/1.1)
204 Tanpa Konten
205 Reset Content
206 Partial Content
207 Multi-Status (WebDAV; RFC 4918)
208 Already Reported (WebDAV; RFC 5842)
226 IM Used (RFC 3229)
```
**Pengalihan**
```
300 Multiple Choices
301 Dipindah Permanen
302 Ditemukan
303 Lihat Lainnya
304 Not Modified
305 Use Proxy (since HTTP/1.1)
306 Switch Proxy
307 Temporary Redirect (since HTTP/1.1)
308 Permanent Redirect (Experimental RFC; RFC 7238)
```
**Kesalahan Dari Klien**
```
400 Permintaan Tak Layak
401 Unauthorized
402 Payment Required
403 Terlarang
404 Tidak Ditemukan
405 Method Not Allowed
406 Not Acceptable
407 Proxy Authentication Required
408 Request Timeout
409 Conflict
410 Tidak tersedia
411 Length Required
412 Precondition Failed
413 Request Entity Too Large
414 Request-URI Too Long
415 Unsupported Media Type
416 Requested Range Not Satisfiable
417 Expectation Failed
419 Authentication Timeout (not in RFC 2616)
420 Method Failure (Spring Framework)
```
**Kesalahan Server**
```
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout
505 HTTP Version Not Supported
506 Variant Also Negotiates (RFC 2295)
507 Insufficient Storage (WebDAV; RFC 4918)
508 Loop Detected (WebDAV; RFC 5842)
509 Bandwidth Limit Exceeded (Apache bw/limited extension)
510 Not Extended (RFC 2774)
511 Network Authentication Required (RFC 6585)
520 Origin Error (CloudFlare)
521 Web server is down (CloudFlare)
522 Connection timed out (CloudFlare)
523 Proxy Declined Request (CloudFlare)
524 A timeout occurred (CloudFlare)
598 Network read timeout error (Unknown)
599 Network connect timeout error (Unknown)
```
<file_sep>import math
phi=math.pi
def luaslingkaran(r):
hasil_luas=r*r*phi
print ("luas Lingkaran: ""{:.3f}".format(hasil_luas))
return
r=int(input("Masukkan Jari-jari Lingkaran: "))
luaslingkaran(r)
<file_sep>import socket
s= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print(s)
server = 'defmacro.com'
port = 80
server_ip =socket.gethostbyname(server)
print(server_ip)
request= "GET / HTTP/1.1\nHost: "+server+"\n\n"
s.connect((server,port))
s.send(request.encode())
result = s.recv(4096)
print(result)
|
d5ed9d7b96652f82e2d0bbb8baf87a1191eb4fae
|
[
"Markdown",
"Python"
] | 4 |
Python
|
azispc/Python
|
52d9d28468c7493938ca27063ee1f551d44210a2
|
3fb3feed15c5a68545e0fb18c289e10bab8f2c7c
|
refs/heads/master
|
<file_sep>import Link from 'next/link';
// style
const linkStyle = {
marginRight: 15
};
// header function
export default function Header(){
return(
<div>
{/* link to home */}
<Link href="/">
<a style={linkStyle}>Home</a>
</Link>
{/* link to about */}
<Link href="/about">
<a style={linkStyle}>About</a>
</Link>
</div>
);
}<file_sep># Nextjs-boilerplate-project
Nextjs Boilerplate Application
# Prerequisites
1. clone this repo
2. install react next ```npm install --save react react-dom next```
3. run ```npm install```
# How to execute the application
- type this command ```npm run dev``` or ```yarn run dev```
|
3d5ccc6e715559cc92c5890cb2b5faff8a70ad92
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
mmsesay/nextjs-boilerplate-project
|
e98bd448627ab344314ba9b6c89e438968d3b406
|
b6468fa1c4f4950f4d8836aa3ce1a3481ab64ee9
|
refs/heads/master
|
<repo_name>kmala/controller-sdk-go<file_sep>/api/appsettings.go
package api
// AppSettings is the structure of an app's settings.
type AppSettings struct {
// Owner is the app owner. It cannot be updated with AppSettings.Set(). See app.Transfer().
Owner string `json:"owner,omitempty"`
// App is the app name. It cannot be updated at all right now.
App string `json:"app,omitempty"`
// Created is the time that the application settings was created and cannot be updated.
Created string `json:"created,omitempty"`
// Updated is the last time the application settings was changed and cannot be updated.
Updated string `json:"updated,omitempty"`
// UUID is a unique string reflecting the application settings in its current state.
// It changes every time the application settings is changed and cannot be updated.
UUID string `json:"uuid,omitempty"`
// Maintenance determines if the application is taken down for maintenance or not.
Maintenance *bool `json:"maintenance,omitempty"`
// Routable determines if the application should be exposed by the router.
Routable *bool `json:"routable,omitempty"`
Whitelist []string `json:"whitelist,omitempty"`
}
// NewRoutable returns a default value for the AppSettings.Routable field.
func NewRoutable() *bool {
b := true
return &b
}
// Whitelist is the structure of POST /v2/app/<app id>/whitelist/.
type Whitelist struct {
Addresses []string `json:"addresses"`
}
|
858f88335fa885bf3cadf350a67f0eecdaa6f049
|
[
"Go"
] | 1 |
Go
|
kmala/controller-sdk-go
|
0dfe5494265c3517a2d201569b7aea3f7cce0035
|
e80eb0fcbbcbb02cb205769e91ff38829bfba623
|
refs/heads/master
|
<repo_name>rozdolski/JSON-tutorial<file_sep>/JsonTutorials/src/main/java/com/rozdolskyi/jackson/databinding/JsonRowDataBindingUserExample.java
package com.rozdolskyi.jackson.databinding;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
/**
* Created by Oleksandr_Rozdolskyi on 11/12/2015.
*/
public class JsonRowDataBindingUserExample {
private static final Logger LOGGER = Logger.getLogger(JsonRowDataBindingUserExample.class.getName());
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String INPUT_FILE = "user.json";
private static final String OUTPUT_FILE = "user-modified.json";
private static final String NAME_ATTRIBUTE = "name";
private static final String FIRST_NAME_ATTRIBUTE = "first";
private static final String LAST_NAME_ATTRIBUTE = "last";
private static final String VERIFIED_ATTRIBUTE = "verified";
private static final String USER_IMAGE_ATTRIBUTE = "userImage";
private static final String GENDER_ATTRIBUTE = "gender";
public static void main(String[] args) throws IOException {
readUserDataAndLog();
writeUserData();
}
private static void readUserDataAndLog() throws IOException {
Map<String,Object> userData = MAPPER.readValue(new File(INPUT_FILE), Map.class);
userData.forEach((k, v) -> LOGGER.info(k + " = " + v));
}
private static void writeUserData() throws IOException {
Map<String, Object> userData = new HashMap<>();
Map<String,String> nameStruct = new HashMap<>();
nameStruct.put(FIRST_NAME_ATTRIBUTE, "Alex");
nameStruct.put(LAST_NAME_ATTRIBUTE, "Rozdolskyi");
userData.put(NAME_ATTRIBUTE, nameStruct);
userData.put(GENDER_ATTRIBUTE, "MALE");
userData.put(VERIFIED_ATTRIBUTE, Boolean.FALSE);
userData.put(USER_IMAGE_ATTRIBUTE, "Rm9vYmFyIQ==");
MAPPER.writeValue(new File(OUTPUT_FILE), userData);
}
}
<file_sep>/JsonTutorials/src/main/java/com/rozdolskyi/jackson/User.java
package com.rozdolskyi.jackson;
/**
* Created by Oleksandr_Rozdolskyi on 11/12/2015.
*/
public class User {
public enum Gender { MALE, FEMALE };
public static class Name {
private String first, last;
public String getFirst() { return first; }
public String getLast() { return last; }
public void setFirst(String s) { first = s; }
public void setLast(String s) { last = s; }
}
private Gender gender;
private Name name;
private boolean isVerified;
private byte[] userImage;
public Name getName() { return name; }
public boolean isVerified() { return isVerified; }
public Gender getGender() { return gender; }
public byte[] getUserImage() { return userImage; }
public void setName(Name name) { this.name = name; }
public void setVerified(boolean isVerified) { this.isVerified = isVerified; }
public void setGender(Gender gender) { this.gender = gender; }
public void setUserImage(byte[] userImage) { this.userImage = userImage; }
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Name: ").append(name.getFirst()).append("\n");
builder.append("Last Name: ").append(name.getLast()).append("\n");
builder.append("Gender: ").append(gender).append("\n");
builder.append("Verified: ").append(isVerified).append("\n");
builder.append("Image: ").append(userImage != null).append("\n");
return builder.toString();
}
}<file_sep>/JsonTutorials/src/main/java/com/rozdolskyi/jackson/treemodel/JsonTreeModelUserExample.java
package com.rozdolskyi.jackson.treemodel;
import com.rozdolskyi.jackson.User;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;
/**
* Created by Oleksandr_Rozdolskyi on 11/12/2015.
*/
public class JsonTreeModelUserExample {
private static final Logger LOGGER = Logger.getLogger(JsonTreeModelUserExample.class.getName());
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String INPUT_FILE = "user.json";
private static final String OUTPUT_FILE = "user-modified.json";
private static final String NAME_ATTRIBUTE = "name";
private static final String FIRST_NAME_ATTRIBUTE = "first";
private static final String LAST_NAME_ATTRIBUTE = "last";
private static final String VERIFIED_ATTRIBUTE = "verified";
private static final String USER_IMAGE_ATTRIBUTE = "userImage";
private static final String GENDER_ATTRIBUTE = "gender";
public static void main(String[] args) throws IOException {
JsonNode rootNode = MAPPER.readTree(new File(INPUT_FILE));
User user = parseUser(rootNode);
LOGGER.info(user.toString());
user.getName().setLast("Rozdolskyi");
MAPPER.writeValue(new File(OUTPUT_FILE), user);
}
private static User parseUser(JsonNode rootNode) throws IOException {
User user = new User();
user.setName(parseUserName(rootNode));
user.setGender(parseUserGender(rootNode));
user.setVerified(rootNode.path(VERIFIED_ATTRIBUTE).getBooleanValue());
user.setUserImage(rootNode.path(USER_IMAGE_ATTRIBUTE).getBinaryValue());
return user;
}
private static User.Name parseUserName(JsonNode rootNode) {
JsonNode nameNode = rootNode.path(NAME_ATTRIBUTE);
User.Name userName = new User.Name();
userName.setFirst(nameNode.path(FIRST_NAME_ATTRIBUTE).getTextValue());
userName.setLast(nameNode.path(LAST_NAME_ATTRIBUTE).getTextValue());
return userName;
}
private static User.Gender parseUserGender(JsonNode rootNode) {
return User.Gender.valueOf(rootNode.path(GENDER_ATTRIBUTE).getTextValue());
}
}
<file_sep>/JsonTutorials/src/main/java/com/rozdolskyi/jackson/databinding/JsonDataBindingUserExample.java
package com.rozdolskyi.jackson.databinding;
import com.rozdolskyi.jackson.User;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;
/**
* Created by Oleksandr_Rozdolskyi on 11/12/2015.
*/
public class JsonDataBindingUserExample {
private static final Logger LOGGER = Logger.getLogger(JsonDataBindingUserExample.class.getName());
private static final String INPUT_FILE = "user.json";
private static final String OUTPUT_FILE = "user-modified.json";
private static final ObjectMapper MAPPER = new ObjectMapper();
public static void main(String[] args) throws IOException {
User user = MAPPER.readValue(new File(INPUT_FILE), User.class);
LOGGER.info(user.toString());
user.getName().setFirst("Alex");
MAPPER.writeValue(new File(OUTPUT_FILE), user);
LOGGER.info(user.toString());
}
}
|
7aa8447402eadd1851fb2c2d06416c1af1bd186c
|
[
"Java"
] | 4 |
Java
|
rozdolski/JSON-tutorial
|
6bb903edc0ac6c6e239b09930574465052b4d371
|
18168cf50791add84734cc8bce15b1d5539173b7
|
refs/heads/master
|
<repo_name>liuxiaogou/vue-self<file_sep>/index.js
function defineReactive(obj,key,val){
observe(val);
const dep = new Dep();
Object.defineProperty(obj,key,{
get(){
console.log('值为'+val);
//依赖收集在这里
Dep.target&& dep.addDep(Dep.target)
return val
},
set(newVal){
if (newVal!==val) {
val = newVal
observe(newVal);
dep.notify();
}
}
})
}
function observe (obj){
if (typeof obj!== 'object' || obj == null) { //要的是个对象,不是的话就不走
return
}
new Observer(obj)
}
function proxy(vm,$data){ //代理,把 实例中的$data的属性 代理到 实例中,这样数据可以直接通过vm.name 去访问
Object.keys(vm[$data]).forEach((key)=>{
Object.defineProperty(vm,key,{
get(){
return vm[$data][key]
},
set(newVal){
if (newVal!==vm[$data][key]) {
vm[$data][key] = newVal
}
}
})
})
}
function getType(obj){ //类型精确判断
var type = Object.prototype.toString.call(obj).slice(8, -1);
return type;
}
class Fy{
constructor(option){
this.$option = option;
this.$data = option.data;
observe(this.$data); //响应化处理
proxy(this,'$data');//代理
new Compiler(option.el, this)
}
}
class Observer{
constructor(value){
if (getType(value) ==='Object') {
this.dataxy(value)
}else if(getType(value) ==='Array'){
}
}
dataxy(obj){
Object.keys(obj).forEach((key)=>{
defineReactive(obj,key,obj[key])
})
}
}
class Watcher{
constructor(vm,key,updateFn){
this.vm = vm;
this.key = key;
this.updateFn = updateFn;
Dep.target = this;
this.vm[this.key] //读取 触发getter
Dep.target = null; //收集完就置空
}
update(){
this.updateFn.call(this.vm,this.vm[this.key])
}
}
// Dep 依赖 管理某个key相关的所有watcher实例
class Dep{
constructor () {
this.deps = []
}
addDep(dep) { //dep是watch实例
this.deps.push(dep)
}
notify() {
this.deps.forEach(dep => dep.update());
}
}<file_sep>/compile.js
// 编译器
// 递归遍历dom树
// 判断节点类型,如果是文本,则判断是否是插值绑定
// 如果是元素,则遍历其属性判断是否是指令或事件,然后递归子元素
class Compiler{
constructor(el,vm){
this.$vm = vm;
this.$el = document.querySelector(el);
if (this.$el) {
this.compile(this.$el)
}
}
compile(el){
const childNodes = el.childNodes;
Array.from(childNodes).forEach((node)=>{
if (this.isElement(node)) {
this.compileElement(node);
}else if (this.isText(node)) {
this.compileText(node);
}
// 递归子节点
if (node.childNodes && node.childNodes.length > 0) {
this.compile(node)
}
})
}
isElement(node){
return node.nodeType ===1
}
isText(node){
return node.nodeType ===3 && /\{\{(.*)\}\}/.test(node.textContent)
}
compileElement(node){
let watch = [];
Array.from(node.attributes).forEach((attr)=>{
const name = attr.name;
const value = attr.value;
if (this.isFyAttr(name)) {
const attr_name = name.substring(3);
this[attr_name] && this[attr_name](node,value)
}
})
}
isFyAttr(name){
return name.indexOf('fy-')===0
}
compileText(node){
this.updata(node,RegExp.$1,"text")
}
html(node,value){
this.updata(node,value,"html")
}
text(node,value){
this.updata(node,value,"text")
}
updata(node,content,name){
//初始化
const fn = this[name+'Updata'];
fn && fn(node,this.$vm[content])
//创建watcher实例
new Watcher(this.$vm,content,function(val){
fn && fn(node,val)
});
}
htmlUpdata(node,content){
node.innerHTML = content;
}
textUpdata(node,content){
node.textContent = content;
}
}
|
18c4738814c94448ce217d8bad9fe42e94ff85d0
|
[
"JavaScript"
] | 2 |
JavaScript
|
liuxiaogou/vue-self
|
d621e815fb700f7a1791b27b0c8dd399233bffba
|
3508d9f0064dbad60625c855503e336aa1d94361
|
refs/heads/master
|
<repo_name>abhishekjd/node-todo-api<file_sep>/server/test/server.test.js
const expect = require('expect');
const request = require('supertest');
var {ObjectID} = require('mongodb');
var {app} = require('./../server.js');
var {Todo} = require('./../models/todos.js');
var todos = [{
_id: new ObjectID(),
text : "Thsi is the 1st todo"
}, {
_id: new ObjectID(),
text : "Thsi si the 2nd todo"
}];
beforeEach((done)=>{
Todo.remove({}).then(()=>{
return Todo.insertMany(todos)
}).then(()=>{
done();
}).catch((err)=>{
done(err);
})
})
describe('POST /todos', ()=>{
it('should save the todos', (done)=>{
var text = 'This is a test script for todo';
request(app)
.post('/todos')
.send({text})
.expect(200)
.expect((res)=>{
expect(res.body.text).toBe(text);
})
.end((err, res)=>{
if (err){
return done(err);
}
Todo.find().then((todos)=>{
expect(todos.length).toBe(3);
expect(todos[2].text).toBe(text);
done();
}).catch((err)=>{
done(err);
})
})
})
it('shoudl not create todo for invalid input', (done)=> {
request(app)
.post('/todos')
.send({})
.expect(400)
.end((err, res)=>{
if (err){
return done(err);
}
Todo.find().then((todos)=>{
expect(todos.length).toBe(2);
done();
}).catch((e)=>{
done(e);
})
})
});
});
describe('GET /todos', ()=>{
it('should return all the todos', (done)=>{
request(app)
.get('/todos')
.expect(200)
.expect((res)=>{
expect(res.body.todos.length).toBe(2)
})
.end(done);
})
})
describe('GET /todos/:id', ()=>{
it('should return the todo corresponding to id', (done)=>{
request(app)
.get(`/todos/${todos[0]._id.toHexString()}`)
.expect(200)
.expect((res)=>{
expect(res.body.todos.text).toBe(todos[0].text);
})
.end(done);
})
it('should check for invalid id', (done)=>{
request(app)
.get('/todos/123')
.expect(404)
.end(done);
})
it('should return 404 for if todo not found', (done)=>{
var newID = new ObjectID().toHexString();
request(app)
.get(`/todos/${newID}`)
.expect(404)
.end(done);
})
});
describe('DELETE /todos/:id', ()=>{
it('should delete the corresponding todo on id', (done)=>{
request(app)
.delete(`/todos/${todos[0]._id.toHexString()}`)
.expect(200)
.expect((res)=>{
expect(res.body.todo.text).toBe(todos[0].text);
})
.end((err, res)=>{
if(err){
return done(err);
}
Todo.findById(todos[0]._id).then((todo)=>{
// expect(null).toNotExist();
done();
}).catch((e)=>{
done(e);
})
});
})
it('should check the invalid todo', (done)=>{
request(app)
.delete('/todos/12332')
.expect(404)
.end(done);
})
it('should send 404 if todo not found', (done)=>{
var newID = new ObjectID().toHexString();
request(app)
.delete(`/todos/${newID}`)
.expect(404)
.end(done);
})
});
|
c2e2ab52f9a5d83fc9a85ccf1a880d61b0ac0a79
|
[
"JavaScript"
] | 1 |
JavaScript
|
abhishekjd/node-todo-api
|
753313de11783b0af5013af7055bd03b770d2926
|
f7cd0cc2628951da236af9d02a87c0f6dfda43e5
|
refs/heads/master
|
<file_sep>#!/bin/bash -x
/Applications/Xcode.app/Contents/Developer/usr/bin/ibtool --errors --warnings --notices --output-format human-readable-text --compile "$1" "$2" --sdk /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk
|
7ab01041b22539abf3caafa840dd56056b3e3290
|
[
"Shell"
] | 1 |
Shell
|
codeoneclick/SNContanct
|
98db0a3e6f0571b929e56fa5183c27738699487a
|
64ef06be66c494b32eab4c8df96368b50e67d4d2
|
refs/heads/master
|
<file_sep>#!/bin/bash
echo "Step 1"
mkdir session_1
mkdir -p task_1/mirantis/files
echo "Step 2"
echo "Hello, world! 43 *******************************************" >> task_1/mirantis/files/text
echo "10 world: worldworldworldworldworldworldworldworldworldworld" >> task_1/mirantis/files/text
echo "10 world: worldworldworldworldworldworldworldworldworldworld" >> task_1/mirantis/files/text
echo "Hello, Anastasia! 39 ***************************************" >> task_1/mirantis/files/text
echo "Hello, Guzikova! 40 ****************************************" >> task_1/mirantis/files/text
#git add task_1/mirantis/files/text
#git commit -m "Step 2a"
#git push
dd if=/dev/zero of=task_1/mirantis/files/bin bs=128 count=1
#git add task_1/mirantis/files/bin
#git commit -m "Step 2b"
#git push
echo "Step 2 Check"
ls -la task_1/mirantis/files/
stat task_1/mirantis/files/bin
echo "Step 3"
chmod 754 task_1/mirantis/files/bin
echo "Step 3 Check"
ls -la task_1/mirantis/files/
#git commit -a -m "Step 3"
#git push
echo "Step 4"
du -sh task_1/mirantis/ >> task_1/mirantis/size
echo "du -sh task_1/mirantis" >> task_1/mirantis/size
echo "Step 4 check"
cat task_1/mirantis/size
#git add task_1/mirantis/size
#git commit -m "Step 4"
#git push
echo "Step 5"
tar -zcvf mirantis.tar.gz task_1/mirantis/ -C task_1/mirantis/
#git add mirantis.tar.gz
#git commit -m "Step 5"
#git push
tar -ztf mirantis.tar.gz
echo "Step 6"
rm -rf task_1/mirantis/
mv mirantis.tar.gz task_1/
#git commit -a -m "Step 6"
#git push
echo "Finished"
<file_sep>#!/bin/bash
echo "Init"
pwd
echo "Step 1"
mkdir session_2
touch session_2/bashrc
#vim session_2/bashrc
echo "# USE! If u want 2 inject this aliases into your terminal, please type source ~/bashrc" >> bashrc
echo "alias gt = 'git diff'" >> bashrc
echo "alias gs = 'git status'" >> bashrc
echo "alias ga = 'git add'" >> bashrc
echo "alias gc = 'git commit'" >> bashrc
echo "alias gl = 'git log --oneline'" >> bashrc
echo "alias clean = 'rm -f *.pyc *.swp'" >> bashrc
echo "alias cdw = 'cd ~/Git/la/session_2'" >> bashrc
cd session_2
#git add bashrc
#git commit -m "Step 1a"
#git push
echo "Step 2"
echo "Var w/grep"
touch cmds
ps -elf | grep -v grep | grep -e "\[.*\]"
echo 'ps -elf | grep -v grep | grep -e "\[.*\]"' >> cmds
echo "Var w/fgrep"
ps -elf | grep -v fgrep | fgrep [
echo "ps -elf | grep -v fgrep | fgrep [" >> cmds
echo "daemons"
ps -ef | grep \? | awk '{ print $2"\t"$1"\t"$8 }'
echo 'ps -ef | grep \? | awk "{ print $2"\t"$1"\t"$8 }"' >> cmds
#git add bashrc
#git commit -m "Step 2"
#git push
echo "Step 3"
crontab -e
crontab -l >> ~/Git/la/session_2/crontab.lst
crontab -r
#git add crontab.lst
#git add date.test
#git commit - m "Step 3"
#git push
echo "Step 4"
tar -xzvf files.tar.gz -C session_2 files/commit.msg
mv ~/Git/la/session_2/files/commit.msg ~/Git/la/session_2/
rm -d ~/Git/la/session_2
#git add commit.msg
#git commit -m "Step 4"
#git push
echo "Step 5"
#IN VIM
# :%s/tset/test/g <-replase failin global w/out confirm
# :%s/Telnet/SSH/g
# :%s/telnet/ssh/g
# :%s/^\(.*\)\n\1$/\1/ <- del strings, which are same
# :set shiftwidth=1
# >> or <<
# :set colorcolumn=80
# :%!fmt
mkdir -p ~/.vim/spell
cd ~/.vim/spell
wget http://ftp.vim.org/vim/runtime/spell/ec.utf-8.spl
wget http://ftp.vim.org/vim/runtime/spell/ec.utf-8.sug
#IN VIM
# :setlocal spell spelllang=ent add commit.msg
#git commit -a -m "Step 5"
#git push
|
6254f57d5e9a54eb2fe23ca98ff7df714cd65af7
|
[
"Shell"
] | 2 |
Shell
|
Anonymousfvr/bash
|
95cc54b39bd5e6c5b86f50963f2c0b0f73feb356
|
0344af0a55667c5b7976f89ba5157036b22a6ea4
|
refs/heads/master
|
<file_sep>let express = require('express');
let router = express.Router();
let User = require('../Database/modals/User');
let passport = require('passport');
router.get('/login', function(req,res){
res.render('login');
})
router.get('/register', function(req,res){
res.render('register');
})
//register handle..
router.post('/register', function(req,res){
let {name, email, password, password2} = req.body;
let errors = [];
if(!name || !email || !password || !password2){
errors.push({msg:'Please fill all fields'});
}
if(password2 && password!==password2){
errors.push({msg:'Password missmatch'});
}
if(password.length<6){
errors.push({msg:'Password should be 6 characters...'});
}
if(errors.length>0){
res.render('register',{
errors,
name,
email,
password
});
}else{
console.log('else');
User.findOne({email:email}, function(err, user){
if(user){
errors.push({msg:'Email already registered'});
console.log('exists...');
res.render('register',{
errors,
name,
email,
password
});
}else{
User.create({
name,
email,
password
}).then(function(user){
console.log(user);
req.flash('success_msg', 'You are successfully registered');
res.redirect('/users/login');
}).catch(function(err){
console.log(err);
if(err) throw err;
})
}
})
}
});
//login handle
router.post('/login', function(req,res,next){
passport.authenticate('local', {
successRedirect:'/dashboard',
failureRedirect:'/users/login',
failureFlash:true
})(req, res, next);
});
//logout handle
router.get('/logout', function(req,res){
req.logout();
req.flash('success_msg', 'You are logged out')
res.redirect('/users/login');
})
module.exports = router;
<file_sep>let express = require('express');
let expressLayouts = require('express-ejs-layouts');
let mongoose = require('mongoose');
let flash = require('connect-flash');
let session = require('express-session');
let passport = require('passport')
let app = express();
let passportConfig = require('./passport-config/config');
let PORT = process.env.PORT || 3000;
//layouts
app.use(expressLayouts);
app.set('view engine', 'ejs');
//bodyparser
app.use(express.urlencoded({extended:false}));
//express session
app.use(session({
secret:'secret',
resave:true,
saveUninitialized:true
}))
//passport config
passportConfig(passport);
app.use(passport.initialize());
app.use(passport.session());
//flash
app.use(flash());
//custom middleware to show msgs
//when we registered successfully, we flash a message
//on login screen after redirection.
//res.locals is to set intermediate data for current req/res lifecycle, which
// will be available for our view engine...
app.use(function(req,res,next){
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
next(); // to call next middle ware, if you ignore, request will not be processed.
})
//static
app.use(express.static('public'));
//Routes..
app.use('/', require('./Routes/index'));
app.use('/users', require('./Routes/users'));
//db connection
mongoose.connect('mongodb://localhost/login-passport-authentication',{useNewUrlParser:true})
.then(()=>console.log('conneected'))
.catch(err=>console.log(err));
app.listen(PORT, function(){
console.log(`started at ${PORT}`)
});
|
dee81a1161c4fe2b829e39c36eb426074ca6d351
|
[
"JavaScript"
] | 2 |
JavaScript
|
sairamalugala/Login-auth-passport
|
b5385a20a1d76b5aac317b3f89d78ceb5aef3977
|
3aa6d14a0c883f642ef7af8951214919b9518f55
|
refs/heads/master
|
<repo_name>Zeitwaechter/petitio-exponere<file_sep>/resources/lang/ru/roles.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Языковые ресурсы названий ролей
|--------------------------------------------------------------------------
|
| Следующие языковые ресурсы используются в названиях
| ролей вашего приложения.
| Вы можете свободно изменять эти языковые ресурсы в соответствии
| с требованиями вашего приложения.
|
*/
'administrator' => 'Администратор',
'user' => 'Пользователь',
];
<file_sep>/config/modules.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Module Namespace
|--------------------------------------------------------------------------
|
| Default module namespace.
|
*/
'namespace' => 'Modules',
/*
|--------------------------------------------------------------------------
| Module Stubs
|--------------------------------------------------------------------------
|
| Default module stubs.
|
*/
'stubs' => [
'enabled' => false,
'path' => base_path() . '/vendor/nwidart/laravel-modules/src/Commands/stubs',
'files' => [
'routes/web' => 'Http/Routes/http.php',
'routes/api' => 'Api/Routes/api.php',
'views/index' => 'Resources/views/index.blade.php',
'views/master' => 'Resources/views/layouts/master.blade.php',
'scaffold/config' => 'Config/config.php',
'composer' => 'composer.json',
'assets/js/app' => 'Resources/assets/js/app.js',
'assets/sass/app' => 'Resources/assets/sass/app.scss',
'webpack' => 'webpack.mix.js',
'package' => 'package.json',
],
'replacements' => [
'routes/web' => ['LOWER_NAME', 'STUDLY_NAME'],
'routes/api' => ['LOWER_NAME'],
'webpack' => ['LOWER_NAME'],
'json' => ['LOWER_NAME', 'STUDLY_NAME', 'MODULE_NAMESPACE'],
'views/index' => ['LOWER_NAME'],
'views/master' => ['LOWER_NAME', 'STUDLY_NAME'],
'scaffold/config' => ['STUDLY_NAME'],
'composer' => [
'LOWER_NAME',
'STUDLY_NAME',
'VENDOR',
'AUTHOR_NAME',
'AUTHOR_EMAIL',
'MODULE_NAMESPACE',
],
],
'gitkeep' => true,
],
'paths' => [
/*
|--------------------------------------------------------------------------
| Modules path
|--------------------------------------------------------------------------
|
| This path used for save the generated module. This path also will be added
| automatically to list of scanned folders.
|
*/
'modules' => base_path('modules'),
/*
|--------------------------------------------------------------------------
| Modules assets path
|--------------------------------------------------------------------------
|
| Here you may update the modules assets path.
|
*/
'assets' => public_path('Modules'),
/*
|--------------------------------------------------------------------------
| The migrations path
|--------------------------------------------------------------------------
|
| Where you run 'module:publish-migration' command, where do you publish the
| the migration files?
|
*/
'migration' => base_path('Database/Migrations'),
/*
|--------------------------------------------------------------------------
| Generator path
|--------------------------------------------------------------------------
| Customise the paths where the folders will be generated.
| Set the generate key to false to not generate that folder
*/
'generator' => [
'api_controller' => ['path' => 'Api/Controllers', 'generate' => true],
'api_filter' => ['path' => 'Api/Middleware', 'generate' => true],
'api_request' => ['path' => 'Api/Requests', 'generate' => true],
'api_routes' => ['path' => 'Api/Routes', 'generate' => true],
'config' => ['path' => 'Config', 'generate' => true],
'command' => ['path' => 'Console', 'generate' => true],
'migration' => ['path' => 'Database/Migrations', 'generate' => true],
'seeder' => ['path' => 'Database/Seeders', 'generate' => true],
'factory' => ['path' => 'Database/Factories', 'generate' => true],
'model' => ['path' => 'Entities', 'generate' => true],
'model_traits_attributes' => ['path' => 'Entities/Traits/Attributes', 'generate' => true],
'model_traits_scopes' => ['path' => 'Entities/Traits/Scopes', 'generate' => true],
'model_traits_methods' => ['path' => 'Entities/Traits/Methods', 'generate' => true],
'model_traits_relationships' => ['path' => 'Entities/Traits/Relationships', 'generate' => true],
'http_controller' => ['path' => 'Http/Controllers', 'generate' => true],
'http_filter' => ['path' => 'Http/Middleware', 'generate' => true],
'http_request' => ['path' => 'Http/Requests', 'generate' => true],
'http_routes' => ['path' => 'Http/Routes', 'generate' => true],
'provider' => ['path' => 'Providers', 'generate' => true],
'assets' => ['path' => 'Resources/assets', 'generate' => true],
'assets_sass' => ['path' => 'Resources/assets/scss', 'generate' => true],
'assets_stylus' => ['path' => 'Resources/assets/stylus', 'generate' => true],
'assets_js_vue' => ['path' => 'Resources/assets/js/vue', 'generate' => true],
'assets_js_vue_components' => ['path' => 'Resources/assets/js/vue/components', 'generate' => true],
'assets_js_vue_components_modules' => ['path' => 'Resources/assets/js/vue/components/modules', 'generate' => true],
'assets_js_vue_components_store' => ['path' => 'Resources/assets/js/vue/components/store', 'generate' => true],
'assets_js_vue_components_utils_containers' => ['path' => 'Resources/assets/js/vue/components/utils/containers', 'generate' => true],
'assets_js_vue_components_utils_modals' => ['path' => 'Resources/assets/js/vue/components/utils/modals', 'generate' => true],
'lang' => ['path' => 'Resources/lang', 'generate' => true],
'lang_de' => ['path' => 'Resources/lang/de', 'generate' => true],
'lang_en' => ['path' => 'Resources/lang/en', 'generate' => true],
'views_namespaces' => ['path' => 'Resources/views/namespaces', 'generate' => true],
'views_partials' => ['path' => 'Resources/views/partials', 'generate' => true],
'views_layouts' => ['path' => 'Resources/views/layouts', 'generate' => true],
'test' => ['path' => 'Tests', 'generate' => true],
'repository' => ['path' => 'Repositories', 'generate' => true],
'event' => ['path' => 'Events', 'generate' => true],
'listener' => ['path' => 'Listeners', 'generate' => true],
'policies' => ['path' => 'Policies', 'generate' => true],
'rules' => ['path' => 'Rules', 'generate' => true],
'jobs' => ['path' => 'Jobs', 'generate' => true],
'emails' => ['path' => 'Emails', 'generate' => false],
'notifications' => ['path' => 'Notifications', 'generate' => true],
'resource' => ['path' => 'Transformers', 'generate' => true],
],
],
/*
|--------------------------------------------------------------------------
| Scan Path
|--------------------------------------------------------------------------
|
| Here you define which folder will be scanned. By default will scan vendor
| directory. This is useful if you host the package in packagist website.
|
*/
'scan' => [
'enabled' => false,
'paths' => [
base_path('vendor/*/*'),
],
],
/*
|--------------------------------------------------------------------------
| Composer File Template
|--------------------------------------------------------------------------
|
| Here is the config for composer.json file, generated by this package
|
*/
'composer' => [
'vendor' => 'zeitwaechter',
'author' => [
'name' => '<NAME>',
'email' => '<EMAIL>',
],
],
/*
|--------------------------------------------------------------------------
| Caching
|--------------------------------------------------------------------------
|
| Here is the config for setting up caching feature.
|
*/
'cache' => [
'enabled' => false,
'key' => 'laravel-modules',
'lifetime' => 60,
],
/*
|--------------------------------------------------------------------------
| Choose what laravel-modules will register as custom namespaces.
| Setting one to false will require you to register that part
| in your own Service Provider class.
|--------------------------------------------------------------------------
*/
'register' => [
'translations' => true,
/**
* load files on boot or register method
*
* Note: boot not compatible with asgardcms
*
* @example boot|register
*/
'files' => 'register',
],
];
<file_sep>/resources/lang/uk/http.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Мовні ресурси HTTP
|--------------------------------------------------------------------------
|
| Наступні мовні ресурси використовуються для виводу
| повідомлень у в'юверах сторінок помилок.
| Ви можете вільно змінювати ці мовні ресурси відповідно до вимог
| вашої програми.
|
*/
'404' => [
'description' => 'Вибачте, але сторінки, яку ви намагаєтеся переглянути, не існує.',
'title' => 'Сторінку не знайдено',
],
'503' => [
'description' => 'Назад',
'title' => 'Назад',
],
];
<file_sep>/modules/Auth/Tests/AuthTestCaseKit.php
<?php
namespace Modules\Auth\Tests;
use Modules\Auth\Database\Seeders\AuthDatabaseSeeder;
use Tests\TestCase;
/**
* Class AuthTestCaseKit
*
* @package Modules\Auth\Tests
*/
abstract class AuthTestCaseKit
extends TestCase
{
/**
* Initializes the modules' test case environment.
*/
public function setUp(): void
{
parent::setUp();
\Artisan::call('db:seed', ['--class' => AuthDatabaseSeeder::class]);
}
}
<file_sep>/resources/lang/es/alerts.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Alert Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain alert messages for various scenarios
| during CRUD operations. You are free to modify these language lines
| according to your application's requirements.
|
*/
'backend' => [
'roles' => [
'created' => 'Rol creado correctamente.',
'deleted' => 'Rol eliminado correctamente.',
'updated' => 'Rol actualizado correctamente.',
],
'users' => [
'cant_resend_confirmation' => 'La aplicación está actualmente configurada para aprobación manual de usuarios.',
'confirmation_email' => 'Un nuevo mensaje de confirmación ha sido enviado a su correo.',
'confirmed' => 'El usuario fue confirmado correctamente.',
'created' => 'El usuario fue creado correctamente.',
'deleted' => 'El usuario fue eliminado correctamente.',
'deleted_permanently' => 'El usuario fue eliminado de forma permanente.',
'restored' => 'El usuario fue restaurado correctamente.',
'session_cleared' => 'La sesión del usuario se borró correctamente.',
'social_deleted' => 'La cuenta social fue eliminada correctamente.',
'unconfirmed' => 'El usuario fue desconfirmado correctamente',
'updated' => 'El usuario fue actualizado correctamente.',
'updated_password' => 'La contraseña fue actualizada correctamente.',
],
],
'frontend' => [
'contact' => [
'sent' => 'Su información fue enviada correctamente. Responderemos tan pronto sea posible al e-mail que proporcionó.',
],
],
];
<file_sep>/resources/lang/fa/alerts.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Alert Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain alert messages for various scenarios
| during CRUD operations. You are free to modify these language lines
| according to your application's requirements.
|
*/
'backend' => [
'roles' => [
'created' => 'نقش کاربر با موفقیت ایجاد شد.',
'deleted' => 'نقش کاربر با موفقیت حذف شد.',
'updated' => 'نقش کاربر با موفقیت بهروز رسانی شد.',
],
'users' => [
'cant_resend_confirmation' => 'برنامه در حال حاضر به صورت دستی کاربران را تأیید میکند.',
'confirmation_email' => 'یک ایمیل تأیید جدید به آدرس داخل فایل فرستاده شده است.',
'confirmed' => 'کاربر با موفقیت تایید شد.',
'created' => 'کاربر با موفقیت ایجاد شد.',
'deleted' => 'کاربر با موفقیت حذف شد.',
'deleted_permanently' => 'کاربر برای همیشه حذف شد.',
'restored' => 'کاربر با موفقیت بازیابی شد.',
'session_cleared' => 'جلسه کاربر موفقیت پاک شد.',
'social_deleted' => 'حساب شبکه اجتماعی حذف شد',
'unconfirmed' => 'کاربر با موفقیت تأیید نشد',
'updated' => 'کاربر با موفقیت بهروز رسانی شد.',
'updated_password' => 'گذرواژهی کاربر با موفقیت بهروز رسانی شد.',
],
'document' => [
'created' => 'پرونده با موفقیت ایجاد شد.',
'deleted' => 'پرونده با موفقیت حذف شد.',
'deleted_permanently' => 'پرونده برای همیشه حذف شد.',
'restored' => 'پرونده با موفقیت بازیابی شد.',
'updated' => 'پرونده با موفقیت بهروز رسانی شد.',
],
'center' => [
'created' => 'مرکز با موفقیت ایجاد شد.',
'deleted' => 'مرکز با موفقیت حذف شد.',
'deleted_permanently' => 'مرکز برای همیشه حذف شد.',
'restored' => 'مرکز با موفقیت بازیابی شد.',
'updated' => 'مرکز با موفقیت بهروز رسانی شد.',
],
'station' => [
'created' => 'ایستگاه با موفقیت ایجاد شد.',
'deleted' => 'ایستگاه با موفقیت حذف شد.',
'deleted_permanently' => 'ایستگاه برای همیشه حذف شد.',
'restored' => 'ایستگاه با موفقیت بازیابی شد.',
'updated' => 'ایستگاه با موفقیت بهروز رسانی شد.',
],
],
'frontend' => [
'contact' => [
'sent' => 'اطلاعات شما با موفقیت ارسال شد. ما در اسرع وقت، به ایمیل شما پاسخ خواهیم داد.',
],
],
];
<file_sep>/app/Repositories/Frontend/Auth/UserSessionRepository.php
<?php
namespace App\Repositories\Frontend\Auth;
use App\Models\Auth\User;
/**
* Class UserSessionRepository.
*/
class UserSessionRepository
{
/**
* @param User $user
*
* @return mixed
*/
public function clearSessionExceptCurrent(User $user)
{
if (config('session.driver') == 'database') {
return $user->sessions()
->where('id', '<>', session()->getId())
->delete();
}
// If session driver not database, do nothing
return false;
}
}
<file_sep>/resources/lang/no/http.php
<?php
return [
/*
|--------------------------------------------------------------------------
| HTTP Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used in the views/errors files.
|
*/
'404' => [
'title' => 'Siden finnes ikke',
'description' => 'Beklager, men siden, du forsøkte at se, finnes ikke.',
],
'503' => [
'title' => 'Er snart tilbake.',
'description' => 'Er snart tilbake.',
],
];
<file_sep>/resources/lang/no/auth.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used during authentication for various
| messages that we need to display to the user. You are free to modify
| these language lines according to your application's requirements.
|
*/
'failed' => 'Brukernavn eller passord stemmer ikke.',
'general_error' => 'Du har ikke tilgang til at utføre denne handling.',
'password_rules' => 'Your password must be more than 8 characters long, should contain at least 1 uppercase, 1 lowercase and 1 number.',
'password_used' => 'You can not set a password that you have previously used.',
'socialite' => [
'unacceptable' => ':provider kan ikke brukes som login.',
],
'throttle' => 'For mange mislykkede forsøk. Prøv igen om :seconds sekunder.',
'unknown' => 'Det oppstod en ukjent feil.',
];
<file_sep>/resources/lang/es/http.php
<?php
return [
/*
|--------------------------------------------------------------------------
| HTTP Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used in the views/errors files.
|
*/
'404' => [
'title' => 'La página a la que intento acceder no ha sido encontrada.',
'description' => 'Parece ser que la página que busca no existe.',
],
'503' => [
'title' => 'Servicio no disponible.',
'description' => 'Volvemos en breve.',
],
];
<file_sep>/resources/lang/tr/alerts.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Alert Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain alert messages for various scenarios
| during CRUD operations. You are free to modify these language lines
| according to your application's requirements.
|
*/
'backend' => [
'roles' => [
'created' => 'Rol başarılı bir şekilde oluşturuldu.',
'deleted' => 'Rol başarıyla silindi.',
'updated' => 'Rol başarıyla güncellendi.',
],
'users' => [
'cant_resend_confirmation' => 'Uygulama şu anda kullanıcıları manuel olarak onaylamak üzere ayarlanmıştır.',
'confirmation_email' => 'Kayıtlı e-posta adresine yeni bir onay e-postası gönderildi.',
'confirmed' => 'Kullanıcı başarıyla onaylandı.',
'created' => 'Kullanıcı başarıyla oluşturuldu.',
'deleted' => 'Kullanıcı başarıyla silindi.',
'deleted_permanently' => 'Kullanıcı kalıcı olarak silindi.',
'restored' => 'Kullanıcı başarıyla geri yüklendi.',
'session_cleared' => 'Kullanıcının oturumu başarıyla temizlendi.',
'social_deleted' => 'Sosyal hesap başarıyla silindi',
'unconfirmed' => 'Kullanıcı onaylanmadı',
'updated' => 'Kullanıcı başarıyla güncellendi.',
'updated_password' => '<PASSWORD>.',
],
],
'frontend' => [
'contact' => [
'sent' => 'Bilgileriniz başarıyla gönderildi. Kısa süre içinde mail adresinizden size dönüş yapacağız.',
],
],
];
<file_sep>/resources/lang/he/alerts.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Alert Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain alert messages for various scenarios
| during CRUD operations. You are free to modify these language lines
| according to your application's requirements.
|
*/
'backend' => [
'roles' => [
'created' => 'התפקיד נוצר בהצלחה.',
'deleted' => 'התפקיד נמחק בהצלחה.',
'updated' => 'התפקיד עודכן בהצלחה.',
],
'users' => [
'cant_resend_confirmation' => 'האפליקציה מוגדרת לאישור ידני של משתמשים בלבד.',
'confirmation_email' => 'מייל אימות חדש נשלח לכתובת השמורה במערכת.',
'confirmed' => 'המשתמש אומת בהצלחה.',
'created' => 'המשתמש נוצר בהצלחה.',
'deleted' => 'המשתמש נמחק בהצלחה.',
'deleted_permanently' => 'המשתמש נמחק לצמיתות.',
'restored' => 'המשתמש שוחזר בהצלחה.',
'session_cleared' => 'הסשן של המשתמש נמחק בהצלחה.',
'social_deleted' => 'חשבון סושיאל נמחק בהצלחה',
'unconfirmed' => 'האישור של המשתמש בוטל בהצלחה.',
'updated' => 'המשתמש עודכן בהצלחה.',
'updated_password' => '<PASSWORD>מה עודכנה בהצלחה עבור המשתמש.',
],
],
'frontend' => [
'contact' => [
'sent' => 'הפנייה נשלחה בהצלחה, נחזור אליך בהקדם.',
],
],
];
<file_sep>/resources/lang/fa/http.php
<?php
return [
/*
|--------------------------------------------------------------------------
| HTTP Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used in the views/errors files.
|
*/
'404' => [
'title' => 'صفحه یافت نشد',
'description' => 'با عرض پوزش، صفحهای که سعی در مشاهده آن دارید؛ وجود ندارد.',
],
'503' => [
'title' => 'الآن برمیگردم.',
'description' => 'الآن برمیگردم.',
],
];
<file_sep>/resources/lang/zh-TW/http.php
<?php
return [
/*
|--------------------------------------------------------------------------
| HTTP Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used in the views/errors files.
|
*/
'404' => [
'title' => '找不到頁面',
'description' => '抱歉,您嘗試查看的頁面不存在。 ',
],
'503' => [
'title' => '馬上回來。 ',
'description' => '馬上回來。 ',
],
];
<file_sep>/resources/lang/de/alerts.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Alert Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain alert messages for various scenarios
| during CRUD operations. You are free to modify these language lines
| according to your application's requirements.
|
*/
'backend' => [
'roles' => [
'created' => 'Rolle erstellt.',
'deleted' => 'Rolle gelöscht.',
'updated' => 'Rolle aktualisiert.',
],
'users' => [
'cant_resend_confirmation' => 'The application is currently set to manually approve users.',
'confirmation_email' => 'Eine Aktivierungsmail wurde an die angegebene E-Mailadresse gesendet.',
'confirmed' => 'The user was successfully confirmed.',
'created' => 'Benutzer erstellt.',
'deleted' => 'Benutzer gelöscht.',
'deleted_permanently' => 'Benutzer permanent gelöscht.',
'restored' => 'Benutzer wiederhergestellt.',
'session_cleared' => "The user's session was successfully cleared.",
'social_deleted' => 'Social Account Successfully Removed',
'unconfirmed' => 'The user was successfully un-confirmed',
'updated' => 'Benutzer aktualisiert.',
'updated_password' => '<PASSWORD>.',
],
],
'frontend' => [
'contact' => [
'sent' => 'Your information was successfully sent. We will respond back to the e-mail provided as soon as we can.',
],
],
];
<file_sep>/resources/lang/ru/auth.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Языковые ресурсы аутентификации
|--------------------------------------------------------------------------
|
| Следующие языковые ресурсы используются во время аутентификации для
| различных сообщений которые мы должны вывести пользователю на экран.
| Вы можете свободно изменять эти языковые ресурсы в соответствии
| с требованиями вашего приложения.
|
*/
'failed' => 'Имя пользователя и пароль не совпадают.',
'general_error' => 'У вас нет прав для просмотра этой страницы.',
'password_rules' => 'Ваш пароль должен быть длиной более 8 символов, должен содержать минимум 1 заглавную букву, 1 маленькую букву и 1 номер.',
'password_used' => 'Вы не можете установить пароль, который вы ранее использовали.',
'socialite' => [
'unacceptable' => ':provider не приемлемый тип для входа.',
],
'throttle' => 'Слишком много попыток входа. Пожалуйста, попробуйте еще раз через :seconds секунд.',
'unknown' => 'Упс..., произошла неизвестная ошибка',
];
<file_sep>/resources/lang/tr/http.php
<?php
return [
/*
|--------------------------------------------------------------------------
| HTTP Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used in the views/errors files.
|
*/
'404' => [
'title' => 'Sayfa Bulunamadı',
'description' => 'Maalesef, görüntülemeye çalıştığınız sayfa mevcut değil.',
],
'503' => [
'title' => 'Hemen döneceğiz.',
'description' => 'Hemen döneceğiz.',
],
];
<file_sep>/resources/lang/uk/strings.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Мовні ресурси назв стрічок (Strings)
|--------------------------------------------------------------------------
|
| Наступні мовні ресурси використовуються в назвах
| стрічокк (Strings) всієї вашої програми.
| Ви можете вільно змінювати ці мовні ресурси відповідно до вимог
| вашої програми.
|
*/
'backend' => [
'access' => [
'users' => [
'delete_user_confirm' => 'Ви впевнені, що хочете видалити цього користувача назавжди? Якщо в додатку, є посилання на цього користувача, можливо це призведе до помилок. Дійте на свій розсуд!',
'if_confirmed_off' => '(Якщо чекбокс \'Підтверджено\' неактивний)',
'no_deactivated' => 'Немає деактивованих користувачів.',
'no_deleted' => 'Немає вилучених користувачів.',
'restore_user_confirm' => 'Відновити цього коричтувача?',
],
],
'dashboard' => [
'title' => 'Системна панель',
'welcome' => 'Ласкаво просимо',
],
'general' => [
'all_rights_reserved' => 'Всі права захищені.',
'are_you_sure' => 'Ви впевнені?',
'boilerplate_link' => 'Laravel 5 Boilerplate',
'continue' => 'Продовжити',
'member_since' => 'Користувач з',
'minutes' => 'хвилин',
'search_placeholder' => 'Пошук...',
'timeout' => 'Ви автоматично виведені із системи з міркувань безпеки, так як Ви були активні протягом',
'see_all' => [
'messages' => 'Перегляд всіх повідомлень',
'notifications' => 'Переглянути все',
'tasks' => 'Переглянути всі задачі',
],
'status' => [
'offline' => 'Офлайн',
'online' => 'Онлайн',
],
'you_have' => [
'messages' => '{0} У Вас немає повідомлень|{1} У Вас 1 повідомлення|[2,Inf] У Вас :number повідомлень',
'notifications' => '{0} У Вас немає сповіщень|{1} У Вас є 1 сповіщеня|[2,Inf] У Вас :number сповіщень',
'tasks' => '{0} У Вас немає завдань|{1} У Вас 1 завдання|[2,Inf] У Вас :number завдань',
],
],
'search' => [
'empty' => 'Введіть слово для пошуку.',
'incomplete' => 'Ви повинні підключити або створити свою систему пошуку для цього додатка.',
'results' => 'Результати пошуку :query',
'title' => 'Результати пошуку',
],
'welcome' => 'Ласкаво просимо до Інформаційної панелі',
],
'emails' => [
'auth' => [
'account_confirmed' => 'Ваш обліковий запис підтверджено.',
'error' => 'Ой!',
'greeting' => 'Вітання!',
'regards' => 'З повагою,',
'trouble_clicking_button' => 'Якщо у вас виникли проблеми з натисканням ":action_text" кнопки, скопіюйте і вставте URL нижче в адресний рядок браузера:',
'thank_you_for_using_app' => 'Дякуємо за використання нашого додатку!',
'password_reset_subject' => 'Зміна пароля',
'password_cause_of_email' => 'Ви отримали цей лист, тому що ми отримали запит на зміну пароля для Вашого облікового запису.',
'password_if_not_requested' => 'Якщо ви не давали запит на зміну пароля, ігноруйте це повідомлення і ніяких додаткових дій робити не потрібно.',
'reset_password' => '<PASSWORD>',
'click_to_confirm' => 'Клацніть тут, щоб підтвердити ваш обліковий запис:',
],
'contact' => [
'email_body_title' => 'У вас нове повідомлення з форми зворотного зв\'язку. Подробиці нижче:',
'subject' => 'Нове :app_name повідомлення форми зворотного зв\'язку!',
],
],
'frontend' => [
'test' => 'Тест',
'tests' => [
'based_on' => [
'permission' => 'Система доступу додатку на прикладі застосування дозволу (ів) в -',
'role' => 'Система доступу додатку на прикладі застосування ролі (ей) в -',
],
'js_injected_from_controller' => 'Javascript Injected from a Controller',
'using_access_helper' => [
'array_permissions' => 'Access Helper з масивом назв дозволів або їх ID\'s, де користувач має всі права.',
'array_permissions_not' => 'Access Helper з масивом назв дозволів або їх ID\'s, де користувач не володіє всіма правами.',
'array_roles' => 'Access Helper з масивом імен ролей або їх ID\'s, де користувач має всі права.',
'array_roles_not' => 'Access Helper з масивом імен ролей або їх ID\'s, де користувач не володіє всіма правами.',
'permission_id' => 'Access Helper з ID назви дозволу',
'permission_name' => 'Access Helper з назвою в дозволі',
'role_id' => 'Access Helper з ID ролі',
'role_name' => 'Access Helper з ім\'ям ролі',
],
'using_blade_extensions' => 'Використання Blade Розширень',
'view_console_it_works' => 'Повідомлення console, ви повинні бачити \'це працює!\' що йде від FrontendController@index',
'you_can_see_because' => 'Ви бачите це, тому що у вас роль \':role\'!',
'you_can_see_because_permission' => 'Ви бачите це, тому що у вас є дозвіл \':permission\'!',
],
'general' => [
'joined' => 'З нами',
],
'user' => [
'change_email_notice' => 'При зміні вашого нового E-mail, він буде перезаписаний, і ви повинні знову підтвердити свій новий E-mail.',
'email_changed_notice' => 'Ви повинні підтвердити Ваш новий E-mail, перш ніж ви зможете увійти знову.',
'password_updated' => 'Пароль змінено.',
'profile_updated' => 'Провіль змінено.',
],
'welcome_to' => 'Вітаємо у програмі :place',
],
];
<file_sep>/app/Models/Auth/Role.php
<?php
namespace App\Models\Auth;
use App\Models\Auth\Traits\Method\RoleMethod;
use App\Models\Auth\Traits\Attribute\RoleAttribute;
/**
* Class Role.
*/
class Role extends \Spatie\Permission\Models\Role
{
use RoleAttribute,
RoleMethod;
}
<file_sep>/resources/lang/id/alerts.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Alert Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain alert messages for various scenarios
| during CRUD operations. You are free to modify these language lines
| according to your application's requirements.
|
*/
'backend' => [
'roles' => [
'created' => 'Peran telah berhasil dibuat.',
'deleted' => 'Peran telah berhasil dihapus.',
'updated' => 'Peran telah berhasil diperbarui.',
],
'users' => [
'cant_resend_confirmation' => 'The application is currently set to manually approve users.',
'confirmation_email' => 'Sebuah e-mail konfirmasi baru telah dikirim ke alamat bersangkutan.',
'confirmed' => 'The user was successfully confirmed.',
'created' => 'Pengguna telah berhasil dibuat.',
'deleted' => 'Pengguna telah berhasil dihapus.',
'deleted_permanently' => 'Pengguna telah dihapus secara permanen.',
'restored' => 'Pengguna telah berhasil direstorasi.',
'session_cleared' => "The user's session was successfully cleared.",
'social_deleted' => 'Social Account Successfully Removed',
'unconfirmed' => 'The user was successfully un-confirmed',
'updated' => 'Pengguna telah berhasil diperbarui.',
'updated_password' => '<PASSWORD>.',
],
],
'frontend' => [
'contact' => [
'sent' => 'Your information was successfully sent. We will respond back to the e-mail provided as soon as we can.',
],
],
];
<file_sep>/resources/lang/uk/roles.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Мовні ресурси назв ролей
|--------------------------------------------------------------------------
|
| Наступні мовні ресурси використовуються в назвах
| ролей усієї вашої програми.
| Ви можете вільно змінювати ці мовні ресурси відповідно до вимог
| вашої програми.
|
*/
'administrator' => 'Адміністратор',
'user' => 'Користувач',
];
<file_sep>/resources/lang/ru/http.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Языковые ресурсы HTTP
|--------------------------------------------------------------------------
|
| Следующие языковые ресурсы используются для вывода
| сообщений во вьюверах страниц ошибок.
| Вы можете свободно изменять эти языковые ресурсы в соответствии
| с требованиями вашего приложения.
|
*/
'404' => [
'description' => 'Извините, но страница, которую вы пытаетесь просмотреть, не существует.',
'title' => 'Страница не найдена',
],
'503' => [
'description' => 'Назад',
'title' => 'Назад',
],
];
<file_sep>/app/Http/Controllers/Backend/Auth/User/UserSessionController.php
<?php
namespace App\Http\Controllers\Backend\Auth\User;
use App\Models\Auth\User;
use App\Http\Controllers\Controller;
use App\Repositories\Backend\Auth\SessionRepository;
use App\Http\Requests\Backend\Auth\User\ManageUserRequest;
/**
* Class UserSessionController.
*/
class UserSessionController extends Controller
{
/**
* @param ManageUserRequest $request
* @param SessionRepository $sessionRepository
* @param User $user
*
* @return mixed
* @throws \App\Exceptions\GeneralException
*/
public function clearSession(ManageUserRequest $request, SessionRepository $sessionRepository, User $user)
{
$sessionRepository->clearSession($user);
return redirect()->back()->withFlashSuccess(__('alerts.backend.users.session_cleared'));
}
}
<file_sep>/resources/lang/no/alerts.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Alert Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain alert messages for various scenarios
| during CRUD operations. You are free to modify these language lines
| according to your application's requirements.
|
*/
'backend' => [
'roles' => [
'created' => 'Rollen ble opprettet.',
'deleted' => 'Rollen ble slettet.',
'updated' => 'Rollen ble oppdateret.',
],
'users' => [
'cant_resend_confirmation' => 'Applikasjonen er satt til å godkjenne brukere manuelt.',
'confirmation_email' => 'En ny bekreftelsesmail er sendt til brukeren.',
'confirmed' => 'Brukeren ble godkjent.',
'created' => 'Brukeren ble opprettet.',
'deleted' => 'Brukeren ble slettet.',
'deleted_permanently' => 'Brukeren ble slettet permanent.',
'restored' => 'Brukeren ble gjenopprettet.',
'session_cleared' => 'Brukerens sessjon har blitt fjernet.',
'social_deleted' => 'Sosiale kontoer er fjernet.',
'unconfirmed' => 'The user was successfully un-confirmed',
'updated' => 'Brukeren ble oppdateret.',
'updated_password' => '<PASSWORD>.',
],
],
'frontend' => [
'contact' => [
'sent' => 'Din informasjon ble sendt. Vi svarer deg på mail så fort vi kan.',
],
],
];
<file_sep>/resources/lang/uk/auth.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Мовні ресурси аутентифікації
|--------------------------------------------------------------------------
|
| Наступні мовні ресурси використовуються під час аутентифікації для
| різних повідомлень які ми повинні вивести користувачеві на екран.
| Ви можете вільно змінювати ці мовні ресурси відповідно до вимог
| вашої програми.
|
*/
'failed' => 'Ці облікові дані не збігаються з нашими записами.',
'general_error' => 'У вас немає прав для перегляду цієї сторінки.',
'password_rules' => 'Ваш пароль має бути довжиною більше 8 символів, повинен містити принаймні 1 велику літеру, 1 маленьку літеру та 1 номер.',
'password_used' => 'Ви не можете встановити пароль, який ви раніше використовували.',
'socialite' => [
'unacceptable' => ':provider неприйнятний тип для входу.',
],
'throttle' => 'Занадто багато спроб входу. Будь ласка, спробуйте ще раз, через :seconds секунд.',
'unknown' => 'От халепа..., сталася невідома помилка',
];
<file_sep>/readme.md
## <NAME>
### DEPRECATED
This project will be replaced.
Still, updated to L8.X.
### Introduction
Much wow, much awesome!
This project is a proof of concept / makeshift Laravel application in old-school monolithic style.
It's base idea is some years old and will now be put in motion due to it's somewhat necessity.
### Table of Contents
- [Milestones](#Milestones)
- [What it does](#What-it-does)
- [Requirements](#Requirements)
- [Development](#Development)
- [Configuration](#Configuration)
- [Localization](#Localization)
- [Quality Management-ish](#Quality-Management-ish)
- [Localization](#Localization)
### Milestones
#### The Low Hanging Fruits (cough, cough)
1. Docs
- [ ] The Lay of the Land
(Makeshift White Papers for it's few USPs, Database, Modules, anemic APIs)
1. Modules
- [ ] Implementing/Restructuring Laravel Boilerplate due to `nwidart/laravel-modules`
- [ ] Implementing of all (current) recognized Modules
- [ ] Implementing of Module Context Structure (Entities/Repositories/Controller/API/Requests)
1. Module Context (simply defined)
- [ ] Module Factories+Migration+Seeding created
- [ ] Module Entities created
- [ ] Module Repositories created
- [ ] Anemic Module Controller created
- [ ] Anemic Module APIs created
- [ ] Anemic Module APIs created
- [ ] Anemic Requests created
- [ ] Anemic, basic Views created
1. Unit Tests
- [ ] Unit Tests
- [ ] Feature Tests
. [ ] Routing Tests
1. Vue.js (keeping things simple)
- [ ] Vue.js implementation
- [ ] Vuex implementation
- [ ] Modular Module V _u_ ews (hah..)
1. CSS (SCSS/Stylus+nib)
- [ ] Setup with Webpack 4
- [ ] Hopefully it's based on Foundation 6, otherwise it will be Bootstrap 4
- [ ] Own implementations
#### The End Game
1. GitLab
- Moving zu GitLab, due to M$ noise pollution (and so on).
2. Deployment
- Docker Image
- CI (GitLab, Kubernetes, etc.)
3. More..?
### What it does
It's all about job applications.
### Requirements
- Linux (probably)
- `nginx` 1.15.0+
- `PHP` 7.3.0+
- `node` 10.0+
- `npm`/`npx` 6.9.0+ (I guess)
- `mariadb` 10.3.0+ (or an equivalent, slower MySQL Server - or up to you, as far as the migration supports it)
### Development
- You need an Web Server that can interpret PHP (FPM) to load this application
- You need to start npm to build all JS- and CSS-related dependencies (via `npm run development`)
- You need a MySQL database for core data setup (and e.g. Unit Testing if not via SQLite+Memory)
### Configuration
Configuration shall be made via your own build `.env` file.
See `.env.example` for more information.
### Localization
This application will be made available for english and german speakers.
### Quality Management-ish
As progress moves on I wish to keep things clean via:
- Gitflow (Branching Principle)
- PhpStorm Plugins:
- Php Annotations
- Php Inspections
- PhpUnit Enhancements
- Prettier
- SonarLint
- Unit Tests (but not TDD)
- Code Style is PSR-2-ish
### Documentations
#### Official Documentation Of Laravel Boilerplate _(project base)_
This project is based on _Laravel Boilerplate_ (which is based on Laravel 5.7) and has no documentation of it's own (as of yet).
### Licensing
#### License of _Petitio Exponere_ (this project)
Apache License Version 2: [https://choosealicense.com/licenses/apache-2.0/](https://choosealicense.com/licenses/apache-2.0/)
[Click here for the official documentation of Laravel Boilerplate, though](http://laravel-boilerplate.com)
#### License of Laravel Boilerplate _(project base)_
Laravel Boilerplate is based on _Laravel Boilerplate_ by _<NAME>_ which is licensed under MIT.
MIT: [https://anthony.mit-license.org/](https://anthony.mit-license.org/)
<file_sep>/resources/lang/tr/auth.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used during authentication for various
| messages that we need to display to the user. You are free to modify
| these language lines according to your application's requirements.
|
*/
'failed' => 'Bu kimlik bilgileri kayıtlarımızla eşleşmiyor.',
'general_error' => 'Bunu yapmak için erişiminiz yok.',
'password_rules' => 'Your password must be more than 8 characters long, should contain at least 1 uppercase, 1 lowercase and 1 number.',
'password_used' => 'You can not set a password that you have previously used.',
'socialite' => [
'unacceptable' => ':provider kabul edilen bir oturum açma türü değil.',
],
'throttle' => 'Çok fazla giriş denemesi. Lütfen :seconds saniye sonra yeniden deneyin.',
'unknown' => 'Bilinmeyen bir hata oluştu',
];
<file_sep>/resources/lang/id/http.php
<?php
return [
/*
|--------------------------------------------------------------------------
| HTTP Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used in the views/errors files.
|
*/
'404' => [
'title' => 'Halaman tidak ditemukan',
'description' => 'Maaf, halaman yang Anda coba lihat tidak ada.',
],
'503' => [
'title' => 'Segera kembali.',
'description' => 'Segera kembali.',
],
];
<file_sep>/resources/lang/nl/alerts.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Alert Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain alert messages for various scenarios
| during CRUD operations. You are free to modify these language lines
| according to your application's requirements.
|
*/
'backend' => [
'roles' => [
'created' => 'De rol is succesvol aangemaakt.',
'deleted' => 'De rol is succesvol verwijderd.',
'updated' => 'De rol is succesvol bijgewerkt.',
],
'users' => [
'cant_resend_confirmation' => 'The application is currently set to manually approve users.',
'confirmation_email' => 'Een nieuwe bevestigings e-mail is verzonden naar het aangegeven adres.',
'confirmed' => 'The user was successfully confirmed.',
'created' => 'De gebruiker is succesvol aangemaakt.',
'deleted' => 'De gebruiker is succesvol verwijderd.',
'deleted_permanently' => 'De gebruiker is permanent verwijderd.',
'restored' => 'De gebruiker is met succes hersteld.',
'session_cleared' => "The user's session was successfully cleared.",
'social_deleted' => 'Social Account Successfully Removed',
'unconfirmed' => 'The user was successfully un-confirmed',
'updated' => 'De gebruiker is succesvol bijgewerkt.',
'updated_password' => '<PASSWORD>',
],
],
'frontend' => [
'contact' => [
'sent' => 'Your information was successfully sent. We will respond back to the e-mail provided as soon as we can.',
],
],
];
<file_sep>/app/Repositories/Backend/Auth/SessionRepository.php
<?php
namespace App\Repositories\Backend\Auth;
use App\Models\Auth\User;
use App\Exceptions\GeneralException;
/**
* Class SessionRepository.
*/
class SessionRepository
{
/**
* @param User $user
*
* @return mixed
* @throws GeneralException
*/
public function clearSession(User $user)
{
if ($user->id === auth()->id()) {
throw new GeneralException(__('exceptions.backend.access.users.cant_delete_own_session'));
}
if (config('session.driver') != 'database') {
throw new GeneralException(__('exceptions.backend.access.users.session_wrong_driver'));
}
return $user->sessions()->delete();
}
}
|
ba1b2fdb3797662b6eeeb8e6908fa5c942bbd25f
|
[
"Markdown",
"PHP"
] | 30 |
PHP
|
Zeitwaechter/petitio-exponere
|
3c76cc59e1a7729c52afc99875ef5fdaf8f3e279
|
2c9a6ad918e34c3807e1152efa72200f3e86619d
|
refs/heads/master
|
<repo_name>Gautham-JS/LargeScaleMapping<file_sep>/sfm_reconstruct.cpp
#define CERES_FOUND true
#include <opencv2/sfm.hpp>
#include <opencv2/viz.hpp>
#include <opencv2/calib3d.hpp>
#include <opencv2/core.hpp>
#include <iostream>
#include <fstream>
using namespace std;
using namespace cv;
using namespace cv::sfm;
int main(int argc, char *argv[]){
String im1 = "/home/gautham/Documents/Codes/Datasets/templeRing/templeR0001.png";
String im2 = "/home/gautham/Documents/Codes/Datasets/templeRing/templeR0002.png";
String im3 = "/home/gautham/Documents/Codes/Datasets/templeRing/templeR0005.png";
String im4 = "/home/gautham/Documents/Codes/Datasets/templeRing/templeR0010.png";
String im5 = "/home/gautham/Documents/Codes/Datasets/templeRing/templeR0015.png";
String im6 = "/home/gautham/Documents/Codes/Datasets/templeRing/templeR0020.png";
vector<String> images_paths;
vector<cv::String> impath;
cv::glob("/home/gautham/Documents/Codes/Datasets/templeRing/*.png", impath, false);
images_paths.push_back(im1);
images_paths.push_back(im2);
images_paths.push_back(im3);
images_paths.push_back(im4);
images_paths.push_back(im5);
images_paths.push_back(im6);
int x = 0;
cout<<"Images count : "<<impath.size()<<endl;
cout << "\nLOADED FIRST IMG" << endl;
float f = atof(argv[2]),
cx = atof(argv[3]), cy = atof(argv[4]);
Matx33d K = Matx33d(f, 0, cx,
0, f, cy,
0, 0, 1);
bool is_projective = true;
vector<Mat> Rs_est, ts_est, points3d_estimated;
reconstruct(images_paths, Rs_est, ts_est, K, points3d_estimated, is_projective);
cout << "\n----------------------------\n"
<< endl;
cout << "Reconstruction: " << endl;
cout << "============================" << endl;
cout << "Estimated 3D points: " << points3d_estimated.size() << endl;
cout << "Estimated cameras: " << Rs_est.size() << endl;
cout << "Refined intrinsics: " << endl
<< K << endl
<< endl;
cout << "3D Visualization: " << endl;
cout << "============================" << endl;
viz::Viz3d window("Coordinate Frame");
window.setWindowSize(Size(500, 500));
window.setWindowPosition(Point(150, 150));
window.setBackgroundColor();
cout << "Recovering points ... ";
vector<Vec3f> point_cloud_est;
for (int i = 0; i < points3d_estimated.size(); ++i)
point_cloud_est.push_back(Vec3f(points3d_estimated[i]));
cout << "[DONE]" << endl;
cout << "Recovering cameras ... ";
vector<Affine3d> path;
for (size_t i = 0; i < Rs_est.size(); ++i)
path.push_back(Affine3d(Rs_est[i], ts_est[i]));
cout << "[DONE]" << endl;
if (point_cloud_est.size() > 0)
{
cout << "Rendering points ... ";
viz::WCloud cloud_widget(point_cloud_est, viz::Color::green());
window.showWidget("point_cloud", cloud_widget);
cout << "[DONE]" << endl;
}
else
{
cout << "Cannot render points: Empty pointcloud" << endl;
}
if (path.size() > 0)
{
cout << "Rendering Cameras ... ";
window.showWidget("cameras_frames_and_lines", viz::WTrajectory(path, viz::WTrajectory::BOTH, 0.1, viz::Color::green()));
window.showWidget("cameras_frustums", viz::WTrajectoryFrustums(path, K, 0.1, viz::Color::yellow()));
window.setViewerPose(path[0]);
cout << "[DONE]" << endl;
}
else
{
cout << "Cannot render the cameras: Empty path" << endl;
}
cout << endl
<< "Press 'q' to close each windows ... " << endl;
window.spin();
return 0;
}
<file_sep>/PyUtils/camera_caliberator.py
import numpy as np
import cv2
import glob
import yaml
#import pathlib
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
fx = 7
fy = 5
objp = np.zeros((fx*fy,3), np.float32)
objp[:,:2] = np.mgrid[0:fx,0:fy].T.reshape(-1,2)
n = 0000
objpoints = []
imgpoints = []
images = glob.glob(r'/home/gautham/Documents/Codes/depth_reconstruct/calib_imgs/*.png')
found = 0
for fname in images:
print("calibrating")
img = cv2.imread(fname)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, corners = cv2.findChessboardCorners(gray, (fx,fy), None)
if ret == True:
objpoints.append(objp)
corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
imgpoints.append(corners2)
img = cv2.drawChessboardCorners(img, (fx,fy), corners2, ret)
found += 1
#half = cv2.resize(img, (0, 0), fx = 0.1, fy = 0.1)
cv2.imshow('img', img)
#cv2.waitKey(10)
if cv2.waitKey(100) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)
data = {'camera_matrix': np.asarray(mtx).tolist(),
'dist_coeff': np.asarray(dist).tolist()}
print("done.")
print(data)
with open("calibration_matrix.yaml", "w") as f:
yaml.dump(data, f)<file_sep>/visualOdometry/include/monoUtils.h
/*
GauthWare, LSM, 01/2021
buncha utility functions to clean up base CXX files
*/
#ifndef UTILS_H
#define UTILS_H
#include "monoOdometry.h"
#include "poseGraph.h"
#include "DloopDet.h"
using namespace std;
using namespace cv;
using namespace g2o;
using namespace DLoopDetector;
using namespace DBoW2;
void appendData(vector<float> data){
std::ofstream outfile;
outfile.open("trajectory.csv", ios::app);
for(size_t i=0; i<data.size(); i+=8){
for(size_t j=i; j<i+8; j++){
outfile<<data[j];
outfile<<",";
}
outfile<<"\n";
}
outfile.close();
}
void createData(vector<float> data){
std::ofstream outfile;
outfile.open("trajectory.csv");
outfile<<"Idx,Xm,Ym,Zm,Xgt,Ygt,Zgt,Const\n";
for(size_t i=0; i<data.size(); i+=8){
for(size_t j=i; j<i+8; j++){
outfile<<data[j];
outfile<<",";
}
outfile<<"\n";
}
outfile.close();
}
void dumpOptimized(vector<float> data){
std::ofstream outfile;
outfile.open("trajectoryOptimized.csv");
outfile<<"Xo,Yo,Zo\n";
for(size_t i=0; i<data.size(); i+=3){
int coount = 0;
for(size_t j=i; j<i+3; j++){
outfile<<data[j];
if(coount==2){
continue;
}
else{
outfile<<",";
coount++;
}
}
outfile<<"\n";
}
outfile.close();
}
inline float SIGN(float x) {
return (x >= 0.0f) ? +1.0f : -1.0f;
}
inline float NORM(float a, float b, float c, float d) {
return sqrt(a * a + b * b + c * c + d * d);
}
Mat mRot2Quat(const Mat& m) {
float r11 = m.at<float>(0, 0);
float r12 = m.at<float>(0, 1);
float r13 = m.at<float>(0, 2);
float r21 = m.at<float>(1, 0);
float r22 = m.at<float>(1, 1);
float r23 = m.at<float>(1, 2);
float r31 = m.at<float>(2, 0);
float r32 = m.at<float>(2, 1);
float r33 = m.at<float>(2, 2);
float q0 = (r11 + r22 + r33 + 1.0f) / 4.0f;
float q1 = (r11 - r22 - r33 + 1.0f) / 4.0f;
float q2 = (-r11 + r22 - r33 + 1.0f) / 4.0f;
float q3 = (-r11 - r22 + r33 + 1.0f) / 4.0f;
if (q0 < 0.0f) {
q0 = 0.0f;
}
if (q1 < 0.0f) {
q1 = 0.0f;
}
if (q2 < 0.0f) {
q2 = 0.0f;
}
if (q3 < 0.0f) {
q3 = 0.0f;
}
q0 = sqrt(q0);
q1 = sqrt(q1);
q2 = sqrt(q2);
q3 = sqrt(q3);
if (q0 >= q1 && q0 >= q2 && q0 >= q3) {
q0 *= +1.0f;
q1 *= SIGN(r32 - r23);
q2 *= SIGN(r13 - r31);
q3 *= SIGN(r21 - r12);
}
else if (q1 >= q0 && q1 >= q2 && q1 >= q3) {
q0 *= SIGN(r32 - r23);
q1 *= +1.0f;
q2 *= SIGN(r21 + r12);
q3 *= SIGN(r13 + r31);
}
else if (q2 >= q0 && q2 >= q1 && q2 >= q3) {
q0 *= SIGN(r13 - r31);
q1 *= SIGN(r21 + r12);
q2 *= +1.0f;
q3 *= SIGN(r32 + r23);
}
else if (q3 >= q0 && q3 >= q1 && q3 >= q2) {
q0 *= SIGN(r21 - r12);
q1 *= SIGN(r31 + r13);
q2 *= SIGN(r32 + r23);
q3 *= +1.0f;
}
else {
printf("coding error\n");
}
float r = NORM(q0, q1, q2, q3);
q0 /= r;
q1 /= r;
q2 /= r;
q3 /= r;
Mat res = (Mat_<float>(4, 1) << q0, q1, q2, q3);
return res;
}
g2o::SE3Quat euler2Quaternion(const cv::Mat& R, const cv::Mat& tvec ){
cv::Mat rvec;
cv::Rodrigues( R, rvec );
double roll = rvec.at<double>(0,0);
double pitch = rvec.at<double>(1,0);
double yaw = rvec.at<double>(2,0);
Eigen::AngleAxisd rollAngle(roll, Eigen::Vector3d::UnitX());
Eigen::AngleAxisd yawAngle(pitch, Eigen::Vector3d::UnitY());
Eigen::AngleAxisd pitchAngle(yaw, Eigen::Vector3d::UnitZ());
Eigen::Quaterniond q = rollAngle * yawAngle * pitchAngle;
Eigen::Vector3d trans(tvec.at<double>(0), tvec.at<double>(1), tvec.at<double>(2));
g2o::SE3Quat pose(q,trans);
return pose;
}
Eigen::Isometry3d cvMat2Eigen( const cv::Mat& R, const cv::Mat& tvec ){
Eigen::Matrix3d r;
for ( int i=0; i<3; i++ )
for ( int j=0; j<3; j++ )
r(i,j) = R.at<double>(i,j);
Eigen::Isometry3d T = Eigen::Isometry3d::Identity();
Eigen::AngleAxisd angle(r);
T = angle;
T(0,3) = tvec.at<double>(0,0);
T(1,3) = tvec.at<double>(1,0);
T(2,3) = tvec.at<double>(2,0);
return T;
}
cv::Mat Eigen2cvMat(const Eigen::Isometry3d& matrix) {
cv::Mat R = cv::Mat::zeros(3,3,CV_64F);
cv::Mat tvec = cv::Mat::zeros(1,3,CV_64F);
for ( int i=0; i<3; i++ )
for ( int j=0; j<3; j++ )
R.at<double>(i,j) = matrix(i,j);
Eigen::Vector3d trans = matrix.translation();
tvec.at<double>(0) = trans(0);
tvec.at<double>(1) = trans(1);
tvec.at<double>(2) = trans(2);
//tvec = -R.t()*tvec.t(); //SUS af
return tvec;
}
double getAbsoluteScale(int frame_id, double &Xpos, double &Ypos, double &Zpos){
string line;
int i = 0;
ifstream myfile ("/media/gautham/Seagate Backup Plus Drive/Datasets/dataset/poses/00.txt");
double x =0, y=0, z = 0;
double x_prev, y_prev, z_prev;
if (myfile.is_open()){
while (( getline (myfile,line) ) && (i<=frame_id)){
z_prev = z;
x_prev = x;
y_prev = y;
std::istringstream in(line);
for (int j=0; j<12; j++) {
in >> z ;
if (j==7) y=z;
if (j==3) x=z;
}
i++;
}
myfile.close();
}
else {
cout << "Unable to open file";
return 0;
}
Xpos = x_prev; Ypos = y_prev; Zpos = z_prev;
return sqrt((x-x_prev)*(x-x_prev) + (y-y_prev)*(y-y_prev) + (z-z_prev)*(z-z_prev)) ;
}
#endif<file_sep>/visualOdometry/include/stereoVisualOdometry.h
#include <iostream>
#include <vector>
#include <algorithm>
#include <thread>
#include <stdio.h>
#include <opencv2/core.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/xfeatures2d.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include "opencv2/highgui/highgui.hpp"
#include <opencv2/opencv.hpp>
#include <opencv2/features2d/features2d.hpp>
#include "DBoW2/DBoW2.h"
#include "poseGraph.h"
#include "DloopDet.h"
#include "TemplatedLoopDetector.h"
#include "monoUtils.h"
using namespace std;
using namespace cv;
using namespace DLoopDetector;
using namespace DBoW2;
#define X_BOUND 1000
#define Y_BOUND 1500
typedef TemplatedDatabase<DBoW2::FORB::TDescriptor, DBoW2::FORB> KeyFrameSelection;
struct keyFrame{
int idx = -1;
bool retrack = false;
Mat R,t;
vector<Point3f> pts3d;
};
class visualOdometry{
public:
int seqNo;
double baseline = 0.54;
int Xbias = 750;
int Ybias = 200;
int LCidx = 0;
int cooldownTimer = 0;
bool LC_FLAG = false;
string absPath;
const char* lFptr; const char* rFptr;
double focal_x = 7.188560000000e+02;
double cx = 6.071928000000e+02;
double focal_y = 7.188560000000e+02;
double cy = 1.852157000000e+02;
Mat K = (Mat1d(3,3) << focal_x, 0, cx, 0, focal_y, cy, 0, 0, 1);
Mat referenceImg, currentImage;
vector<Point3f> referencePoints3D, mapPts, untransformed;
vector<Point2f> referencePoints2D;
vector<vector<Point3f>> mapHistory;
vector<cv::Mat> trajectory;
vector<keyFrame> keyFrameHistory;
vector<vector<double>> gtTraj;
vector<Point2f> inlierReferencePyrLKPts;
Mat canvas = Mat::zeros(X_BOUND, Y_BOUND, CV_8UC3);
Mat ret;
globalPoseGraph poseGraph;
std::shared_ptr<OrbLoopDetector> loopDetector;
std::shared_ptr<OrbVocabulary> voc;
std::shared_ptr<KeyFrameSelection> KFselector;
std::string vocfile = "/home/gautham/Documents/Projects/LargeScaleMapping/orb_voc00.yml.gz";
visualOdometry(int Seq, const char*Lfptr, const char*Rfptr){
lFptr = Lfptr;
rFptr = Rfptr;
Params param;
param.image_rows = 1241;
param.image_cols = 376;
param.use_nss = true;
param.alpha = 0.9;
param.k = 1;
param.geom_check = GEOM_DI;
param.di_levels = 2;
voc.reset(new OrbVocabulary());
cerr<<"Loading vocabulary file : "<<vocfile<<endl;
voc->load(vocfile);
cerr<<"Done"<<endl;
loopDetector.reset(new OrbLoopDetector(*voc, param));
loopDetector->allocate(4000);
}
void restructure (cv::Mat& plain, vector<FORB::TDescriptor> &descriptors){
const int L = plain.rows;
descriptors.resize(L);
for (unsigned int i = 0; i < (unsigned int)plain.rows; i++) {
descriptors[i] = plain.row(i);
}
}
Mat loadImageL(int iter);
Mat loadImageR(int iter);
void checkLoopDetectorStatus(Mat img, int idx);
void stereoTriangulate(Mat im1, Mat im2,
vector<Point3f>&ref3dPts,
vector<Point2f>&ref2dPts);
Mat drawDeltas(Mat im, vector<Point2f> in1, vector<Point2f> in2);
void RANSACThreshold(Mat refImg, Mat curImg, vector<Point2f>refPts, vector<Point3f>ref3dpts, vector<Point2f>&inTrkPts, vector<Point3f>&in3dpts);
void PyrLKtrackFrame2Frame(Mat refimg, Mat curImg, vector<Point2f>refPts, vector<Point3f>ref3dpts,
vector<Point2f>&refRetpts, vector<Point3f>&ref3dretPts);
vector<int> removeDuplicates(vector<Point2f>&baseFeatures, vector<Point2f>&newFeatures,
vector<int>&mask, int radius=10);
void repjojectionError(Mat im, vector<Point2f> pt2d, vector<Point3f>pts3d);
void relocalizeFrames(int start, Mat imL, Mat imR, Mat&inv_transform, vector<Point2f>&ftrPts, vector<Point3f>&pts3d);
vector<Point3f> update3dtransformation(vector<Point3f>& pt3d, Mat& inv_transform);
void initSequence();
};<file_sep>/SFM_pipeline/meta.h
#ifndef META_H
#define META_H
//church focal = 10689, ds=4
const int IMAGE_DOWNSAMPLE = 2;
const double FOCAL_LENGTH = 2759 / IMAGE_DOWNSAMPLE;
const int MIN_LANDMARK_SEEN = 3;
#endif<file_sep>/visualOdometry/LK.cpp
#include <g2o/types/sba/types_six_dof_expmap.h>
#include <g2o/solvers/eigen/linear_solver_eigen.h>
#include "g2o/core/sparse_optimizer.h"
#include "g2o/core/block_solver.h"
#include "g2o/core/solver.h"
#include "g2o/core/robust_kernel_impl.h"
#include "g2o/core/optimization_algorithm_levenberg.h"
#include "g2o/solvers/cholmod/linear_solver_cholmod.h"
#include "g2o/solvers/dense/linear_solver_dense.h"
#include "g2o/types/sba/types_six_dof_expmap.h"
#include "g2o/types/slam3d/edge_xyz_prior.h"
#include "g2o/types/slam3d/vertex_se3.h"
#include "g2o/types/slam3d/vertex_pointxyz.h"
#include "g2o/types/slam3d/edge_se3_pointxyz.h"
//#include "edge_se3exp_pointxyz_prior.h"
#include "g2o/solvers/structure_only/structure_only_solver.h"
using namespace std;
using namespace Eigen;
static double uniform_rand(double lowerBndr, double upperBndr){
return lowerBndr + ((double) std::rand() / (RAND_MAX + 1.0)) * (upperBndr - lowerBndr);
}
static double gauss_rand(double mean, double sigma){
double x, y, r2;
do {
x = -1.0 + 2.0 * uniform_rand(0.0, 1.0);
y = -1.0 + 2.0 * uniform_rand(0.0, 1.0);
r2 = x * x + y * y;
} while (r2 > 1.0 || r2 == 0.0);
return mean + sigma * y * std::sqrt(-2.0 * log(r2) / r2);
}
double uniform(){
return uniform_rand(0., 1.);
}
struct CamExtrinsic{
Eigen::Matrix3d R;
Eigen::Vector3d t;
};
vector<CamExtrinsic> genPose(int siz){
vector<CamExtrinsic> poses;
for(int i=0; i<siz; i++){
poses.emplace_back(CamExtrinsic{Eigen::Matrix3d::Identity(3,3), Eigen::Vector3d(0,0,i)});
}
return poses;
}
int main(){
vector<CamExtrinsic> poses = genPose(10);
g2o::SparseOptimizer optimizer;
auto linearSolverType = g2o::make_unique<g2o::LinearSolverCholmod<g2o::BlockSolverPL<6,1>::PoseMatrixType>>();
auto solver = g2o::make_unique<g2o::BlockSolverPL<6,1>>(std::move(linearSolverType));
g2o::OptimizationAlgorithmLevenberg* LMAlgo = new g2o::OptimizationAlgorithmLevenberg(std::move(solver));
optimizer.setAlgorithm(LMAlgo);
vector<g2o::VertexSE3Expmap*> se3Vertices;
int ID=0;
for(auto pose : poses){
g2o::SE3Quat curPose(pose.R, pose.t);
g2o::VertexSE3Expmap* vertex;
vertex->setId(ID);
vertex->setFixed(false);
curPose.setTranslation(curPose.translation()+2.0f*Vector3d(uniform(), uniform(), uniform()));
vertex->setEstimate(curPose);
se3Vertices.emplace_back(vertex);
optimizer.addVertex(vertex);
ID++;
g2o::EdgeSE3Expmap* constraint = new g2o::EdgeSE3Expmap();
}
}
<file_sep>/PyUtils/stereo_feature_est.py
import cv2
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
import math
import imutils
cam = cv2.VideoCapture(0)
K = [[647.8849454418848, 0.0, 312.70216601346215],
[0.0, 648.2741486235716, 245.95593954674428],
[0.0, 0.0, 1.0]]
K = np.array(K)
distCoeffs = [0.035547431486979156, -0.15592121266783593, 0.0005127230470698213, -0.004324823776384423, 1.2415990279352762]
distCoeffs = np.array(distCoeffs)
focal_len = 648.2741486235716
pp = (312.70216601346215, 245.95593954674428)
im1 = cv2.imread("/home/gautham/Documents/Codes/depth_reconstruct/opencv_frame_0.png")
im2 = cv2.imread("/home/gautham/Documents/Codes/depth_reconstruct/opencv_frame_3.png")
def odom(im1, im2):
im1 = cv.cvtColor(im1, cv2.COLOR_BGR2GRAY)
im2 = cv.cvtColor(im2, cv2.COLOR_BGR2GRAY)
orb = cv2.ORB_create()
kp1, descs1 = orb.detectAndCompute(im1,None)
kp2, descs2 = orb.detectAndCompute(im2,None)
#pts_1 = np.array([x.pt for x in kp1], dtype=np.float32)
#pts_2 = np.array([x.pt for x in kp2], dtype=np.float32)
matcher = cv2.BFMatcher()
matches = matcher.knnMatch(descs1, descs2, k=2)
good = []
pt1 = []
pt2 = []
for i,(m,n) in enumerate(matches):
if m.distance < 0.8*n.distance:
good.append(m)
pt2.append(kp2[m.trainIdx].pt)
pt1.append(kp1[m.queryIdx].pt)
pts1 = np.float32(pt1)
pts2 = np.float32(pt2)
F, mask = cv.findFundamentalMat(pts1,pts2,cv.FM_LMEDS)
pts1 = pts1[mask.ravel()==1]
pts2 = pts2[mask.ravel()==1]
pts11 = pts1.reshape(-1,1,2)
pts22 = pts2.reshape(-1,1,2)
pts1_norm = cv2.undistortPoints(pts11, cameraMatrix=K, distCoeffs=distCoeffs)
pts2_norm = cv2.undistortPoints(pts22, cameraMatrix=K, distCoeffs=distCoeffs)
E,mask = cv.findEssentialMat(pts1_norm, pts2_norm, focal=focal_len, pp=pp, method=cv2.RANSAC,prob=0.99, threshold=1.0)
r1, r2, t = cv.decomposeEssentialMat(E)
_,R,T,mask = cv.recoverPose(E,pts1_norm,pts2_norm,focal=focal_len,pp=pp)
M_r = np.hstack((R, T))
proj = np.dot(K,M_r)
print(R)
angles = cv2.decomposeProjectionMatrix(proj)[-1]
# y_rot = math.asin(R[2][0])
# y_rot_angle = y_rot *(180/3.1415)
# x_rot = math.acos(R[2][2]/math.cos(y_rot))
# z_rot = math.acos(R[0][0]/math.cos(y_rot))
# x_rot_angle = x_rot *(180/3.1415)
# z_rot_angle = z_rot *(180/3.1415)
print(angles[0],angles[1],angles[2])
#print(E)
def drawlines(img1,img2,lines,pts1,pts2):
''' img1 - image on which we draw the epilines for the points in img2
lines - corresponding epilines '''
r,c = img1.shape
img1 = cv.cvtColor(img1,cv.COLOR_GRAY2BGR)
img2 = cv.cvtColor(img2,cv.COLOR_GRAY2BGR)
for r,pt1,pt2 in zip(lines,pts1,pts2):
color = tuple(np.random.randint(0,255,3).tolist())
x0,y0 = map(int, [0, -r[2]/r[1] ])
x1,y1 = map(int, [c, -(r[2]+r[0]*c)/r[1] ])
img1 = cv.line(img1, (x0,y0), (x1,y1), color,1)
img1 = cv.circle(img1,tuple(pt1),5,color,-1)
img2 = cv.circle(img2,tuple(pt2),5,color,-1)
return img1,img2
# Find epilines corresponding to points in right image (second image) and
# drawing its lines on left image
lines1 = cv.computeCorrespondEpilines(pts2.reshape(-1,1,2), 2,F)
lines1 = lines1.reshape(-1,3)
img5,img6 = drawlines(im1,im2,lines1,pts1,pts2)
# Find epilines corresponding to points in left image (first image) and
# drawing its lines on right image
lines2 = cv.computeCorrespondEpilines(pts1.reshape(-1,1,2), 1,F)
lines2 = lines2.reshape(-1,3)
img3,img4 = drawlines(im2,im1,lines2,pts2,pts1)
return img3, img5
step = 0
while True:
imbuf = imutils.rotate(im1,step)
imL,imR = odom(im1,imbuf)
cv2.namedWindow("Test")
cv2.imshow("Test", imL)
cv2.namedWindow("Main")
cv2.imshow("Main", imR)
step+=10
k = cv.waitKey(0)
if step>90:
print("Angular Overflow")
break
if k%256 == 27:
print("Escape hit, closing...")
break
<file_sep>/visualOdometry/monocularBA.cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <thread>
#include "Eigen/Core"
#include <opencv2/core.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/xfeatures2d.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include "opencv2/highgui/highgui.hpp"
#include <opencv2/opencv.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/core/eigen.hpp>
#include <g2o/core/sparse_optimizer.h>
#include <g2o/core/block_solver.h>
#include <g2o/core/robust_kernel.h>
#include <g2o/core/robust_kernel_impl.h>
#include <g2o/core/optimization_algorithm_levenberg.h>
#include "g2o/solvers/cholmod/linear_solver_cholmod.h"
#include <g2o/solvers/eigen/linear_solver_eigen.h>
#include <g2o/types/slam3d/se3quat.h>
#include <g2o/types/sba/types_six_dof_expmap.h>
#include "g2o/core/sparse_optimizer.h"
#include "g2o/core/block_solver.h"
#include "g2o/core/solver.h"
#include "g2o/core/robust_kernel_impl.h"
#include "g2o/core/optimization_algorithm_levenberg.h"
#include "g2o/solvers/cholmod/linear_solver_cholmod.h"
#include "g2o/solvers/dense/linear_solver_dense.h"
#include "g2o/types/sba/types_six_dof_expmap.h"
#include "g2o/types/slam3d/edge_xyz_prior.h"
#include "g2o/types/slam3d/vertex_se3.h"
#include "g2o/types/slam3d/vertex_pointxyz.h"
#include "g2o/types/slam3d/edge_se3_pointxyz.h"
//#include "edge_se3exp_pointxyz_prior.h"
#include "g2o/solvers/structure_only/structure_only_solver.h"
// typedef g2o::BlockSolver<g2o::BlockSolverTraits<6, 6>> SlamBlockSolver;
// typedef g2o::LinearSolverEigen<SlamBlockSolver::PoseMatrixType> SlamLinearSolver;
typedef g2o::BlockSolver_6_3 SlamBlockSolver;
typedef g2o::LinearSolverEigen< SlamBlockSolver::PoseMatrixType > SlamLinearSolver;
using namespace std;
using namespace cv;
using namespace g2o;
struct FrameMetedata{
int ID = -1;
vector<Point2f> inliers;
vector<Point3f> projection;
Mat K, rvec, tvec, R,t;
};
struct FrameInfo{
std::vector<cv::Point2f> features2d;
std::vector<int> obj_indexes;
// std::vector<cv::Point3f> features3d;
cv::Mat rvec;
cv::Mat tvec;
};
vector<KeyPoint> denseKeypointExtractor(Mat img, int stepSize){
vector<KeyPoint> out;
for (int y=stepSize; y<img.rows-stepSize; y+=stepSize){
for (int x=stepSize; x<img.cols-stepSize; x+=stepSize){
out.push_back(KeyPoint(float(x), float(y), float(stepSize)));
}
}
return out;
}
void appendData(vector<float> data){
std::ofstream outfile;
outfile.open("/home/gautham/Documents/Projects/LargeScaleMapping/visualOdometry/trajectory.txt");
for(size_t i=0; i<data.size(); i+=7){
for(size_t j=0; j<7; j++){
outfile<<data[j];
outfile<<" ";
}
outfile<<"\n";
}
}
void pyrLKtracking(Mat refImg, Mat curImg, vector<Point2f>&refPts, vector<Point2f>&trackPts){
vector<Point2f> trPts, inlierRefPts, inlierTracked;
vector<uchar> Idx;
vector<float> err;
calcOpticalFlowPyrLK(refImg, curImg, refPts, trPts,Idx, err);
for(int i=0; i<refPts.size(); i++){
if(Idx[i]==1){
inlierRefPts.emplace_back(refPts[i]);
inlierTracked.emplace_back(trPts[i]);
}
}
trackPts.clear(); refPts.clear();
trackPts = inlierTracked; refPts = inlierRefPts;
}
void FmatThresholding(vector<Point2f>&refPts, vector<Point2f>&trkPts){
Mat F;
vector<uchar> mask;
vector<Point2f>inlierRef, inlierTrk;
F = findFundamentalMat(refPts, trkPts, CV_RANSAC, 3.0, 0.99, mask);
for(size_t j=0; j<mask.size(); j++){
if(mask[j]==1){
inlierRef.emplace_back(refPts[j]);
inlierTrk.emplace_back(trkPts[j]);
}
}
refPts.clear(); trkPts.clear();
refPts = inlierRef; trkPts = inlierTrk;
}
void FmatThresholding2(vector<Point2f>&refPts, vector<Point2f>&trkPts, vector<Point3f>&ref3d){
Mat F;
vector<uchar> mask;
vector<Point2f>inlierRef, inlierTrk; vector<Point3f> inlier3d;
F = findFundamentalMat(refPts, trkPts, CV_RANSAC, 3.0, 0.99, mask);
for(size_t j=0; j<mask.size(); j++){
if(mask[j]==1){
inlierRef.emplace_back(refPts[j]);
inlierTrk.emplace_back(trkPts[j]);
inlier3d.emplace_back(ref3d[j]);
}
}
refPts.clear(); trkPts.clear(); ref3d.clear();
refPts = inlierRef; trkPts = inlierTrk; ref3d = inlier3d;
}
cv::Mat Merge( const cv::Mat& rvec, const cv::Mat& tvec ){
cv::Mat R;
cv::Rodrigues( rvec, R );
cv::Mat T = cv::Mat::zeros(3,4, CV_64F);
T.at<double>(0,0) = R.at<double>(0,0);
T.at<double>(0,1) = R.at<double>(0,1);
T.at<double>(0,2) = R.at<double>(0,2);
T.at<double>(1,0) = R.at<double>(1,0);
T.at<double>(1,1) = R.at<double>(1,1);
T.at<double>(1,2) = R.at<double>(1,2);
T.at<double>(2,0) = R.at<double>(2,0);
T.at<double>(2,1) = R.at<double>(2,1);
T.at<double>(2,2) = R.at<double>(2,2);
T.at<double>(0,3) = tvec.at<double>(0);
T.at<double>(1,3) = tvec.at<double>(1);
T.at<double>(2,3) = tvec.at<double>(2);
// cv::hconcat(R, tvec, T);
// std::cout << T << std::endl;
return T;
}
// cvMat2Eigen
Eigen::Isometry3d cvMat2Eigen( const cv::Mat& rvec, const cv::Mat& tvec ){
cv::Mat R;
cv::Rodrigues( rvec, R );
Eigen::Matrix3d r;
for ( int i=0; i<3; i++ )
for ( int j=0; j<3; j++ )
r(i,j) = R.at<double>(i,j);
// 将平移向量和旋转矩阵转换成变换矩阵
Eigen::Isometry3d T = Eigen::Isometry3d::Identity();
Eigen::AngleAxisd angle(r);
T = angle;
T(0,3) = tvec.at<double>(0,0);
T(1,3) = tvec.at<double>(1,0);
T(2,3) = tvec.at<double>(2,0);
return T;
}
//将eigen 矩阵转换为opencv矩阵
cv::Mat Eigen2cvMat(const Eigen::Isometry3d& matrix) {
cv::Mat R = cv::Mat::zeros(3,3,CV_64F);
cv::Mat tvec = cv::Mat::zeros(1,3,CV_64F);
for ( int i=0; i<3; i++ )
for ( int j=0; j<3; j++ )
R.at<double>(i,j) = matrix(i,j);
tvec.at<double>(0) = matrix(0, 3);
tvec.at<double>(1) = matrix(1, 3);
tvec.at<double>(2) = matrix(2, 3);
tvec = -R.t()*tvec.t();
return tvec;
}
//欧拉 旋转 转换为 四元角 表达
g2o::SE3Quat euler2Quaternion(const cv::Mat& rvec, const cv::Mat& tvec )
{
// std::cout << rvec.size() << std::endl;
// std::cout << tvec.size() << std::endl;
cv::Mat R;
cv::Rodrigues( rvec, R );
double roll = rvec.at<double>(0,0);
double pitch = rvec.at<double>(1,0);
double yaw = rvec.at<double>(2,0);
Eigen::AngleAxisd rollAngle(roll, Eigen::Vector3d::UnitX());
Eigen::AngleAxisd yawAngle(pitch, Eigen::Vector3d::UnitY());
Eigen::AngleAxisd pitchAngle(yaw, Eigen::Vector3d::UnitZ());
Eigen::Quaterniond q = rollAngle * yawAngle * pitchAngle;
Eigen::Vector3d trans(tvec.at<double>(0), tvec.at<double>(1), tvec.at<double>(2));
g2o::SE3Quat pose(q,trans);
// std::cout << pose << std::endl;
// std::cout << trans << std::endl;
// assert(false);
return pose;
}
void print(const std::vector<FrameInfo>& frameinfo, g2o::SparseOptimizer& optimizer) {
for ( size_t i=0; i < frameinfo.size(); i++ )
{
// if ( i < frameinfo.size() - 1) continue;
g2o::VertexSE3Expmap* v = dynamic_cast<g2o::VertexSE3Expmap*> (optimizer.vertex(i));
// std::cout<<"vertex id "<<i<<", pos = " << std::endl;
Eigen::Isometry3d pose = v->estimate();
cv::Mat tvec = Eigen2cvMat(pose);
// std::cout<<pose.matrix()<<std::endl;
// g2o::SE3Quat pose2 = euler2Quaternion(frameinfo[i].rvec, frameinfo[i].tvec);
// std::cout<<pose2<<std::endl;
std::cout << "optimized: " << std::endl << tvec << std::endl;
cv::Mat R;
cv::Rodrigues( frameinfo[i].rvec, R );
std::cout<< "original: "<<std::endl << -R.t()*frameinfo[i].tvec <<std::endl;
}
}
class visualOdometry{
public:
int seqNo;
double baseline = 0.54;
string absPath;
const char* lFptr; const char* rFptr;
double focal_x = 7.188560000000e+02;
double cx = 6.071928000000e+02;
double focal_y = 7.188560000000e+02;
double cy = 1.852157000000e+02;
Mat K = (Mat1d(3,3) << focal_x, 0, cx, 0, focal_y, cy, 0, 0, 1);
Mat referenceImg, currentImage;
vector<Point3f> referencePoints3D;
vector<Point2f> referencePoints2D;
vector<Point2f> inlierReferencePyrLKPts;
Mat canvas = Mat::zeros(600,600, CV_8UC3);
Mat Rba, tba;
Mat ret;
std::queue<FrameMetedata> BAwindowQueue;
mutable std::vector<cv::Point3f> world_landmarks;
mutable std::vector<cv::Point3f> history_pose;
mutable std::vector<FrameInfo> framepoints;
visualOdometry(int Seq, const char*Lfptr, const char*Rfptr){
cout<<"\n\nINITIALIZING VISUAL ODOMETRY PIPELINE...\n\n"<<endl;
lFptr = Lfptr;
rFptr = Rfptr;
}
~visualOdometry(){
cout<<"\n\nDESTRUCTOR CALLED, TERMINATING PROCESS\n"<<endl;
}
void stereoTriangulate(Mat im1, Mat im2,
vector<Point3f>&ref3dPts,
vector<Point2f>&ref2dPts){
Ptr<FeatureDetector> detector = xfeatures2d::SURF::create(500);
//Ptr<FeatureDetector> detector = BRISK::create();
if(!im1.data || !im2.data){
cout<<"NULL IMG"<<endl;
return;
}
vector<KeyPoint> kp1, kp2;
Mat desc1, desc2;
// kp1 = denseKeypointExtractor(im1, 10);
// vector<Point2f> pt1;
// for(size_t i=0; i<kp1.size(); i++){
// pt1.emplace_back(kp1[i].pt);
// }
// vector<Point2f> pt2;
// pyrLKtracking(im1, im2, pt1, pt2);
// FmatThresholding(pt1, pt2);
std::thread left([&](){
detector->detect(im1, kp1);
detector->compute(im1, kp1, desc1);
});
std::thread right([&](){
detector->detect(im2, kp2);
detector->compute(im2, kp2, desc2);
});
left.join();
right.join();
desc1.convertTo(desc1, CV_32F);
desc2.convertTo(desc2, CV_32F);
BFMatcher matcher;
vector<vector<DMatch>> matches;
matcher.knnMatch(desc1, desc2, matches, 2);
vector<Point2f> pt1, pt2;
for(int i=0; i<matches.size(); i++){
DMatch &m = matches[i][0]; DMatch &n = matches[i][1];
if(m.distance<0.8*n.distance){
pt1.emplace_back(kp1[m.queryIdx].pt);
pt2.emplace_back(kp2[m.trainIdx].pt);
}
}
Mat E, mask, R, t;
E = findEssentialMat(pt1, pt2, K, 8, 0.99, 1, mask);
recoverPose(E, pt1, pt2, K, R, t,mask);
vector<Point3f> pts3d;
Mat P1 = Mat::zeros(3,4, CV_64F);
Mat P2 = Mat::zeros(3,4, CV_64F);
P1.at<double>(0,0) = 1; P1.at<double>(1,1) = 1; P1.at<double>(2,2) = 1;
P2.at<double>(0,0) = 1; P2.at<double>(1,1) = 1; P2.at<double>(2,2) = 1;
R.col(0).copyTo(P2.col(0));
R.col(1).copyTo(P2.col(1));
R.col(2).copyTo(P2.col(2));
t.copyTo(P2.col(3));
P1 = K*P1;
P2 = K*P2;
Mat est3d;
triangulatePoints(P1, P2, pt1, pt2, est3d);
//cout<<est3d.size()<<endl;
for(int i=0; i<est3d.cols; i++){
Point3f localpt;
localpt.x = est3d.at<float>(0,i) / est3d.at<float>(3,i);
localpt.y = est3d.at<float>(1,i) / est3d.at<float>(3,i);
localpt.z = est3d.at<float>(2,i) / est3d.at<float>(3,i);
pts3d.emplace_back(localpt);
}
vector<Point2f> reprojection;
for(int k=0; k<pts3d.size(); k++){
Point2f projection; Point3f pt3d = pts3d[k];
projection.x = pt3d.x; projection.y = pt3d.y;
reprojection.emplace_back(projection);
}
//cout<<reprojection.size()<<" PTSIZE "<<pt1.size()<<endl;
ret = drawDeltas(im2, pt1, reprojection);
ref3dPts = pts3d;
ref2dPts = pt1;
}
Mat drawDeltas(Mat im, vector<Point2f> in1, vector<Point2f> in2){
Mat frame;
im.copyTo(frame);
for(int i=0; i<in1.size(); i++){
Point2f pt1 = in1[i];
Point2f pt2 = in2[i];
line(frame, pt1, pt2, Scalar(0,255,0),1);
circle(frame, pt1, 5, Scalar(0,0,255));
circle(frame, pt2, 5, Scalar(255,0,0));
}
return frame;
}
void PyrLKtrackFrame2Frame(Mat refimg, Mat curImg, vector<Point2f>refPts, vector<Point3f>ref3dpts,
vector<Point2f>&refRetpts, vector<Point3f>&ref3dretPts, bool Fthresh){
vector<Point2f> trackPts;
vector<uchar> Idx;
vector<float> err;
calcOpticalFlowPyrLK(refimg, curImg, refPts, trackPts,Idx, err);
vector<Point2f> inlierRefPts;
vector<Point3f> inlierRef3dPts;
vector<Point2f> inlierTracked;
vector<int> res;
for(int j=0; j<refPts.size(); j++){
if(Idx[j]==1){
inlierRefPts.emplace_back(refPts[j]);
ref3dretPts.emplace_back(ref3dpts[j]);
refRetpts.emplace_back(trackPts[j]);
}
}
if(Fthresh){
FmatThresholding2(inlierRefPts, refRetpts, ref3dretPts);
}
inlierReferencePyrLKPts = inlierRefPts;
}
vector<int> removeDuplicates(vector<Point2f>&baseFeatures, vector<Point2f>&newFeatures,
vector<int>&mask, int radius=10){
vector<int> res;
for(int i=0; i<newFeatures.size(); i++){
Point2f&p2 = newFeatures[i];
bool inRange=false;
for(auto j:mask){
Point2f&p1 = baseFeatures[j];
if(norm(p1-p2)<radius){
inRange=true;
break;
}
}
if(!inRange){res.emplace_back(i);}
}
return res;
}
void create_new_features(int start, const Mat& inv_transform, std::vector<Point2f>& featurePoints, std::vector<Point3f>& landmarks){
if (featurePoints.size() != 0) {
featurePoints.clear();
landmarks.clear();
}
Mat curImage_L = loadImageL(start);
Mat curImage_R = loadImageL(start-1);
vector<Point3f> landmark_3D_new;
vector<Point2f> reference_2D_new;
//extract_keypoints_surf(curImage_L, curImage_R, landmark_3D_new, reference_2D_new);
stereoTriangulate(curImage_L, curImage_R, landmark_3D_new, reference_2D_new);
// // cout << inv_transform << endl;
for (int k = 0; k < landmark_3D_new.size(); k++) {
//
const Point3f& pt = landmark_3D_new[k];
Point3f p;
p.x = inv_transform.at<double>(0, 0)*pt.x + inv_transform.at<double>(0, 1)*pt.y + inv_transform.at<double>(0, 2)*pt.z + inv_transform.at<double>(0, 3);
p.y = inv_transform.at<double>(1, 0)*pt.x + inv_transform.at<double>(1, 1)*pt.y + inv_transform.at<double>(1, 2)*pt.z + inv_transform.at<double>(1, 3);
p.z = inv_transform.at<double>(2, 0)*pt.x + inv_transform.at<double>(2, 1)*pt.y + inv_transform.at<double>(2, 2)*pt.z + inv_transform.at<double>(2, 3);
// cout << p << endl;
if (p.z > 0) {
landmarks.push_back(p);
featurePoints.push_back(reference_2D_new[k]);
}
}
}
vector<int> removeDuplicate(const vector<Point2f>& baseFeaturePoints, const vector<Point2f>& newfeaturePoints,
const vector<int>& mask, int radius=10){
std::vector<int> res;
for (int j = 0; j < newfeaturePoints.size(); j++) {
const Point2f& p2 = newfeaturePoints[j];
bool within_range = false;
for (auto index : mask) {
const Point2f& p1 = baseFeaturePoints[index];
if (cv::norm(p1-p2) < radius) {
within_range = true;
break;
}
}
if (!within_range) res.push_back(j);
}
return res;
}
vector<Point2f> updateFrame(int i, const cv::Mat& inv_transform, const vector<Point2f>& featurePoints,
const vector<int>&tracked, const vector<int>& inliers, const Mat& rvec, const Mat& tvec){
vector<Point2f> new_2D;
vector<Point3f> new_3D;
create_new_features(i, inv_transform, new_2D, new_3D);
std::vector<Point2f> up_featurePoints;
const std::vector<int>& preIndexes = framepoints.back().obj_indexes;
vector<int> res = removeDuplicate(featurePoints, new_2D, inliers);
cout << res.size() << ": " << new_2D.size() << endl;
std::vector<int> indexes;
for (auto index : inliers) {
up_featurePoints.push_back(featurePoints[index]);
indexes.push_back(preIndexes[tracked[index]]);
}
int start = world_landmarks.size();
for (auto index : res) {
up_featurePoints.push_back(new_2D[index]);
world_landmarks.push_back(new_3D[index]);
indexes.push_back(start++);
}
///for check correctness
// for (int k = 0; k < landmarks.size(); k++) {
// if (landmarks[k] != world_landmarks[indexes[k]])
// throw std::invalid_argument("These two landmarks should be the same!");
// }
FrameInfo frameinfo;
frameinfo.features2d = up_featurePoints;
frameinfo.obj_indexes = indexes;
// frameinfo.features3d = landmarks;
frameinfo.rvec = rvec;
frameinfo.tvec = tvec;
framepoints.push_back(frameinfo);
if (framepoints.size() > 1000) {
framepoints.erase(framepoints.begin());
}
return up_featurePoints;
}
vector<int> tracking(const cv::Mat& ref_img, const cv::Mat& curImg, std::vector<Point2f>& featurePoints, std::vector<Point3f>& landmarks) {
vector<Point2f> nextPts;
vector<uchar> status;
vector<float> err;
calcOpticalFlowPyrLK(ref_img, curImg, featurePoints, nextPts, status, err);
std::vector<int> res;
featurePoints.clear();
// cout << featurePoints.size() << ", " << landmarks.size() << ", " << status.size() << endl;
for (int j = status.size()-1; j > -1; j--) {
if (status[j] != 1) {
// featurePoints.erase(featurePoints.begin()+j);
landmarks.erase(landmarks.begin()+j);
} else {
featurePoints.push_back(nextPts[j]);
res.push_back(j);
}
}
std::reverse(res.begin(),res.end());
std::reverse(featurePoints.begin(),featurePoints.end());
return res;
}
void relocalizeFrames(int start, Mat imL, Mat imR, Mat&inv_transform, vector<Point2f>&ftrPts, vector<Point3f>&pts3d){
vector<Point2f> new2d;
vector<Point3f> new3d;
ftrPts.clear();
pts3d.clear();
stereoTriangulate(imL, imR, new3d, new2d);
for(int i=0; i<new3d.size(); i++){
Point3f pt = new3d[i];
Point3f p;
p.x = inv_transform.at<double>(0,0)*pt.x + inv_transform.at<double>(0,1)*pt.y + inv_transform.at<double>(0,2)*pt.z + inv_transform.at<double>(0,3);
p.y = inv_transform.at<double>(1,0)*pt.x + inv_transform.at<double>(1,1)*pt.y + inv_transform.at<double>(1,2)*pt.z + inv_transform.at<double>(1,3);
p.z = inv_transform.at<double>(2,0)*pt.x + inv_transform.at<double>(2,1)*pt.y + inv_transform.at<double>(2,2)*pt.z + inv_transform.at<double>(2,3);
pts3d.emplace_back(p);
ftrPts.emplace_back(new2d[i]);
}
}
Mat loadImageL(int iter){
char FileName[200];
sprintf(FileName, lFptr, iter);
Mat im = imread(FileName);
if(!im.data){
cout<<"yikes, failed to fetch frame, check the paths"<<endl;
}
return im;
}
Mat loadImageR(int iter){
char FileName[200];
sprintf(FileName, rFptr, iter);
Mat im = imread(FileName);
if(!im.data){
cout<<"yikes, failed to fetch frame, check the paths"<<endl;
}
return im;
}
void initSequence(){
int iter = 1;
char FileName1[200], filename2[200];
sprintf(FileName1, lFptr, iter);
sprintf(filename2, rFptr, iter);
//PoseDatas* pose = new PoseDatas;
vector<FrameMetedata*> window;
Mat prevR, prevt;
// Mat imL = imread(FileName1);
// Mat imR = imread(filename2);
Mat imL = loadImageL(iter);
Mat imR = loadImageL(iter-1);
referenceImg = imL;
vector<Point2f> features;
vector<Point3f> pts3d;
stereoTriangulate(imL, imR, pts3d, features);
for(int iter=iter+1; iter<4000; iter+=1){
FrameMetedata* meta = new FrameMetedata;
cout<<"PROCESSING FRAME "<<iter<<endl;
currentImage = loadImageL(iter);
vector<Point3f> refPts3d; vector<Point2f> refFeatures;
PyrLKtrackFrame2Frame(referenceImg, currentImage, features, pts3d, refFeatures, refPts3d, true);
//cout<<" ref features "<<refPts3d.size()<<" refFeature size "<<refFeatures.size()<<endl;
Mat distCoeffs = Mat::zeros(4,1,CV_64F);
Mat rvec, tvec; vector<int> inliers;
//cout<<refPts3d.size()<<endl;
//cout<<refFeatures.size()<<" "<<inlierReferencePyrLKPts.size()<<" "<<refPts3d.size()<<endl;
solvePnPRansac(refPts3d, refFeatures, K, distCoeffs, rvec, tvec, false,100, 1.0, 0.99, inliers);
cout<<"Inlier Size : "<<inliers.size()<<endl;
if(inliers.size()<20 or tvec.at<double>(0)>1000){
cout<<"\n\nEyo What the fuck, skipping RANSAC layer and retracking\n"<<endl;
PyrLKtrackFrame2Frame(referenceImg, currentImage, features, pts3d, refFeatures, refPts3d, false);
solvePnPRansac(refPts3d, refFeatures, K, distCoeffs, rvec, tvec, false,100,4.0, 0.99, inliers);
if(inliers.size()<10 or tvec.at<double>(0)>1000){
cout<<"\n\n Damn bro inliers do be less, Skipping RANSAC all together, BA recommended\n"<<endl;
solvePnP(refPts3d, refFeatures, K, distCoeffs, rvec, tvec);
}
}
if(inliers.size()<10){
cout<<"Low inlier count at "<<refFeatures.size()<<", skipping RANSAC and using PnP "<<iter<<endl;
solvePnP(refPts3d, refFeatures, K, distCoeffs, rvec, tvec, false);
}
Mat R;
Rodrigues(rvec, R);
Mat Rba, tba;
R.copyTo(Rba); tvec.copyTo(tba);
R = R.t();
Mat t = -R*tvec;
meta->ID = iter;
meta->inliers = refFeatures;
meta->K = K;
meta->projection = refPts3d;
meta->rvec = rvec;
meta->R = R;
window.emplace_back(meta);
//BundleAdjust3d2d(features,pts3d, K, Rba, tba);
//tba = -Rba*tba;
//PoseDatas pose;
// pose.x = t.at<float>(0);
// pose.y = t.at<float>(1);
// pose.z = t.at<float>(3);
// pose.qa = quat.at<float>(0);
// pose.qb = quat.at<float>(1);
// pose.qc = quat.at<float>(2);
// pose.qd = quat.at<float>(3);
//poses.emplace_back(pose);
prevR = rvec; prevt = tvec;
Rba = Rba.t();
tba = -Rba*tba;
Mat inv_transform = Mat::zeros(3,4, CV_64F);
R.col(0).copyTo(inv_transform.col(0));
R.col(1).copyTo(inv_transform.col(1));
R.col(2).copyTo(inv_transform.col(2));
t.copyTo(inv_transform.col(3));
if(inliers.size()<200){
cerr<<"RELOCALIZING KeyFrame at "<<iter<<endl;
Mat i1 = loadImageL(iter); Mat i2 = loadImageR(iter);
relocalizeFrames(0, i1, i2, inv_transform, features, pts3d);
}
else{
features = refFeatures;
pts3d = refPts3d;
}
//create_new_features(iter, inv_transform, features, pts3d);
vector<Point3f> test3d;
//MonocularTriangulate(currentImage, referenceImg, refFeatures, inlierReferencePyrLKPts, test3d);
referenceImg = currentImage;
t.convertTo(t, CV_32F);
tba.convertTo(tba, CV_32F);
Mat frame = drawDeltas(currentImage, inlierReferencePyrLKPts, refFeatures);
Point2f center = Point2f(int(t.at<float>(0)) + 300, int(t.at<float>(2)) + 100);
Point2f centerBA = Point2f(int(tba.at<float>(0)) + 300, int(tba.at<float>(2)) + 100);
circle(canvas, center ,1, Scalar(0,0,255), 1);
//circle(canvas, centerBA ,1, Scalar(0,255,0), 1);
rectangle(canvas, Point2f(10, 30), Point2f(550, 50), Scalar(0,0,0), cv::FILLED);
imshow("frame", frame);
imshow("trajectory", canvas);
int k = waitKey(100);
if (k=='q'){
break;
}
}
cerr<<"Trajectory Saved"<<endl;
imwrite("Trajectory.png",canvas);
}
/*-------------------------------------EXPERIMENTAL SHIT BEGINS HERE-------------------------------------------------------------*/
void BundleAdjust3d2d(vector<Point2f>points_2d, vector<Point3f>points_3d, Mat&K, Mat&R, Mat&t){
typedef BlockSolver<BlockSolverTraits<6,3>>block;
typedef LinearSolverDense<block::PoseMatrixType> linearSolver;
auto solver = new g2o::OptimizationAlgorithmLevenberg(
g2o::make_unique<block>(g2o::make_unique<linearSolver>())
);
SparseOptimizer optimizer;
optimizer.initializeOptimization();
optimizer.setAlgorithm(solver);
optimizer.setVerbose(true);
VertexSE3Expmap* pose = new VertexSE3Expmap();
Eigen::Matrix3d Rmatrix;
Rmatrix<<R.at<double> ( 0,0 ), R.at<double> ( 0,1 ), R.at<double> ( 0,2 ),
R.at<double> ( 1,0 ), R.at<double> ( 1,1 ), R.at<double> ( 1,2 ),
R.at<double> ( 2,0 ), R.at<double> ( 2,1 ), R.at<double> ( 2,2 );
pose->setId(0);
pose->setEstimate(SE3Quat(Rmatrix, Eigen::Vector3d(t.at<double>(0,0), t.at<double>(1,0), t.at<double>(2,0))));
int count=1;
optimizer.addVertex(pose);
for(const Point3f p: points_3d){
VertexSBAPointXYZ* point = new VertexSBAPointXYZ();
point->setId(count);
point->setEstimate(Eigen::Vector3d(p.x, p.y, p.z));
point->setMarginalized(true);
optimizer.addVertex(point);
count++;
}
CameraParameters* cam = new CameraParameters(
K.at<double>(0,0), Eigen::Vector2d(K.at<double>(0,2), K.at<double>(1,2)), 0
);
cam->setId(0);
optimizer.addParameter(cam);
int edgeCount = 1;
for(const Point2f pt: points_2d){
EdgeProjectXYZ2UV* edge = new EdgeProjectXYZ2UV();
edge->setId(edgeCount);
edge->setVertex(0, dynamic_cast<g2o::VertexSBAPointXYZ*> ( optimizer.vertex(edgeCount)));
edge->setVertex(1, pose);
edge->setMeasurement(Eigen::Vector2d(pt.x, pt.y));
edge->setParameterId(0,0);
edge->setInformation(Eigen::Matrix2d::Identity());
optimizer.addEdge(edge);
edgeCount++;
}
//cout<<"T before="<<endl<<Eigen::Isometry3d ( pose->estimate() ).matrix() <<endl;
optimizer.initializeOptimization();
optimizer.optimize(15);
//cout<<"T after="<<endl<<Eigen::Isometry3d ( pose->estimate() ).matrix() <<endl;
SE3Quat postpose = pose->estimate();
Eigen::Vector3d trans = postpose.translation();
eigen2cv(trans, t);
optimizer.clear();
}
void playSequence(){
int startIndex = 1;
vector<Point3f> location_history;
Mat left_img = loadImageL(startIndex);
Mat right_img = loadImageL(startIndex-1);
Mat& ref_img = left_img;
// vector<Point3f> landmarks;
vector<Point2f> featurePoints;
//vector<int> landmarks;
bool visualize = true;
//bool bundle = true;
// int optimized_frame = ;
//extract_keypoints_surf(left_img, right_img, landmarks, featurePoints);
//extract_keypoints_surf(left_img, right_img, world_landmarks, featurePoints);
stereoTriangulate(left_img, right_img, world_landmarks,featurePoints );
// cout << featurePoints[0] << endl;
// cout << landmarks[0] << endl;
// vector<FrameInfo> framepoints;
//initilize the first frame with the below parameters
{
FrameInfo frameinfo;
frameinfo.features2d = featurePoints;
for (int i = 0; i < featurePoints.size(); i++) frameinfo.obj_indexes.push_back(i);
// frameinfo.features3d = landmarks;
// world_landmarks = landmarks;
frameinfo.rvec = Mat::zeros(3,1,CV_64F);
frameinfo.tvec = Mat::zeros(3,1,CV_64F);
framepoints.push_back(frameinfo);
}
int start = 0;
Mat curImg;
bool bundle=true;
Mat traj = Mat::zeros(600, 600, CV_8UC3);
for(int i = startIndex + 1; i < 4000; i+=1) {
cout << i << endl;
curImg = loadImageL(i);
//std::vector<Point3f> landmarks_ref, landmarks;
//std::vector<Point2f> featurePoints_ref;
std::vector<Point3f> landmarks;
featurePoints = framepoints.back().features2d;
for (auto index : framepoints.back().obj_indexes) {
landmarks.push_back(world_landmarks[index]);
}
vector<int> tracked = tracking(ref_img, curImg, featurePoints, landmarks);// landmarks_ref, featurePoints_ref);
// cout << featurePoints.size() << ", " << landmarks.size() << endl;
if (landmarks.size() < 10) continue;
Mat dist_coeffs = Mat::zeros(4,1,CV_64F);
Mat rvec, tvec;
vector<int> inliers;
// cout << featurePoints.size() << ", " << landmarks.size() << endl;
solvePnPRansac(landmarks, featurePoints, K, dist_coeffs,rvec, tvec,false, 100, 8.0, 0.99, inliers);// inliers);
if (inliers.size() < 5) continue;
// cout << "Norm: " << normofTransform(rvec- framepoints.back().rvec, tvec - framepoints.back().tvec) << endl;
// if ( normofTransform(rvec- framepoints.back().rvec, tvec - framepoints.back().tvec) > 2 ) continue;
// if (normofTransform(rvec, tvec) > 0.3) continue;
float inliers_ratio = inliers.size()/float(landmarks.size());
cout << "inliers ratio: " << inliers_ratio << endl;
cerr<<i<<endl;
Mat R_matrix;
Rodrigues(rvec,R_matrix);
R_matrix = R_matrix.t();
Mat t_vec = -R_matrix*tvec;
// cout << t_vec << endl;
Mat inv_transform = Mat::zeros(3,4,CV_64F);
R_matrix.col(0).copyTo(inv_transform.col(0));
R_matrix.col(1).copyTo(inv_transform.col(1));
R_matrix.col(2).copyTo(inv_transform.col(2));
t_vec.copyTo(inv_transform.col(3));
featurePoints = updateFrame(i, inv_transform, featurePoints, tracked, inliers, rvec, tvec);
if (featurePoints.size() == 0) continue;
//featurePoints = up_featurePoints;
ref_img = curImg;
t_vec.convertTo(t_vec, CV_32F);
if (bundle && (framepoints.size() == 500 || i == 4000 - 1)) {
cerr<<"BA time"<<endl;
Point3f p3 = BundleAdjust2(framepoints, world_landmarks, location_history, K);
framepoints.erase(framepoints.begin()+1, framepoints.end()-1);
history_pose.push_back(p3);
} else {
history_pose.push_back(Point3f(t_vec.at<float>(0), t_vec.at<float>(1), t_vec.at<float>(2)));
}
//cout << t_vec.t() << endl;
//cout << "truth" << endl;
//cout << "["<<poses[i][3] << ", " << poses[i][7] << ", " << poses[i][11] <<"]"<<endl;
if (visualize) {
// plot the information
string text = "Red color: estimated trajectory";
string text2 = "Blue color: Groundtruth trajectory";
// cout << framepoints.size() << endl;
// cout << t_vec.t() << endl;
// cout << "["<<poses[i][3] << ", " << poses[i][7] << ", " << poses[i][11] <<"]"<<endl;
Mat tdraw = t_vec.clone();
tdraw*=0.4;
Point2f center = Point2f(int(tdraw.at<float>(0)) + 300, int(tdraw.at<float>(2)) + 100);
//Point2f center2 = Point2f(int(poses[i][3]) + 300, int(poses[i][11]) + 100);
circle(traj, center , 1, Scalar(0,0,255), 1);
//circle(traj, center2, 1, Scalar(255,0,0), 1);
rectangle(traj, Point2f(10, 30), Point2f(550, 50), Scalar(0,0,0), cv::FILLED);
putText(traj, text, Point2f(10,50), cv::FONT_HERSHEY_PLAIN, 1, Scalar(0, 0,255), 1, 5);
putText(traj, text2, Point2f(10,70), cv::FONT_HERSHEY_PLAIN, 1, Scalar(255,0,0), 1, 5);
if (bundle) {
string text1 = "Green color: bundle adjusted trajectory";
for (const auto& p3 : location_history) {
int xc = int(p3.x)*0.4;
int zc = int(p3.z)*0.4;
Point2f center1 = Point2f(int(xc) + 300, int(zc) + 100);
circle(traj, center1, 1, Scalar(0,255,0), 1);
}
location_history.clear();
putText(traj, text1, Point2f(10,90), cv::FONT_HERSHEY_PLAIN, 1, Scalar(0,255,0), 1, 5);
}
imshow( "Trajectory", traj);
waitKey(1);
}
}
// if (bundle) {
// // BundleAdjust2(framepoints, world_landmarks, history_pose, K);
// }
if (visualize) {
// if (bundle) {
// string text1 = "Green color: bundle adjusted trajectory";
// putText(traj, text1, Point2f(10,90), cv::FONT_HERSHEY_PLAIN, 1, Scalar(0,255,0), 1, 5);
// for (const auto& p3 : history_pose) {
// Point2f center1 = Point2f(int(p3.x) + 300, int(p3.z) + 100);
// circle(traj, center1, 1, Scalar(0,255,0), 1);
// }
// imshow( "Trajectory", traj);
// }
imwrite("map2.png", traj);
waitKey(0);
}
}
cv::Point3f BundleAdjust2(std::vector<FrameInfo>& frameinfo, std::vector<cv::Point3f>& world_points, std::vector<cv::Point3f>& history_poses, const cv::Mat& K) {
// g2o::SparseOptimizer optimizer;
// auto linearSolver = g2o::make_unique<SlamLinearSolver>();
// linearSolver->setBlockOrdering( false );
// // L-M 下降
// g2o::OptimizationAlgorithmLevenberg* algorithm = new g2o::OptimizationAlgorithmLevenberg(g2o::make_unique<SlamBlockSolver>(std::move(linearSolver)));
// optimizer.setAlgorithm( algorithm );
// optimizer.setVerbose( false );
SlamLinearSolver* linearSolver = new SlamLinearSolver();
linearSolver->setBlockOrdering( false );
//SlamBlockSolver* blockSolver = new SlamBlockSolver( linearSolver );
// g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg(
// g2o::make_unique<g2o::BlockSolverX>(
// g2o::make_unique<g2o::LinearSolverEigen<g2o::BlockSolverX::PoseMatrixType>>()));
g2o::OptimizationAlgorithm* solver = new g2o::OptimizationAlgorithmLevenberg(
g2o::make_unique<SlamBlockSolver>(g2o::make_unique<SlamLinearSolver>())
);
g2o::SparseOptimizer optimizer; // 最后用的就是这个东东
optimizer.setAlgorithm( solver );
// 不要输出调试信息
optimizer.setVerbose( true );
//camera information
g2o::CameraParameters* camera = new g2o::CameraParameters(K.at<double>(0,0), Eigen::Vector2d(K.at<double>(0,2), K.at<double>(1,2)), 0 );
camera->setId(0);
optimizer.addParameter( camera);
int size = frameinfo.size();
//add vertext
for ( int i=0; i< size; i++ )
{
g2o::VertexSE3Expmap* v = new g2o::VertexSE3Expmap();
v->setId(i);
if ( i == 0) v->setFixed( true );
// Eigen::Isometry3d T = cvMat2Eigen(frameinfo[i].rvec, frameinfo[i].tvec);
g2o::SE3Quat pose = euler2Quaternion(frameinfo[i].rvec, frameinfo[i].tvec);
v->setEstimate( pose );
optimizer.addVertex( v );
}
int startIndex = size;
std::cout <<"start Index: " << startIndex << std::endl;
std::unordered_map<int, int> has_seen;
int count = 0;
for (int i = 0; i < size; i++) {
const FrameInfo& frame = frameinfo[i];
for (int j = 0; j < frame.obj_indexes.size(); j++) {
int index = frame.obj_indexes[j];
int currentNodeIndex = startIndex;
if (has_seen.find(index) == has_seen.end()) {
//add the landmark
g2o::VertexSBAPointXYZ* v = new g2o::VertexSBAPointXYZ();
v->setId(startIndex);
v->setMarginalized(true);
cv::Point3f w_point = world_points[index];
v->setEstimate(Eigen::Vector3d(w_point.x, w_point.y, w_point.z));
optimizer.addVertex( v );
has_seen[index] = startIndex;
startIndex++;
} else {
currentNodeIndex = has_seen[index];
}
//add the edges
g2o::EdgeProjectXYZ2UV* edge = new g2o::EdgeProjectXYZ2UV();
edge->setVertex( 0, dynamic_cast<g2o::VertexSBAPointXYZ*> (optimizer.vertex(currentNodeIndex)));
edge->setVertex( 1, dynamic_cast<g2o::VertexSE3Expmap*> (optimizer.vertex(i)));
edge->setMeasurement( Eigen::Vector2d(frame.features2d[j].x, frame.features2d[j].y));
edge->setInformation( Eigen::Matrix2d::Identity() );
edge->setParameterId(0, 0);
edge->setRobustKernel( new g2o::RobustKernelHuber() );
optimizer.addEdge( edge );
}
}
std::cout<<"optimizing pose graph, vertices: "<<optimizer.vertices().size()<<std::endl;
optimizer.save("sba.g2o");
optimizer.initializeOptimization();
optimizer.optimize(20); //可以指定优化步数
cerr<<"BA1"<<endl;
// 以及所有特征点的位置
// print(frameinfo, optimizer);
g2o::VertexSE3Expmap* v = dynamic_cast<g2o::VertexSE3Expmap*> (optimizer.vertex(size-1));
Eigen::Isometry3d pose = v->estimate();
cv::Mat tvec = Eigen2cvMat(pose);
// std::cout << "tvec is : " << tvec.at<double>(0) << ", " << tvec.at<double>(1) << ", " << tvec.at<double>(2) << std::endl;
// history_poses.push_back(cv::Point3f(tvec.at<double>(0), tvec.at<double>(1), tvec.at<double>(2)));
{
// g2o::VertexSE3Expmap* v = dynamic_cast<g2o::VertexSE3Expmap*> (optimizer.vertex(i));
// Eigen::Isometry3d pose = v->estimate();
// cv::Mat tvec = Eigen2cvMat(pose);
for ( size_t i=2; i < frameinfo.size(); i++ )
{
g2o::VertexSE3Expmap* v = dynamic_cast<g2o::VertexSE3Expmap*> (optimizer.vertex(i));
Eigen::Isometry3d pose = v->estimate();
cv::Mat t_vec = Eigen2cvMat(pose);
//cv::Mat R;
//cv::Rodrigues( frameinfo[i].rvec, R );
//cv::Mat t_vec = -R.t()*frameinfo[i].tvec;
history_poses.push_back(cv::Point3f(t_vec.at<double>(0), t_vec.at<double>(1), t_vec.at<double>(2)));
}
// for (auto& item : has_seen) {
// g2o::VertexSBAPointXYZ* v = dynamic_cast<g2o::VertexSBAPointXYZ*> (optimizer.vertex(item.second));
// Eigen::Vector3d pos = v->estimate();
// world_points[item.first] = cv::Point3f(pos[0], pos[1], pos[2]);
// }
}
optimizer.clear();
std::cout<<"Optimization done."<<std::endl;
return cv::Point3f(tvec.at<double>(0), tvec.at<double>(1), tvec.at<double>(2));
}
};
int main(){
const char* impathL = "/media/gautham/Seagate Backup Plus Drive/Datasets/dataset/sequences/00/image_0/%0.6d.png";
const char* impathR = "/media/gautham/Seagate Backup Plus Drive/Datasets/dataset/sequences/00/image_1/%0.6d.png";
vector<Point2f> ref2d; vector<Point3f> ref3d;
visualOdometry VO(0, impathL, impathR);
char FileName1[200], filename2[200];
sprintf(FileName1, impathL, 0);
sprintf(filename2, impathR, 0);
Mat im1 = imread(FileName1);
Mat im2 = imread(filename2);
//VO.stereoTriangulate(im1, im2, ref3d, ref2d);
//visualOdometry* VO = new visualOdometry(0, impathR, impathL);
VO.initSequence();
}
<file_sep>/SFM_pipeline/multiview_reconstruct.cpp
//LSM <NAME> OCT-2020
#include <opencv2/features2d.hpp>
#include <opencv2/xfeatures2d.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/viz.hpp>
#include <opencv2/xfeatures2d/nonfree.hpp>
#include <gtsam/geometry/Point2.h>
#include <gtsam/inference/Symbol.h>
#include <gtsam/slam/PriorFactor.h>
#include <gtsam/slam/ProjectionFactor.h>
#include <gtsam/slam/GeneralSFMFactor.h>
#include <gtsam/nonlinear/NonlinearFactorGraph.h>
#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>
#include <gtsam/nonlinear/DoglegOptimizer.h>
#include <gtsam/nonlinear/Values.h>
#include <vector>
#include <iostream>
#include <map>
#include <fstream>
#include <cassert>
#include "meta.h"
using namespace std;
using namespace cv;
const std::string IMAGE_DIR = "";
const std::string img_dir3 = "/home/gautham/Documents/Datasets/Statue2/*.jpg";
const std::string img_dir2 = "/home/gautham/Documents/Datasets/SfM_quality_evaluation/Benchmarking_Camera_Calibration_2008/fountain-P11/images/Testing/*.jpg";
std::vector<std::string> IMAGES;
vector<cv::String> impath;
struct SFM_metadata{
struct ImagePose{
cv::Mat img;
cv::Mat desc;
std::vector<cv::KeyPoint> kp;
cv::Mat T;
cv::Mat P;
using kp_idx_t = size_t;
using landmark_idx_t = size_t;
using img_idx_t = size_t;
std::map<kp_idx_t, std::map<img_idx_t, kp_idx_t>> kp_matches;
std::map<kp_idx_t, landmark_idx_t> kp_landmark;
kp_idx_t& kp_match_idx(size_t kp_idx, size_t img_idx) { return kp_matches[kp_idx][img_idx]; };
bool kp_match_exist(size_t kp_idx, size_t img_idx) { return kp_matches[kp_idx].count(img_idx) > 0; };
landmark_idx_t& kp_3d(size_t kp_idx) { return kp_landmark[kp_idx]; }
bool kp_3d_exist(size_t kp_idx) { return kp_landmark.count(kp_idx) > 0; }
};
struct Landmark{
cv::Point3f pt;
int seen = 0;
};
std::vector<ImagePose> img_pose;
std::vector<Landmark> landmark;
};
struct dataType {
cv::Point3d point;
int red;
int green;
int blue;
};
typedef dataType SpacePoint;
vector<SpacePoint> pointCloud;
void toPly(){
ofstream outfile("/home/gautham/Documents/Codes/pointcloud.ply");
outfile << "ply\n" << "format ascii 1.0\n" << "comment VTK generated PLY File\n";
outfile << "obj_info vtkPolyData points and polygons : vtk4.0\n" << "element vertex " << pointCloud.size() << "\n";
outfile << "property float x\n" << "property float y\n" << "property float z\n" << "element face 0\n";
outfile << "property list uchar int vertex_indices\n" << "end_header\n";
for (int i = 0; i < pointCloud.size(); i++)
{
Point3d point = pointCloud.at(i).point;
outfile << point.x << " ";
outfile << point.y << " ";
outfile << point.z << " ";
outfile << "\n";
}
cout<<"PLY SAVE DONE"<<endl;
outfile.close();
}
class GTSAMBundleAdjust{
public:
gtsam::Values output;
gtsam::Cal3_S2 K_mat;
SFM_metadata SFM;
GTSAMBundleAdjust(SFM_metadata observations){
SFM = observations;
}
void FactorGraphOptimize(){
using namespace gtsam;
double cx = SFM.img_pose[0].img.size().width/2;
double cy = SFM.img_pose[0].img.size().height/2;
gtsam::Cal3_S2 K(FOCAL_LENGTH, FOCAL_LENGTH,0,cx,cy);
gtsam::noiseModel::Isotropic::shared_ptr measurement_noise = gtsam::noiseModel::Isotropic::Sigma(2,2.0);
gtsam::NonlinearFactorGraph graph;
gtsam::Values initial;
for(size_t i=0; i<SFM.img_pose.size(); i++){
auto &img_pose = SFM.img_pose[i];
gtsam::Rot3 R(
img_pose.T.at<double>(0,0),
img_pose.T.at<double>(0,1),
img_pose.T.at<double>(0,2),
img_pose.T.at<double>(1,0),
img_pose.T.at<double>(1,1),
img_pose.T.at<double>(1,2),
img_pose.T.at<double>(2,0),
img_pose.T.at<double>(2,1),
img_pose.T.at<double>(2,2)
);
gtsam::Point3 t;
t(0) = img_pose.T.at<double>(0,3);
t(1) = img_pose.T.at<double>(1,3);
t(2) = img_pose.T.at<double>(2,3);
gtsam::Pose3 pose(R,t);
if(i==0){
gtsam::noiseModel::Diagonal::shared_ptr pose_noise = gtsam::noiseModel::Diagonal::Sigmas((Vector(6) << Vector3::Constant(0.1), Vector3::Constant(0.1)).finished());
graph.emplace_shared<gtsam::PriorFactor<gtsam::Pose3>>(gtsam::Symbol('x',0),pose,pose_noise);
}
initial.insert(gtsam::Symbol('x',i),pose);
for (size_t k=0; k < img_pose.kp.size(); k++) {
if (img_pose.kp_3d_exist(k)) {
size_t landmark_id = img_pose.kp_3d(k);
if (SFM.landmark[landmark_id].seen >= MIN_LANDMARK_SEEN) {
gtsam::Point2 pt;
pt(0) = img_pose.kp[k].pt.x;
pt(1) = img_pose.kp[k].pt.y;
graph.emplace_shared<gtsam::GeneralSFMFactor2<gtsam::Cal3_S2>>(pt, measurement_noise, gtsam::Symbol('x', i), gtsam::Symbol('l', landmark_id), gtsam::Symbol('K', 0));
}
}
}
}
initial.insert(Symbol('K', 0), K);
noiseModel::Diagonal::shared_ptr cal_noise = noiseModel::Diagonal::Sigmas((Vector(5) << 100, 100, 0.01 /*skew*/, 100, 100).finished());
graph.emplace_shared<PriorFactor<Cal3_S2>>(Symbol('K', 0), K, cal_noise);
bool init_prior = false;
for (size_t i=0; i < SFM.landmark.size(); i++) {
if (SFM.landmark[i].seen >= MIN_LANDMARK_SEEN) {
cv::Point3f &p = SFM.landmark[i].pt;
initial.insert<Point3>(Symbol('l', i), Point3(p.x, p.y, p.z));
if (!init_prior) {
init_prior = true;
noiseModel::Isotropic::shared_ptr point_noise = noiseModel::Isotropic::Sigma(3, 0.1);
Point3 p(SFM.landmark[i].pt.x, SFM.landmark[i].pt.y, SFM.landmark[i].pt.z);
graph.emplace_shared<PriorFactor<Point3>>(Symbol('l', i), p, point_noise);
}
}
}
output = LevenbergMarquardtOptimizer(graph, initial).optimize();
output.print("");
cout << endl;
cout << "initial graph error = " << graph.error(initial) << endl;
cout << "final graph error = " << graph.error(output) << endl;
K_mat = K;
}
void PMVSformatting(){
using namespace gtsam;
Matrix3 K_refined = output.at<Cal3_S2>(Symbol('K', 0)).K();
cout << endl << "final camera matrix K" << endl << K_refined << endl;
K_refined(0, 0) *= IMAGE_DOWNSAMPLE;
K_refined(1, 1) *= IMAGE_DOWNSAMPLE;
K_refined(0, 2) *= IMAGE_DOWNSAMPLE;
K_refined(1, 2) *= IMAGE_DOWNSAMPLE;
system("mkdir -p root/visualize");
system("mkdir -p root/txt");
system("mkdir -p root/models");
ofstream option("root/options.txt");
option << "timages -1 " << 0 << " " << (SFM.img_pose.size()-1) << endl;;
option << "oimages 0" << endl;
option << "level 1" << endl;
option.close();
for (size_t i=0; i < SFM.img_pose.size(); i++) {
Eigen::Matrix<double, 3, 3> R;
Eigen::Matrix<double, 3, 1> t;
Eigen::Matrix<double, 3, 4> P;
char str[256];
R = output.at<Pose3>(Symbol('x', i)).rotation().matrix();
t = output.at<Pose3>(Symbol('x', i)).translation().matrix();
P.block(0, 0, 3, 3) = R.transpose();
P.col(3) = -R.transpose()*t;
P = K_refined*P;
sprintf(str, "cp -f %s/%s root/visualize/%04d.jpg", IMAGE_DIR.c_str(), IMAGES[i].c_str(), (int)i);
system(str);
//imwrite(str, SFM.img_pose[i].img);
sprintf(str, "root/txt/%04d.txt", (int)i);
ofstream out(str);
out << "CONTOUR" << endl;
for (int j=0; j < 3; j++) {
for (int k=0; k < 4; k++) {
out << P(j, k) << " ";
}
out << endl;
}
}
cout << endl;
cout << "Ready to compute PMVS2, options saved at root dir" << endl;
}
};
class SFMtoolkit{
public:
SFM_metadata SFM;
void feature_proc(){
using namespace cv;
using namespace cv::xfeatures2d;
//Ptr<AKAZE> feature = AKAZE::create();
//Ptr<SIFT> feature = SIFT::create();
Ptr<ORB> feature = ORB::create(10000);
//Ptr<SURF> feature = SURF::create();
Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create("BruteForce-Hamming");
namedWindow("img", WINDOW_NORMAL);
cout<<"CKPT 1 "<<endl;
cv::glob(img_dir2, impath, false);
for (auto f : impath) {
cout<<"Image ::: "<<f<<endl;
IMAGES.push_back(f);
SFM_metadata::ImagePose a;
Mat img = imread(f);
assert(!img.empty());
resize(img, img, img.size()/IMAGE_DOWNSAMPLE);
a.img = img;
cvtColor(img, img, COLOR_BGR2GRAY);
feature->detect(img, a.kp);
feature->compute(img, a.kp, a.desc);
SFM.img_pose.emplace_back(a);
}
}
void FeatureMatch(){
using namespace cv;
using namespace xfeatures2d;
Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create(DescriptorMatcher::BRUTEFORCE_HAMMING);
cout<<"CKPT 2 "<<endl;
int count = 0;
for (size_t i=0; i < SFM.img_pose.size()-1; i++) {
auto &img_pose_i = SFM.img_pose[i];
for (size_t j=i+1; j < SFM.img_pose.size(); j++) {
auto &img_pose_j = SFM.img_pose[j];
vector<vector<DMatch>> matches;
vector<Point2f> src, dst;
vector<uchar> mask;
vector<int> i_kp, j_kp;
matcher->knnMatch(img_pose_i.desc, img_pose_j.desc, matches, 2);
for (auto &m : matches) {
if(m[0].distance < 0.7*m[1].distance) {
src.push_back(img_pose_i.kp[m[0].queryIdx].pt);
dst.push_back(img_pose_j.kp[m[0].trainIdx].pt);
i_kp.push_back(m[0].queryIdx);
j_kp.push_back(m[0].trainIdx);
}
}
findFundamentalMat(src, dst, FM_RANSAC, 3.0, 0.99, mask);
Mat canvas = img_pose_i.img.clone();
Mat buffer_canvas = img_pose_j.img.clone();
cv::drawKeypoints(canvas, img_pose_i.kp, canvas,Scalar(255,0,0));
cv::drawKeypoints(buffer_canvas, img_pose_j.kp, buffer_canvas,Scalar(0,0,255));
canvas.push_back(buffer_canvas);
for (size_t k=0; k < mask.size(); k++) {
if (mask[k]) {
img_pose_i.kp_match_idx(i_kp[k], j) = j_kp[k];
img_pose_j.kp_match_idx(j_kp[k], i) = i_kp[k];
line(canvas, src[k], dst[k] + Point2f(0, img_pose_i.img.rows), Scalar(0, 255, 0), 1);
}
}
int good_matches = sum(mask)[0];
assert(good_matches >= 10);
cout << "Feature matching " << i << " " << j << " ==> " << good_matches << "/" << matches.size() << endl;
resize(canvas, canvas, canvas.size()/2);
if(count>0){
cv::namedWindow("img");
imshow("img", canvas);
waitKey(1000);
}
count++;
}
cv::destroyAllWindows();
}
}
void sfm_reconstruct(){
using namespace cv;
using namespace viz;
double cx = SFM.img_pose[0].img.size().width/2;
double cy = SFM.img_pose[0].img.size().height/2;
Point2d pp(cx, cy);
Mat K = Mat::eye(3, 3, CV_64F);
K.at<double>(0,0) = FOCAL_LENGTH;
K.at<double>(1,1) = FOCAL_LENGTH;
K.at<double>(0,2) = cx;
K.at<double>(1,2) = cy;
cout << endl << "initial camera matrix K " << endl << K << endl << endl;
SFM.img_pose[0].T = Mat::eye(4, 4, CV_64F);
SFM.img_pose[0].P = K*Mat::eye(3, 4, CV_64F);
for (size_t i=0; i < SFM.img_pose.size() - 1; i++) {
auto &prev = SFM.img_pose[i];
auto &cur = SFM.img_pose[i+1];
vector<Point2f> src, dst;
vector<size_t> kp_used;
for (size_t k=0; k < prev.kp.size(); k++) {
if (prev.kp_match_exist(k, i+1)) {
size_t match_idx = prev.kp_match_idx(k, i+1);
src.push_back(prev.kp[k].pt);
dst.push_back(cur.kp[match_idx].pt);
kp_used.push_back(k);
}
}
Mat mask;
Mat E = findEssentialMat(dst, src, FOCAL_LENGTH, pp, RANSAC, 0.999, 1.0, mask);
Mat local_R, local_t;
//cout<<E<<endl;
recoverPose(E, dst, src, local_R, local_t, FOCAL_LENGTH, pp, mask);
Mat T = Mat::eye(4, 4, CV_64F);
local_R.copyTo(T(Range(0, 3), Range(0, 3)));
local_t.copyTo(T(Range(0, 3), Range(3, 4)));
cur.T = prev.T*T;
Mat R = cur.T(Range(0, 3), Range(0, 3));
Mat t = cur.T(Range(0, 3), Range(3, 4));
Mat P(3, 4, CV_64F);
P(Range(0, 3), Range(0, 3)) = R.t();
P(Range(0, 3), Range(3, 4)) = -R.t()*t;
P = K*P;
cur.P = P;
Mat points4D;
triangulatePoints(prev.P, cur.P, src, dst, points4D);
if (i > 0) {
double scale = 0;
int count = 0;
Point3f prev_camera;
prev_camera.x = prev.T.at<double>(0, 3);
prev_camera.y = prev.T.at<double>(1, 3);
prev_camera.z = prev.T.at<double>(2, 3);
vector<Point3f> new_pts;
vector<Point3f> existing_pts;
cout<<"KP USED size : "<<kp_used.size()<<endl;
for (size_t j=0; j < kp_used.size(); j++) {
size_t k = kp_used[j];
//cout<<" Mask.at j : "<<mask.at<uchar>(j)<<" prev.kp_ex : "<<prev.kp_match_exist(k, i+1)<<" prev.kp3d_ex : "<<prev.kp_3d_exist(k)<<endl;
if (mask.at<uchar>(j) && prev.kp_match_exist(k, i+1) && prev.kp_3d_exist(k)) {
Point3f pt3d;
pt3d.x = points4D.at<float>(0, j) / points4D.at<float>(3, j);
pt3d.y = points4D.at<float>(1, j) / points4D.at<float>(3, j);
pt3d.z = points4D.at<float>(2, j) / points4D.at<float>(3, j);
size_t idx = prev.kp_3d(k);
Point3f avg_landmark = SFM.landmark[idx].pt / (SFM.landmark[idx].seen - 1);
count++;
new_pts.push_back(pt3d);
existing_pts.push_back(avg_landmark);
}
}
cout<<"NEW point size is as : "<<new_pts.size()<<endl;
if(new_pts.size()<=0){
cout<<"SKIPPING FRAME"<<endl;
continue;
}
for (size_t j=0; j < new_pts.size()-1; j++) {
for (size_t k=j+1; k< new_pts.size(); k++) {
double s = norm(existing_pts[j] - existing_pts[k]) / norm(new_pts[j] - new_pts[k]);
scale += s;
count++;
}
}
assert(count > 0);
scale /= count;
cout << "image " << (i+1) << " ==> " << i << " scale=" << scale << " count=" << count << endl;
local_t *= scale;
Mat T = Mat::eye(4, 4, CV_64F);
local_R.copyTo(T(Range(0, 3), Range(0, 3)));
local_t.copyTo(T(Range(0, 3), Range(3, 4)));
cur.T = prev.T*T;
R = cur.T(Range(0, 3), Range(0, 3));
t = cur.T(Range(0, 3), Range(3, 4));
Mat P(3, 4, CV_64F);
P(Range(0, 3), Range(0, 3)) = R.t();
P(Range(0, 3), Range(3, 4)) = -R.t()*t;
P = K*P;
cur.P = P;
triangulatePoints(prev.P, cur.P, src, dst, points4D);
}
for (size_t j=0; j < kp_used.size(); j++) {
if (mask.at<uchar>(j)) {
size_t k = kp_used[j];
size_t match_idx = prev.kp_match_idx(k, i+1);
Point3f pt3d;
pt3d.x = points4D.at<float>(0, j) / points4D.at<float>(3, j);
pt3d.y = points4D.at<float>(1, j) / points4D.at<float>(3, j);
pt3d.z = points4D.at<float>(2, j) / points4D.at<float>(3, j);
if (prev.kp_3d_exist(k)) {
cur.kp_3d(match_idx) = prev.kp_3d(k);
SFM.landmark[prev.kp_3d(k)].pt += pt3d;
SFM.landmark[cur.kp_3d(match_idx)].seen++;
} else {
SFM_metadata::Landmark landmark;
landmark.pt = pt3d;
landmark.seen = 2;
SFM.landmark.push_back(landmark);
prev.kp_3d(k) = SFM.landmark.size() - 1;
cur.kp_3d(match_idx) = SFM.landmark.size() - 1;
}
}
}
}
vector<Mat> pts_est;
for (auto &l : SFM.landmark) {
if (l.seen >= 3) {
SpacePoint pts;
l.pt /= (l.seen - 1);
pts.point.x = l.pt.x;
pts.point.y = l.pt.y;
pts.point.z = l.pt.z;
pts.red = 1; pts.blue = 1; pts.green = 1;
pointCloud.push_back(pts);
}
}
toPly();
}
};
int main(int argc, char **argv){
SFMtoolkit stk;
stk.feature_proc();
stk.FeatureMatch();
stk.sfm_reconstruct();
GTSAMBundleAdjust gtb(stk.SFM);
gtb.FactorGraphOptimize();
gtb.PMVSformatting();
cout<<"EXECUTED"<<endl;
return 0;
}
<file_sep>/visualOdometry/include/windowedBundleAdjust.h
#include <vector>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <g2o/types/slam3d/types_slam3d.h>
#include <g2o/core/block_solver.h>
#include <g2o/core/optimization_algorithm_levenberg.h>
#include <g2o/solvers/eigen/linear_solver_eigen.h>
using namespace std;
using namespace g2o;
<file_sep>/ocvsfm.sh
echo "Enter fname"
read fname
echo "Compiling $fname.cxx"
g++ $fname.cpp -o app `pkg-config --cflags --libs opencv`
if [ "$?" = "0" ]; then
echo "Compiled"
else
echo "Terminate"
exit 1
fi
echo "Enter Args focal length, Cx, Cy"
read f
read cx
read cy
echo "Building ./$fname with args $f,$cx,$cy"
./app aths.txt $f $cx $cy
if [ "$?" = "0" ]; then
echo " "
else
echo "Terminate with exit 1"
exit 1
fi
<file_sep>/visualOdometry/src/monoOdometry.cpp
/*
-->GauthWare, LSM, 01/2021
*/
// #include <iostream>
// #include <vector>
// #include <algorithm>
#include "../include/monoOdometry.h"
#include "../include/monoUtils.h"
#include "../include/poseGraph.h"
using namespace std;
using namespace cv;
Mat monoOdom::loadImage(int iter){
char fileName[200];
sprintf(fileName, lFptr, iter);
Mat im = imread(fileName);
if(!im.data){
cerr<<"YIKES, failed to grab "<<iter<<" image.\nYou might wanna check that path again dawg."<<endl;
}
return im;
}
Mat monoOdom::drawDeltasErr(Mat im, vector<Point2f> in1, vector<Point2f> in2){
Mat frame;
im.copyTo(frame);
for(int i=0; i<in1.size(); i++){
Point2f pt1 = in1[i];
Point2f pt2 = in2[i];
line(frame, pt1, pt2, Scalar(0,255,0),2);
circle(frame, pt1, 5, Scalar(0,0,255));
circle(frame, pt2, 5, Scalar(255,0,0));
}
return frame;
}
vector<KeyPoint> monoOdom::denseKeypointExtractor(Mat img, int stepSize){
vector<KeyPoint> out;
for (int y=stepSize; y<img.rows-stepSize; y+=stepSize){
for (int x=stepSize; x<img.cols-stepSize; x+=stepSize){
out.push_back(KeyPoint(float(x), float(y), float(stepSize)));
}
}
return out;
}
void monoOdom::pyrLKtracking(Mat refImg, Mat curImg, vector<Point2f>&refPts, vector<Point2f>&trackPts){
vector<Point2f> trPts, inlierRefPts, inlierTracked;
vector<uchar> Idx;
vector<float> err;
calcOpticalFlowPyrLK(refImg, curImg, refPts, trPts,Idx, err);
for(int i=0; i<refPts.size(); i++){
if(Idx[i]==1){
inlierRefPts.emplace_back(refPts[i]);
inlierTracked.emplace_back(trPts[i]);
}
}
trackPts.clear(); refPts.clear();
trackPts = inlierTracked; refPts = inlierRefPts;
}
void monoOdom::FmatThresholding(vector<Point2f>&refPts, vector<Point2f>&trkPts){
Mat F;
vector<uchar> mask;
vector<Point2f>inlierRef, inlierTrk;
F = findFundamentalMat(refPts, trkPts, CV_RANSAC, 3.0, 0.99, mask);
for(size_t j=0; j<mask.size(); j++){
if(mask[j]==1){
inlierRef.emplace_back(refPts[j]);
inlierTrk.emplace_back(trkPts[j]);
}
}
refPts.clear(); trkPts.clear();
refPts = inlierRef; trkPts = inlierTrk;
}
void monoOdom::monoTriangulate(Mat img1, Mat img2,vector<Point2f>&ref2dPts, vector<Point2f>&trk2dPts, vector<Point3f>&ref3dpts){
// Ptr<FeatureDetector> detector = xfeatures2d::SIFT::create(1000);
// Ptr<FeatureDetector> detector = ORB::create(2000);
vector<KeyPoint> dkps;
dkps = denseKeypointExtractor(img1, 20);
vector<Point2f> refPts;
for(size_t i=0; i<dkps.size(); i++){
refPts.emplace_back(dkps[i].pt);
}
vector<Point2f> trkPts;
pyrLKtracking(img1, img2, refPts, trkPts);
FmatThresholding(refPts, trkPts);
// vector<KeyPoint> kp1, kp2;
// detector->detect(img1, kp1);
// detector->detect(img2, kp2);
// Mat desc1, desc2;
// detector->compute(img1, kp1, desc1);
// detector->compute(img2, kp2, desc2);
// desc1.convertTo(desc1, CV_32F);
// desc2.convertTo(desc2, CV_32F);
// BFMatcher matcher;
// vector<vector<DMatch>> matches;
// matcher.knnMatch(desc1, desc2, matches, 2);
// vector<Point2f> pt1, pt2;
// for(int i=0; i<matches.size(); i++){
// DMatch &m = matches[i][0]; DMatch &n = matches[i][1];
// if(m.distance<0.8*n.distance){
// pt1.emplace_back(kp1[m.queryIdx].pt);
// pt2.emplace_back(kp2[m.trainIdx].pt);
// }
// }
// FmatThresholding(pt1, pt2);
// vector<Point2f> refPts, trkPts;
// refPts = pt1; trkPts = pt2;
Mat E, mask;
E = findEssentialMat(refPts, trkPts, K, 8, 0.99, 1, mask);
recoverPose(E, refPts, trkPts, K, R, t,mask);
Mat pts4d;
Mat P1 = Mat::zeros(3,4,CV_64F); Mat P2 = Mat::zeros(3,4,CV_64F);
P1.at<double>(0,0) = 1; P1.at<double>(1,1) = 1; P1.at<double>(2,2) = 1;
R.col(0).copyTo(P2.col(0));
R.col(1).copyTo(P2.col(1));
R.col(2).copyTo(P2.col(2));
t.copyTo(P2.col(3));
triangulatePoints(P1, P2, refPts, trkPts, pts4d);
vector<Point3f> pts3d;
pts3d.reserve(pts4d.cols);
for(size_t j=0; j<pts4d.cols; j++){
Point3f landmark;
landmark.x = pts4d.at<double>(0,j)/pts4d.at<double>(3,j);
landmark.y = pts4d.at<double>(1,j)/pts4d.at<double>(3,j);
landmark.z = pts4d.at<double>(2,j)/pts4d.at<double>(3,j);
pts3d.emplace_back(landmark);
}
ref2dPts.clear(); trk2dPts.clear(); ref3dpts.clear();
ref2dPts = refPts; trk2dPts = trkPts; ref3dpts = pts3d;
}
void monoOdom::initSequence(){
Mat ima = loadImage(iter);
Mat imb = loadImage(iter+1);
vector<Point2f> refPts, trkPts;
vector<Point3f> ref3d;
monoTriangulate(ima, imb, refPts, trkPts, ref3d);
prevFeatures = refPts;
prev3d = ref3d;
imMeta.im1 = ima; imMeta.im2 = imb; imMeta.refPts = refPts; imMeta.trkPts = trkPts; imMeta.pts3d = ref3d;
imMeta.R = R; imMeta.t = t;
Rmono = R.clone(); tmono = t.clone();
rvec = R.clone(); tvec = t.clone();
poseGraph.initializeGraph();
prevImMeta = imMeta;
iter+=2;
}
void monoOdom::relocalize(int start, Mat imL, Mat imR, Mat&inv_transform, vector<Point2f>&ftrPts, vector<Point3f>&pts3d){
vector<Point2f> new2d, newTrk;
vector<Point3f> new3d;
ftrPts.clear();
pts3d.clear();
monoTriangulate(imL, imR, new2d, newTrk, new3d);
for(int i=0; i<new3d.size(); i++){
Point3f pt = new3d[i];
Point3f p;
p.x = inv_transform.at<double>(0,0)*pt.x + inv_transform.at<double>(0,1)*pt.y + inv_transform.at<double>(0,2)*pt.z + inv_transform.at<double>(0,3);
p.y = inv_transform.at<double>(1,0)*pt.x + inv_transform.at<double>(1,1)*pt.y + inv_transform.at<double>(1,2)*pt.z + inv_transform.at<double>(1,3);
p.z = inv_transform.at<double>(2,0)*pt.x + inv_transform.at<double>(2,1)*pt.y + inv_transform.at<double>(2,2)*pt.z + inv_transform.at<double>(2,3);
pts3d.emplace_back(p);
ftrPts.emplace_back(new2d[i]);
}
}
void monoOdom::PyrLKtrackFrame2Frame(Mat refimg, Mat curImg, vector<Point2f>refPts, vector<Point3f>ref3dpts,
vector<Point2f>&refRetpts, vector<Point3f>&ref3dretPts){
vector<Point2f> trackPts;
vector<uchar> Idx;
vector<float> err;
calcOpticalFlowPyrLK(refimg, curImg, refPts, trackPts,Idx, err);
vector<Point2f> inlierRefPts;
vector<Point3f> inlierRef3dPts;
vector<Point2f> inlierTracked;
vector<int> res;
for(int j=0; j<refPts.size(); j++){
if(Idx[j]==1){
inlierRefPts.emplace_back(refPts[j]);
ref3dretPts.emplace_back(ref3dpts[j]);
refRetpts.emplace_back(trackPts[j]);
}
}
}
void monoOdom::stageForPGO(Mat Rl, Mat tl, Mat Rg, Mat tg, bool loopClose){
Eigen::Isometry3d localT, globalT;
localT = cvMat2Eigen(Rl, tl);
globalT = cvMat2Eigen(Rg, tg);
if(loopClose){
LC_FLAG = true;
poseGraph.addLoopClosure(globalT,LCidx);
}
else{
poseGraph.augmentNode(localT, globalT);
}
}
void monoOdom::updateOdometry(vector<Eigen::Isometry3d>&T){
cerr<<"\n\nUpdating global odometry measurements"<<endl;
vector<float> data;
for(Eigen::Isometry3d &isoMatrix : T){
Mat t = Eigen2cvMat(isoMatrix);
data.emplace_back(t.at<double>(0));
data.emplace_back(t.at<double>(1));
data.emplace_back(t.at<double>(2));
trajectory.emplace_back(t.clone());
}
dumpOptimized(data);
}
void monoOdom::checkLoopDetector(Mat img, int idx){
Ptr<FeatureDetector> orb = ORB::create();
vector<KeyPoint> kp;
Mat desc;
vector<FORB::TDescriptor> descriptors;
orb->detectAndCompute(img, Mat(), kp, desc);
restructure(desc, descriptors);
DetectionResult result;
loopDetector->detectLoop(kp, descriptors, result);
if(result.detection() &&(result.query-result.match > 100) && cooldownTimer==0){
cerr<<"Found Loop Closure between "<<idx<<" and "<<result.match<<endl;
LC_FLAG = true;
LCidx = result.match-1;
cooldownTimer = 100;
}
}
void monoOdom::loopSequence(){
vector<float> data; vector<imageMetadata> metaData;
for(int i=iter; i<4500; i++){
Mat ima = loadImage(i); Mat imb = loadImage(i+1);
vector<Point2f> refPts, trkPts;
vector<Point3f> ref3d;
vector<Point2f> inlierRefPts;
vector<Point3f> inlier3dPts;
monoTriangulate(ima, imb, refPts, trkPts, ref3d);
Mat rv, tv;
double xgt,ygt,zgt;
double absScale = getAbsoluteScale(i, xgt, ygt, zgt);
Mat Rcpy, tcpy;
Rcpy = R.clone();
tcpy = t.clone();
//BundleAdjust3d2d(refPts, ref3d, K, Rcpy, tcpy);
if(absScale<0.1){
tvec = tvec;
rvec = rvec;
tmono = tmono;
Rmono = Rmono;
}
else{
tvec = tvec + absScale*(rvec*t);
rvec = rvec*R;
tmono = tmono + absScale*(Rmono*t);
Rmono = Rmono*R;
}
// rvec = R.t();
// tvec = -rvec*t;
Mat inv_transform = Mat::zeros(3,4, CV_64F);
R.col(0).copyTo(inv_transform.col(0));
R.col(1).copyTo(inv_transform.col(1));
R.col(2).copyTo(inv_transform.col(2));
t.copyTo(inv_transform.col(3));
checkLoopDetector(ima, i);
if(LC_FLAG){
stageForPGO(R, t, Rmono, tmono, true);
stageForPGO(R, t, Rmono, tmono, false);
std::vector<Eigen::Isometry3d> trans = poseGraph.globalOptimize();
Mat interT = Eigen2cvMat(trans[trans.size()-1]);
tmono = interT.t();
}
else{
stageForPGO(R, t, Rmono, tmono, false);
}
data.emplace_back(i);
data.emplace_back(tvec.at<double>(0));
data.emplace_back(tvec.at<double>(1));
data.emplace_back(tvec.at<double>(2));
data.emplace_back(xgt);
data.emplace_back(ygt);
data.emplace_back(zgt);
data.emplace_back(-1.00);
//cout<<int(tvec.at<double>(0))<<" "<<int(tvec.at<double>(2))<<" "<<int(xgt)<<" "<<int(zgt)<<en
Point2f center = Point2f(int(tvec.at<double>(0)) + 750, int(-1*tvec.at<double>(2)) + 200);
Point2f centerGT = Point2f(xgt + 750, zgt + 200);
circle(canvas, centerGT ,1, Scalar(0,255,0), 1);
circle(canvas, center ,1, Scalar(0,0,255), 1);
rectangle(canvas, Point2f(10, 30), Point2f(550, 50), Scalar(0,0,0), cv::FILLED);
imMeta.im1 = ima; imMeta.im2 = imb; imMeta.refPts = refPts; imMeta.trkPts = trkPts; imMeta.pts3d = ref3d;
imMeta.R = rvec; imMeta.t = tvec;
prevImMeta = imMeta;
debug1 = drawDeltasErr(ima, refPts, trkPts);
imshow("debug", debug1);
imshow("Original Image",ima);
imshow("trajectory", canvas);
if(i==iter){
createData(data);
}
else{
appendData(data);
}
// if(LC_FLAG){
// if(cooldownTimer==0){
// vector<Eigen::Isometry3d> res = poseGraph.globalOptimize();
// updateOdometry(res);
// cerr<<"Redrawing Trajectory"<<endl;
// Mat tUpdated;
// for(Mat& position : trajectory){
// Point2f centerMono = Point2f(int(position.at<double>(0)) + 750, int(-1*position.at<double>(2)) + 200);
// circle(canvas, centerMono ,1, Scalar(255,0,0), 1);
// tUpdated = position.clone();
// }
// tmono = tUpdated.clone();
// LC_FLAG = false;
// }
// else{
// cooldownTimer--;
// }
// }
LC_FLAG = false;
data.clear();
cerr<<"Timer : "<<cooldownTimer<<"\r";
if(cooldownTimer!=0){
cooldownTimer-=1;
}
int k = waitKey(1);
if(k=='q'){
break;
}
}
poseGraph.saveStructure();
vector<Eigen::Isometry3d> res = poseGraph.globalOptimize();
updateOdometry(res);
cerr<<"\nRedrawing Trajectory\nPress any key to quit (even power key, lmao.)"<<endl;
for(Mat& position : trajectory){
Point2f centerMono = Point2f(int(position.at<double>(0)) + 750, int(-1*position.at<double>(2)) + 200);
circle(canvas, centerMono ,1, Scalar(255,0,0), 1);
}
imshow("trajectory", canvas);
waitKey(0);
imwrite("Trajectory.png",canvas);
cerr<<"Trajectory Saved"<<endl;
}
int main(){
const char* impathL = "/media/gautham/Seagate Backup Plus Drive/Datasets/dataset/sequences/00/image_0/%0.6d.png";
const char* impathR = "/media/gautham/Seagate Backup Plus Drive/Datasets/dataset/sequences/00/image_0/%0.6d.png";
monoOdom od(0, impathL, impathR);
od.initSequence();
od.loopSequence();
//od.pureMonocularSequence();
return 0;
}<file_sep>/SFM_pipeline/to_ply.h
#ifndef TO_PLY
#define TO_PLY
void to_ply();
#endif<file_sep>/Stereo_pipeline/Stereo_Matching.py
import numpy as np
import cv2
from matplotlib import pyplot as plt
import open3d as o3d
def write_ply(fn, verts, colors):
ply_header = '''ply
format ascii 1.0
element vertex %(vert_num)d
property float x
property float y
property float z
property uchar red
property uchar green
property uchar blue
end_header
'''
out_colors = colors.copy()
verts = verts.reshape(-1, 3)
verts = np.hstack([verts, out_colors])
with open(fn, 'wb') as f:
f.write((ply_header % dict(vert_num=len(verts))).encode('utf-8'))
np.savetxt(f, verts, fmt='%f %f %f %d %d %d ')
def Pose_Est(im1,im2,k1,k2):
orb = cv2.ORB_create()
kp1, descs1 = orb.detectAndCompute(im1,None)
kp2, descs2 = orb.detectAndCompute(im2,None)
#pts_1 = np.array([x.pt for x in kp1], dtype=np.float32)
#pts_2 = np.array([x.pt for x in kp2], dtype=np.float32)
matcher = cv2.BFMatcher()
matches = matcher.knnMatch(descs1, descs2, k=2)
good = []
pt1 = []
pt2 = []
for i,(m,n) in enumerate(matches):
if m.distance < 0.8*n.distance:
good.append(m)
pt2.append(kp2[m.trainIdx].pt)
pt1.append(kp1[m.queryIdx].pt)
pts1 = np.float32(pt1)
pts2 = np.float32(pt2)
F, mask = cv2.findFundamentalMat(pts1,pts2,cv2.FM_LMEDS)
pts1 = pts1[mask.ravel()==1]
pts2 = pts2[mask.ravel()==1]
pts11 = pts1.reshape(-1,1,2)
pts22 = pts2.reshape(-1,1,2)
pts1_norm = cv2.undistortPoints(pts11, cameraMatrix=k1, distCoeffs=None)
pts2_norm = cv2.undistortPoints(pts22, cameraMatrix=k2, distCoeffs=None)
E,mask = cv2.findEssentialMat(pts1_norm, pts2_norm, focal=k1[0,0], pp=(k1[0,2],k1[1,2]), method=cv2.RANSAC,prob=0.99, threshold=1.0)
r1, r2, t = cv2.decomposeEssentialMat(E)
_,R,T,mask = cv2.recoverPose(E,pts1_norm,pts2_norm,focal=k1[0,0],pp=(k1[0,2],k1[1,2]))
return R,T
calib_mat1 = [[3997.684,0,1176.728],
[0,3997.684,1011.728],
[0,0,1]]
calib_mat2 = [[3997.684,0,1307.839],
[0,3997.684,1011.728],
[0,0,1]]
K1 = np.array(calib_mat1)
K2 = np.array(calib_mat2)
path = "/home/gautham/Documents/Codes/Datasets/Stereo/Motorcycle/"
path2 = "/home/gautham/Documents/Codes/Datasets/Stereo/Bag/"
imgLc = cv2.imread(path + 'im0.png')
imgRc = cv2.imread(path + 'im1.png')
imgL = cv2.blur(cv2.cvtColor(imgLc, cv2.COLOR_RGB2GRAY),(5,5))
imgR = cv2.blur(cv2.cvtColor(imgRc, cv2.COLOR_RGB2GRAY),(5,5))
#imgL = cv2.undistort(imgL,K1,distCoeffs=None)
#imgR = cv2.undistort(imgR,K2,distCoeffs=None)
#stereo = cv2.StereoBM_create(numDisparities=288, blockSize=27)
window_size = 3
min_disp = 16
num_disp = 256
stereo = cv2.StereoSGBM_create(minDisparity = min_disp,
numDisparities = num_disp,
blockSize = 11,
P1 = 8*3*window_size**2,
P2 = 32*3*window_size**2,
disp12MaxDiff = 10,
uniquenessRatio = 20,
speckleWindowSize = 5000,
speckleRange = 5
)
#cv2.filterSpeckles()
# stereo = cv2.StereoMatcher()
disparity = stereo.compute(imgL,imgR)
plt.imshow(disparity,'CMRmap_r')
plt.show()
Tmat = np.array([0.4, 0., 0.])
#R, t = Pose_Est(imgR,imgL,K2,K1)
#Tmat = t
print(np.linalg.norm(Tmat))
rev_proj_matrix = np.zeros((4,4))
cv2.stereoRectify(cameraMatrix1 = K1,cameraMatrix2 = K2, \
distCoeffs1 = 0, distCoeffs2 = 0, \
imageSize = imgL.shape[:2], \
R = np.identity(3), T = Tmat, \
R1 = None, R2 = None, \
P1 = None, P2 = None, Q = rev_proj_matrix)
h, w = imgL.shape[:2]
f = 0.8*w
Q = np.float32([[1, 0, 0, -0.5*w],
[0,-1, 0, 0.5*h],
[0, 0, 0, -f],
[0, 0, 1, 0]])
points = cv2.reprojectImageTo3D(disparity, Q)
reflect_matrix = np.identity(3)
reflect_matrix[0] *= -1
points = np.matmul(points,reflect_matrix)
colors = cv2.cvtColor(imgLc, cv2.COLOR_BGR2RGB)
mask = disparity > disparity.min()
out_colors = colors[mask]
out_colors = out_colors.reshape(-1, 3)
out_points = points[mask]
# idx = np.fabs(out_points[:,0]) < 0.3
# out_points = out_points[idx]
#write_ply(path + 'out.ply', out_points, out_colors)
print(out_points)
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(np.array(out_points))
o3d.visualization.draw_geometries([pcd])<file_sep>/visualOdometry/visualizer/test.py
res = []
def ssum(s,subset, branch, depth):
if sum(branch)>s:
return
if sum(branch)==s:
if set(branch) not in res:
res.append(set(branch))
if depth>1000:
print("depth limit reached")
return
for i in range(len(subset)):
subsubset = subset[i+1:]
num = subset[i]
depth+=1
branchcpy = branch.copy()
branchcpy.append(num)
ssum(s, subsubset, branchcpy, depth)
ss = [10,30,65,80,35,21,32,35,41,100,11,5,6,8,12,150,30,63,102,12]
ss = sorted(ss)
print(ss, len(ss))
sval = 165
ssum(sval, ss, [], 0)
j = 0
for i in res:
if sum(i)==sval:
print(i, sum(i))
j+=1
print(j)<file_sep>/SFM_pipeline/to_ply.cpp
#include <bits/stdc++.h>
#include <opencv2/core.hpp>
using namespace std;
using namespace cv;
struct dataType {
cv::Point3d point;
int red;
int green;
int blue;
};
typedef dataType SpacePoint;
vector<SpacePoint> pointCloud;
void toPly(){
ofstream outfile("/home/gautham/Documents/Codes/pointcloud.ply");
outfile << "ply\n" << "format ascii 1.0\n" << "comment VTK generated PLY File\n";
outfile << "obj_info vtkPolyData points and polygons : vtk4.0\n" << "element vertex " << pointCloud.size() << "\n";
outfile << "property float x\n" << "property float y\n" << "property float z\n" << "element face 0\n";
outfile << "property list uchar int vertex_indices\n" << "end_header\n";
for (int i = 0; i < pointCloud.size(); i++)
{
Point3d point = pointCloud.at(i).point;
outfile << point.x << " ";
outfile << point.y << " ";
outfile << point.z << " ";
outfile << "\n";
}
cout<<"PLY SAVE DONE"<<endl;
outfile.close();
}<file_sep>/dependency_scan.sh
#LSM, <NAME>, 29,oct,2020
echo "Finding Dependencies <viz toolkit>,<sfm pkg>,<calib3d pkg>,<cvcore>,<xfeatures2d>,<features2d>,<highgui>,<ceres solver>"
r=`tput setaf 1`
rst=`tput sgr0`
g=`tput setaf 2`
#find /lib* /usr/local/include/ /usr/include/ -name '*viz.hpp*'
lines=$(find /lib* /usr/local/include/ /usr/include/ -name '*viz.hpp*' | wc -l)
pkgs="viz.hpp"
echo;
if [ $lines -eq 0 ]; then
echo "$r---x $pkgs not found in include path$rst"
else
echo "$g---> $pkgs FOUND w/ $lines copy$rst"
fi
echo;
#find /lib* /usr/local/include/ /usr/include/ -name '*sfm.hpp*'
lines=$(find /lib* /usr/local/include/ /usr/include/ -name '*sfm.hpp*' | wc -l)
pkgs="sfm.hpp"
echo;
if [ $lines -eq 0 ]; then
echo "$r---x $pkgs not found in include path$rst"
else
echo "$g---> $pkgs FOUND w/ $lines copy$rst"
fi
echo;
#find /lib* /usr/local/include/ /usr/include/ -name '*calib3d.hpp*'
lines=$(find /lib* /usr/local/include/ /usr/include/ -name '*calib3d.hpp*' | wc -l)
pkgs="calib3d.hpp"
echo;
if [ "$lines" = "0" ]; then
echo "$r---x $pkgs not found in include path$rst"
else
echo "$g---> $pkgs FOUND w/ $lines copy$rst"
fi
echo;
#find /lib* /usr/local/include/ /usr/include/ -name '*core.hpp*'
lines=$(find /lib* /usr/local/include/ /usr/include/ -name '*core.hpp*' | wc -l)
pkgs="core.hpp"
echo;
if [ "$lines" = "0" ]; then
echo "$r---x $pkgs not found in include path$rst"
else
echo "$g---> $pkgs FOUND w/ $lines copy$rst"
fi
echo;
#find /lib* /usr/local/include/ /usr/include/ -name '*xfeatures2d.hpp*'
lines=$(find /lib* /usr/local/include/ /usr/include/ -name '*xfeatures2d.hpp*' | wc -l)
pkgs="xfeatures2d.hpp"
echo;
if [ "$lines" = "0" ]; then
echo "$r---x $pkgs not found in include path$rst"
else
echo "$g---> $pkgs FOUND w/ $lines copy$rst"
fi
echo;
#find /lib* /usr/local/include/ /usr/include/ -name '*features2d.hpp*'
lines=$(find /lib* /usr/local/include/ /usr/include/ -name '*features2d.hpp*' | wc -l)
pkgs="features2d.hpp"
echo;
if [ "$lines" = "0" ]; then
echo "$r---x $pkgs not found in include path$rst"
else
echo "$g---> $pkgs FOUND w/ $lines copy$rst"
fi
echo;
#find /lib* /usr/local/include/ /usr/include/ -name '*highgui.hpp*'
lines=$(find /lib* /usr/local/include/ /usr/include/ -name '*highgui.hpp*' | wc -l)
pkgs="highgui.hpp"
echo;
if [ "$lines" = "0" ]; then
echo "$r---x $pkgs not found in include path$rst"
else
echo "$g---> $pkgs FOUND w/ $lines copy$rst"
fi
echo;
#find /lib* /usr/local/include/ /usr/include/ -name '*ceres*'
lines=$(find /lib* /usr/local/include/ /usr/include/ -name '*ceres*' | wc -l)
pkgs="ceres"
echo;
if [ "$lines" = "0" ]; then
echo "$r---x $pkgs not found in include path$rst"
else
echo "$g---> $pkgs FOUND w/ $lines copy$rst"
fi
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.0)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
project(LargeScaleMapping)
SET( EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)
set(HDRS_DBOW2
DBoW2/BowVector.h
DBoW2/FORB.h
DBoW2/FClass.h
DBoW2/FeatureVector.h
DBoW2/ScoringObject.h
DBoW2/TemplatedVocabulary.h)
set(SRCS_DBOW2
DBoW2/BowVector.cpp
DBoW2/FORB.cpp
DBoW2/FeatureVector.cpp
DBoW2/ScoringObject.cpp)
find_package(OpenCV REQUIRED)
include_directories(
${OpenCV_INCLUDE_DIRS}
${G2O_INCLUDE_DIR}
${CSPARSE_INCLUDE_DIR}
${GTSAM_INCLUDE_DIR}
${DBoW2_INCLUDE_DIR}
"/usr/include/eigen3/"
)
add_executable(
visualOdometry ${PROJECT_SOURCE_DIR}/visualOdometry/VisualOdometry.cpp
)
add_executable(
bundleAdjust ${PROJECT_SOURCE_DIR}/visualOdometry/bundleAdjust.cpp
)
add_executable(
BoWtest ${PROJECT_SOURCE_DIR}/visualOdometry/bagOfWordsDetector.cpp
)
target_link_libraries(
visualOdometry ${OpenCV_LIBS}
)
target_link_libraries(
bundleAdjust ${OpenCV_LIBS} ${G2O_LIBS} ${CSPARSE_LIBS} g2o_core g2o_stuff g2o_types_sba g2o_csparse_extension
)
target_link_libraries(
BoWtest ${OpenCV_LIBS} ${DBoW2_LIBS} DBoW2
)
target_include_directories(
BoWtest PUBLIC ${DBoW2_INCLUDE_DIR}
)<file_sep>/visualOdometry/src/poseGraphOptimizer.cpp
#include "../include/poseGraph.h"
<file_sep>/PyUtils/pose_estimate.py
import cv2
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
import math
import imutils
import time
cam = cv2.VideoCapture(0)
K = [[647.8849454418848, 0.0, 312.70216601346215],
[0.0, 648.2741486235716, 245.95593954674428],
[0.0, 0.0, 1.0]]
K = np.array(K)
distCoeffs = [0.035547431486979156, -0.15592121266783593, 0.0005127230470698213, -0.004324823776384423, 1.2415990279352762]
distCoeffs = np.array(distCoeffs)
focal_len = 648.2741486235716
pp = (312.70216601346215, 245.95593954674428)
im1 = cv2.imread("/home/gautham/Documents/Codes/depth_reconstruct/opencv_frame_0.png")
im2 = cv2.imread("/home/gautham/Documents/Codes/depth_reconstruct/opencv_frame_3.png")
ref_vocab = []
class PoseEstimate:
def __init__(self,K,distCoeff):
self.K = K
self.distCoeff = distCoeff
self.ref_frame = None
self.frame = None
self.ref_kpmask = None
self.frame_kpmask = None
self.match_frame = None
self.Kp_ref = None
self.descs_ref = None
self.Kp_frame = None
self.descs_frame = None
self.F = None
self.Rmat = None
self.Tvec = None
self.goodkps = None
self.pts_ref = None
self.pts_frame = None
self.focal_len = 1.0
self.pp = (0. ,0.)
self.RotX = 0.
self.RotY = 0.
self.RotZ = 0.
self.PosX = 0.
self.PosY = 0.
self.PosZ = 0.
self.eulerAngles = None
self.ref_homography = None
self.frame_homography = None
self.resampleFlag = False
self.interruptFlag = False
def featureEst(self):
orb = cv2.ORB_create()
self.Kp_ref, self.descs_ref = orb.detectAndCompute(self.ref_frame,None)
self.Kp_frame, self.descs_frame = orb.detectAndCompute(self.frame,None)
def featureMatch(self):
matcher = cv2.BFMatcher()
matches = matcher.knnMatch(self.descs_ref, self.descs_frame, k=2)
good = []
pt1 = []
pt2 = []
for i,(m,n) in enumerate(matches):
if m.distance < 0.8*n.distance:
good.append(m)
pt2.append(self.Kp_frame[m.trainIdx].pt)
pt1.append(self.Kp_ref[m.queryIdx].pt)
self.goodkps = good
pts1 = np.float32(pt1)
pts2 = np.float32(pt2)
self.ref_kpmask = cv2.drawKeypoints(self.ref_frame, self.Kp_ref, self.ref_kpmask,color=(0,255,0), flags=cv2.DRAW_MATCHES_FLAGS_DEFAULT)
self.frame_kpmask = cv2.drawKeypoints(self.frame, self.Kp_frame, self.frame_kpmask,color=(0,255,0),flags=cv2.DRAW_MATCHES_FLAGS_DEFAULT)
#self.match_frame = cv2.drawMatchesKnn(self.ref_frame, self.Kp_ref ,self.frame, self.Kp_frame, good[:10], np.copy(self.match_frame), flags=2)
self.F, mask = cv.findFundamentalMat(pts1,pts2,cv.FM_LMEDS)
pts1 = pts1[mask.ravel()==1]
pts2 = pts2[mask.ravel()==1]
pts11 = pts1.reshape(-1,1,2)
pts22 = pts2.reshape(-1,1,2)
pts1_norm = cv2.undistortPoints(pts11, cameraMatrix=self.K, distCoeffs=self.distCoeff)
pts2_norm = cv2.undistortPoints(pts22, cameraMatrix=self.K, distCoeffs=self.distCoeff)
self.pts_ref = pts1_norm
self.pts_frame = pts2_norm
def vectorizePose(self):
E,mask = cv.findEssentialMat(self.pts_ref, self.pts_frame, focal=1.0, pp=(0.,0.), method=cv2.RANSAC,prob=0.99, threshold=1.0)
r1, r2, t = cv.decomposeEssentialMat(E)
_,R,T,mask = cv.recoverPose(E, self.pts_ref, self.pts_frame, focal=1.0, pp=(0.,0.))
self.Rmat = R
self.Tvec = T
def geometricTransform(self):
M_r = np.hstack((self.Rmat, self.Tvec))
projMat = np.dot(self.K, M_r)
eulerAngles = cv2.decomposeProjectionMatrix(projMat)[-1]
self.RotX = eulerAngles[0]
self.Roty = eulerAngles[1]
self.Rotz = eulerAngles[2]
self.eulerAngles = eulerAngles
def poseTrack(self,ref_image,image):
self.ref_frame = ref_image
self.frame = image
def estimate(self):
self.featureEst()
self.featureMatch()
self.vectorizePose()
self.geometricTransform()
return self.eulerAngles
_, ref_frame = cam.read()
xrot = []
yrot = []
zrot = []
step = []
i=0
xr = 0
yr = 0
zr = 0
pose = PoseEstimate(K,distCoeffs)
step = 0
while True:
imbuf = imutils.rotate(im2,step)
pose.poseTrack(im2,imbuf)
angles = pose.estimate()
imR = pose.ref_kpmask
imL = pose.frame_kpmask
#match_img = cv2.drawMatchesKnn(pose.ref_kpmask, pose.Kp_ref, pose.frame_kpmask, pose.Kp_frame, pose.goodkps,None,flags=2)
print(np.transpose(angles))
cv2.namedWindow("Test")
cv2.imshow("Test", imR)
print(len(pose.pts_frame))
cv2.namedWindow("Main")
cv2.imshow("Main", imL)
step+=10
k = cv.waitKey(0)
if step>90:
print("Angular Overflow")
break
if k%256 == 27:
print("Escape hit, closing...")
break
cv.destroyAllWindows()
<file_sep>/visualOdometry/ros_vo.py
#!/usr/bin/env python
'''
--><NAME>, 26/12/2020
A rosified implementation of
Visual Odometry + Stereo Reconstruction + P2P-ICP transformation
'''
import numpy as np
import cv2
import os
import math
import open3d as o3d
import matplotlib.pyplot as plt
import rospy
from math import pow, atan2, sqrt, sin, cos
from std_msgs.msg import Float64, Float64MultiArray, Header
from sensor_msgs.msg import Image
from sensor_msgs.msg import PointCloud2, PointField
from visualization_msgs.msg import Marker
from sensor_msgs import point_cloud2 as pcl2
from geometry_msgs.msg import Pose, PoseStamped
from cv_bridge import CvBridge
from scipy.spatial.transform import Rotation
Trmat = [4.276802385584e-04, -9.999672484946e-01, -8.084491683471e-03, -1.198459927713e-02,
-7.210626507497e-03, 8.081198471645e-03, -9.999413164504e-01, -5.403984729748e-02,
9.999738645903e-01, 4.859485810390e-04, -7.206933692422e-03, -2.921968648686e-01]
class PoseGraphOptimizer:
def __init__(self,downsamplefactor=0.0):
self.Pcd = o3d.geometry.PointCloud()
self.Points = None
self.pPcd = o3d.geometry.PointCloud()
self.pcdBuffer = []
self.downSampleFactor = downsamplefactor
self.max_correspondence_distance_coarse = self.downSampleFactor * 15
self.max_correspondence_distance_fine = self.downSampleFactor * 1.5
self.pPoints = None
self.pR_ = None
self.pt_ = None
self.count = 0
self.ckpt = 1
self.xpts = []
self.ypts = []
self.zpts = []
self.X = None
self.Y = None
self.Z = None
def loadBuffer(self, pcl):
self.pcdBuffer.clear()
self.pcdBuffer.append(self.pPcd)
#pcl.voxel_down_sample(voxel_size = self.downSampleFactor)
self.Pcd = pcl
self.pcdBuffer.append(self.Pcd)
def pairwiseRegistration(self, source, target):
max_correspondence_distance_coarse = self.max_correspondence_distance_coarse
max_correspondence_distance_fine = self.max_correspondence_distance_fine
icp_coarse = o3d.pipelines.registration.registration_icp(
source, target, max_correspondence_distance_coarse, np.identity(4),
o3d.pipelines.registration.TransformationEstimationPointToPlane())
icp_fine = o3d.pipelines.registration.registration_icp(
source, target, max_correspondence_distance_fine,
icp_coarse.transformation,
o3d.pipelines.registration.TransformationEstimationPointToPlane())
transformation_icp = icp_fine.transformation
information_icp = o3d.pipelines.registration.get_information_matrix_from_point_clouds(
source, target, max_correspondence_distance_fine,
icp_fine.transformation)
return transformation_icp, information_icp
def fullRegistration(self,pcds, max_correspondence_distance_coarse, max_correspondence_distance_fine):
max_correspondence_distance_coarse = self.max_correspondence_distance_coarse
max_correspondence_distance_fine = self.max_correspondence_distance_fine
pose_graph = o3d.pipelines.registration.PoseGraph()
odometry = np.identity(4)
pose_graph.nodes.append(o3d.pipelines.registration.PoseGraphNode(odometry))
n_pcds = len(pcds)
for source_id in range(n_pcds):
for target_id in range(source_id + 1, n_pcds):
transformation_icp, information_icp = self.pairwiseRegistration(
pcds[source_id], pcds[target_id])
print("Build o3d.pipelines.registration.PoseGraph")
if target_id == source_id + 1: # odometry case
odometry = np.dot(transformation_icp, odometry)
pose_graph.nodes.append(
o3d.pipelines.registration.PoseGraphNode(
np.linalg.inv(odometry)))
pose_graph.edges.append(
o3d.pipelines.registration.PoseGraphEdge(source_id,
target_id,
transformation_icp,
information_icp,
uncertain=False))
else: # loop closure case
pose_graph.edges.append(
o3d.pipelines.registration.PoseGraphEdge(source_id,
target_id,
transformation_icp,
information_icp,
uncertain=True))
return pose_graph
def processAndUpdate(self,pcl):
if self.count==0:
#self.pPcd = pcl.voxel_down_sample(voxel_size=self.downSampleFactor)
self.pPcd = pcl
self.pPcd.estimate_normals()
self.count+=1
print("initializing ICP")
return None, None
self.Pcd = pcl
self.Pcd.estimate_normals()
max_correspondence_distance_coarse = self.downSampleFactor * 15
max_correspondence_distance_fine = self.downSampleFactor * 1.5
transformation, info = self.pairwiseRegistration(self.pPcd, self.Pcd, max_correspondence_distance_coarse, max_correspondence_distance_fine)
R,t = transformation[:3, :3], transformation[:3, -1:]
if self.count==1:
print("initializing R,t")
self.pR_ = R
self.pt_ = t
self.count+=1
return R,t
self.pt_ = self.pt_ + 3*(self.pR_.dot(t))
self.pR_ = self.pR_.dot(R)
tvec = self.pt_.T[0]
self.X = tvec[0]
self.Y = tvec[1]
self.Z = tvec[2]
self.xpts.append(tvec[0])
self.ypts.append(tvec[2])
self.zpts.append(tvec[1])
self.pPcd = self.Pcd
return self.pR_, self.pt_
class VOpipeline:
def __init__(self, Focal, pp, impath):
self.impath = impath
fsys_handle = os.listdir(self.impath)
n_ims = len(fsys_handle)
self.count = 0
self.ckpt = 1
self.pKps = None
self.pDescs = None
self.pPts = None
self.pR = None
self.pt = None
self.pProj = None
self.inlier1, self.inlier2 = [], []
self.FOCAL = Focal
self.PP = pp
self.K = np.array([self.FOCAL, 0, self.PP[0], 0, self.FOCAL, self.PP[1], 0, 0, 1]).reshape(3, 3)
self.xpts = []
self.ypts = []
self.zpts = []
self.X = 0
self.Y = 0
self.Z = 0
self.kpmask = None
self.traj = np.zeros((600,600,3), dtype=np.uint8)
def drawDeltas(self, im, in1, in2):
dist = []
for i in range(len(in1)):
pt1 = (int(in1[i][0]) , int(in1[i][1]))
pt2 = (int(in2[i][0]) , int(in2[i][1]))
cv2.line(im, pt1, pt2, color=(0,255,0),thickness=2)
cv2.circle(im, pt1, 5, color = (0,0,255))
cv2.circle(im, pt2, 5, color = (255,0,0))
delta = math.sqrt((pt1[0]-pt2[0])**2 + (pt1[1]-pt2[1])**2)
dist.append(delta)
mean = sum(dist)/len(dist)
org = (int(im.shape[1]-(im.shape[1]*0.3)) , int(im.shape[0]-(im.shape[0]*0.1)))
im = cv2.putText(im,"Mean delta :{0:.2f} Pixels".format(mean),org,cv2.FONT_HERSHEY_SIMPLEX,0.7,color=(0,0,255),thickness=2)
return im, mean
def isRotationMatrix(self,R) :
Rt = np.transpose(R)
shouldBeIdentity = np.dot(Rt, R)
I = np.identity(3, dtype = R.dtype)
n = np.linalg.norm(I - shouldBeIdentity)
return n < 1e-6
def rotationMatrixToEulerAngles(self,R) :
assert(self.isRotationMatrix(R))
sy = math.sqrt(R[0,0] * R[0,0] + R[1,0] * R[1,0])
singular = sy < 1e-6
if not singular :
x = math.atan2(R[2,1] , R[2,2])
y = math.atan2(-R[2,0], sy)
z = math.atan2(R[1,0], R[0,0])
else :
x = math.atan2(-R[1,2], R[1,1])
y = math.atan2(-R[2,0], sy)
z = 0
return np.array([x, y, z])
def execute(self,ID):
fptr = self.impath + str(self.count).zfill(6) + ".png"
frame = cv2.imread(fptr,0)
detector = cv2.xfeatures2d.SIFT_create(2000)
kpf, descf = detector.detectAndCompute(frame,None)
if self.count==0:
self.pKps = kpf
self.pDescs = descf
print(f"CKPT {self.ckpt}")
self.ckpt+=1
self.count+=1
return None, None
bf = cv2.BFMatcher()
knnmatch = bf.knnMatch(descf, self.pDescs,k=2)
good = []
pts1 = []
pts2 = []
for m,n in knnmatch:
if m.distance < 0.8*n.distance:
good.append(m)
pts1.append(kpf[m.queryIdx].pt)
pts2.append(self.pKps[m.trainIdx].pt)
pts1 = np.array(pts1)
pts2 = np.array(pts2)
F, mask = cv2.findFundamentalMat(pts1, pts2, method=cv2.RANSAC, ransacReprojThreshold=0.1, confidence=0.99)
inlier1 = pts1[mask.ravel()==1]
inlier2 = pts2[mask.ravel()==1]
self.inlier1 = inlier1
self.inlier2 = inlier2
E, emask = cv2.findEssentialMat(inlier1, inlier2, focal=self.FOCAL, pp=self.PP)
_,R,t,pmask = cv2.recoverPose(E, inlier1, inlier2, focal = self.FOCAL, pp = self.PP)
if self.count==1:
print(f"CKPT : {self.ckpt}")
self.pR = R
self.pt = t
self.pProj = np.concatenate((np.dot(self.K,R),np.dot(self.K,t)), axis = 1)
self.count+=1
self.ckpt+=1
return R,t
kpmask = frame.copy()
kpmask = cv2.cvtColor(kpmask,cv2.COLOR_GRAY2BGR)
self.kpmask, meanDelta = self.drawDeltas(kpmask,inlier1,inlier2)
if meanDelta<3:
print("No motion")
self.count+=1
return self.pR, self.pt
self.pt = self.pt + 0.3*(self.pR.dot(t))
self.pR = self.pR.dot(R)
Proj = np.concatenate((np.dot(self.K, self.pR), np.dot(self.K,self.pt)), axis = 1)
trans = self.pt.T[0]
x, y, z = trans[0], trans[1], trans[2]
self.X = z
self.Y = x
self.Z = -y
self.xpts.append(x)
self.ypts.append(z)
self.zpts.append(-y)
draw_x, draw_y = int(x)+290, int(z)+90
cv2.circle(self.traj, (draw_x, draw_y), 1, (self.count*255/4540,255-self.count*255/4540,0), 1)
cv2.rectangle(self.traj, (10, 20), (600, 60), (0,0,0), -1)
self.pKps = kpf
self.pDescs = descf
self.count+=1
return self.pR, self.pt
class Stereo_Driver:
def __init__(self, seqNo):
rospy.init_node('camera_driver', anonymous=True)
self.frame_id = 0
self.seqNo = seqNo
self.impathL = f"/home/gautham/Documents/Datasets/dataset/sequences/{str(seqNo).zfill(2)}/image_0/"
self.impathR = f"/home/gautham/Documents/Datasets/dataset/sequences/{str(seqNo).zfill(2)}/image_1/"
self.pcpub = rospy.Publisher("/Stereo/PointCloud",PointCloud2,queue_size=10)
self.posepub = rospy.Publisher("/VO/PoseSt",PoseStamped,queue_size=10)
self.n_frames = 0
self.outpath = "/home/gautham/ros_env/src/sjtu-drone/data/"
self.bridge = CvBridge()
self.rate = rospy.Rate(5)
self.break_flg = False
self.frame0 = None
self.frame1 = None
self.points = None
self.colors = None
self.R = None
self.t = None
self.focal = 718.8560
self.pp = (607.1928, 185.2157)
self.baseline = 0.5707/15
self.clip_threshold = 10
self.wlsFilterFlag = 0
self.disparity = None
self.pointCloud = None
self.pPcd = o3d.geometry.PointCloud()
self.pcd = None
self.VO = VOpipeline(self.focal, self.pp, self.impathL)
self.ICP = PoseGraphOptimizer(downsamplefactor=0.001)
def wlsFilterCalc(self,imgL,imgR, min_disp, num_disp, p1, p2):
sigma = 2.0
lmbda = 2000.0
lstereo = cv2.StereoSGBM_create(minDisparity = min_disp,
numDisparities = num_disp,
blockSize = 5,
P1 = p1,
P2 = p2,
preFilterCap= 60,
speckleWindowSize = 3000,
speckleRange = 1,
mode=cv2.StereoSGBM_MODE_SGBM_3WAY
)
rstereo = cv2.ximgproc.createRightMatcher(lstereo)
left_disp = lstereo.compute(imgL, imgR)
right_disp = rstereo.compute(imgR, imgL)
wls = cv2.ximgproc.createDisparityWLSFilter(lstereo)
wls.setSigmaColor(sigma)
filtered_disp = wls.filter(left_disp, imgL, disparity_map_right=right_disp)
return filtered_disp
def stereo_core(self):
if self.frame0 is not None:
imgL = self.frame0
imgR = self.frame1
window_size = 1
min_disp = 2
num_disp = 80
p1 = (8*3*window_size**2)//(2**3)
p2 = (32*3*window_size**2)//(2**3)
if self.wlsFilterFlag==0:
stereo = cv2.StereoSGBM_create(minDisparity = min_disp,
numDisparities = num_disp,
blockSize = 7,
P1 = p1,
P2 = p2,
preFilterCap= 100,
speckleWindowSize = 3000,
speckleRange = 1,
mode=cv2.StereoSGBM_MODE_SGBM_3WAY
)
disparity = stereo.compute(imgL,imgR)
else:
disparity = self.wlsFilterCalc(imgL, imgR, min_disp, num_disp, p1, p2)
norm_disp = cv2.normalize(disparity,None,alpha=0,beta=255,norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)
self.disparity = norm_disp
h, w = imgL.shape[:2]
f = self.focal
rev_proj_matrix = np.zeros((4,4))
Q = np.float32([[1, 0, 0, -0.5*w],
[0, 1, 0, -0.5*h],
[0, 0, 0, f],
[0, 0, -1/self.baseline, 0]])
points = cv2.reprojectImageTo3D(disparity, Q)
# reflect_matrix = np.identity(3)
# reflect_matrix[0] *= -1
# points = np.matmul(points,reflect_matrix)
colors = cv2.cvtColor(self.frame0, cv2.COLOR_GRAY2RGB)
mask = self.disparity > ((self.disparity.max() - self.disparity.min()) * (self.clip_threshold/100))
out_colors = colors[mask]
out_colors = out_colors.reshape(-1, 3)
out_points = points[mask]
idx = np.fabs(out_points[:,0]) < 0.3
out_points = out_points[idx]
out_colors = out_colors[idx]
self.pcd = o3d.geometry.PointCloud()
self.pcd.points = o3d.utility.Vector3dVector(np.array(out_points))
self.pcd = self.pcd.voxel_down_sample(voxel_size=0.001)
filtered_points = self.StatisticOutlierRemoval(self.pcd, 300, 1.0)
#filtered_points = np.array(self.pcd.points)
self.pcd.points = o3d.utility.Vector3dVector(np.array(filtered_points))
points_refined = np.zeros_like(filtered_points)
points_refined[:,2] = filtered_points[:,1]
points_refined[:,1] = filtered_points[:,2]
points_refined[:,0] = filtered_points[:,0]
colors_refined = np.zeros_like(out_points)
colors_refined[:,2] = out_colors[:,1]
colors_refined[:,1] = out_colors[:,2]
colors_refined[:,0] = out_colors[:,0]
self.points = self.orthogonalTransform(filtered_points,0,0,0)
self.colors = colors_refined
else:
print("NULL Disparity")
def StatisticOutlierRemoval(self,cloud, n_neigh, std_ratio):
cl, ind = cloud.remove_statistical_outlier(nb_neighbors=n_neigh, std_ratio=std_ratio)
inlier_cloud = cloud.select_by_index(ind)
return np.array(inlier_cloud.points)
def transformCloud(self, cloud, R, t):
cloud.translate((t[0], t[1], t[2]))
cloud.rotate(R, center=(0, 0, 0))
self.pcd = cloud
def orthogonalTransform(self, points, rotx, roty, rotz):
points_refined = np.zeros_like(points)
points_refined[:,0] = points[:,0]
points_refined[:,2] = points[:,1]
points_refined[:,1] = points[:,2]
return points_refined
def run(self):
while True:
self.frame0 = cv2.imread(self.impathL + str(self.frame_id).zfill(6) + ".png" ,0)
self.frame1 = cv2.imread(self.impathR + str(self.frame_id).zfill(6) + ".png",0)
if self.frame0 is not None:
R,t = self.VO.execute(self.frame_id)
if self.VO.kpmask is not None:
cv2.imshow("Frame1",self.VO.kpmask)
pose_msg = PoseStamped()
if (R is not None):
rots = self.VO.rotationMatrixToEulerAngles(R)
rot = Rotation.from_matrix(R)
rot_q = rot.as_quat()
pose_msg.pose.position.x = self.VO.Y
pose_msg.pose.position.y = self.VO.X
pose_msg.pose.position.z = self.VO.Z
pose_msg.pose.orientation.x = rot_q[2]
pose_msg.pose.orientation.y = rot_q[0]
pose_msg.pose.orientation.z = -rot_q[1]
pose_msg.pose.orientation.w = rot_q[3]
Rtx = Rotation.from_quat([rot_q[2], rot_q[0], rot_q[1], rot_q[3]])
Tmat = np.array([self.VO.Y, self.VO.X, self.VO.Z])
Rmat = Rtx.as_matrix()
self.R, self.t = Rmat, Tmat
else:
pose_msg.pose.position.x = 0
pose_msg.pose.position.y = 0
pose_msg.pose.position.z = 0
pose_msg.pose.orientation.x = 0
pose_msg.pose.orientation.y = 0
pose_msg.pose.orientation.z = 0
pose_msg.pose.orientation.w = 1
Rtx = Rotation.from_quat([0, 0, 0, 1])
Tmat = np.array([0, 0, 0])
Rmat = Rtx.as_matrix()
self.R, self.t = Rmat, Tmat
self.stereo_core()
Ricp, Ticp = self.ICP.processAndUpdate(self.pcd)
print("VO tvec :\n{}\nICP tvec:\n{}\n".format(t, Ticp))
cv2.imshow("disparity",self.disparity)
cv2.imshow("trajectory",self.VO.traj)
h = Header()
h.stamp = rospy.Time.now()
h.frame_id = "map"
pose_msg.header = h
scaled_points = pcl2.create_cloud_xyz32(h,self.points*100)
self.pcpub.publish(scaled_points)
self.posepub.publish(pose_msg)
k = cv2.waitKey(100)
if k%256 == 27:
print("Escape hit, closing...")
break
elif k%256==32:
print("Writing frames {}".format(self.n_frames))
self.n_frames+=1
self.frame_id+=1
else:
print("NULL FRAME, {}.png".format(self.impathL + str(self.frame_id).zfill(6)))
break
if self.break_flg:
break
self.rate.sleep()
self.plotter(self.VO.xpts, self.VO.ypts, self.VO.zpts)
self.plotter(self.ICP.xpts, self.ICP.ypts, self.ICP.zpts)
cv2.destroyAllWindows()
def plotter(self, xpts, ypts, zpts):
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot3D(xpts, ypts, zpts, c="b")
ax.scatter3D(xpts, ypts, zpts, c= zpts, cmap='plasma')
ax.set_xlabel("X axis")
ax.set_ylabel("Y axis")
ax.set_zlabel("Z axis")
plt.show()
if __name__ == "__main__":
rig1 = Stereo_Driver(7)
rig1.run()
<file_sep>/visualOdometry/visualizer/plotter.py
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import random
from itertools import count, combinations
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import itertools
plt.style.use('ggplot')
x_values = []
y_values = []
z_values = []
xgt_values = []
ygt_values = []
zgt_values = []
chi = []
chi_op = []
xopt = []
yopt = []
zopt = []
data = pd.read_csv("/home/gautham/Documents/Projects/LargeScaleMapping/trajectory.csv")
dataOpt = pd.read_csv("/home/gautham/Documents/Projects/LargeScaleMapping/trajectoryOptimized.csv")
index = count()
print(dataOpt.iloc[:5,0], dataOpt.iloc[:5,2])
xBound = np.max( [np.max(data.iloc[:,0]), np.max(data.iloc[:,3])] )
ybound = np.max( [np.max(data.iloc[:,2]), np.max(data.iloc[:,5])] )
def animate(i):
# x_values = data.iloc[:,1]
# y_values = data.iloc[:,3]
x_values.append(data.iloc[i,0])
z_values.append(data.iloc[i,1])
y_values.append(-1*data.iloc[i,2])
xgt_values.append(data.iloc[i,3])
ygt_values.append(data.iloc[i,5])
xopt.append(dataOpt.iloc[i,0])
yopt.append(-1*dataOpt.iloc[i,2])
plt.cla()
plt.scatter(x_values, y_values, label="Noisy Est.",c="b",s=5)
#plt.plot(x_values, y_values, label="Predicted Trajectory",c="r")
plt.scatter(xgt_values, ygt_values, label="True Trajectory",c="g",s=5)
# plt.plot(xgt_values, ygt_values, label="True Trajectory",c="g")
plt.scatter(xopt, yopt, label="Optimized Est.",c="r",s=5)
#plt.plot(xopt, yopt, label="Optimized Prediction",c="b")
plt.gcf().autofmt_xdate()
plt.tight_layout()
leg = plt.legend(loc="lower right")
for handles in leg.legendHandles:
handles.set_sizes([50.0])
plt.axis("scaled")
plt.grid(True)
ani = FuncAnimation(plt.gcf(), animate, len(data.iloc[:,0]), interval=0.1)
plt.show()<file_sep>/README.md
# Large scale Multi-Agent Mapping toolkit.
**< NOTE : This project is in Active Development and the repository is subject to change. >**
## File Structure
Source file for SFM 3D reconstruction :
```
SFM_pipelime/multiview_reconstruct.cpp
```
The metadata such as Image Focal Lengths, Downscale factor can be set in ```SFM_pipeline/meta.h``` the whole process can be compiled using the shell script ```./SFM_pipeline/MVRcompile.sh```.
Source file for Stereo Processing :
```
Stereo_pipeline/Stereo_matching.py
```
Stereo is recommended if the input images are having fixed baseline distance and real time processing is preffered.
## To be added
1. PCL C++ support to natively support pointcloud view.
2. ROS integration.
3. CMAKE/Catkin build structure.
4. Qt+OpenGL GUI with plugins
5. Instance segmentation on pointclouds
## Underlying Working Process
This project can solve all these challenges to a great extent and even offers over the top functionality. Using the presented approach we can complete the following objectives:
1. The image sequence coming from the camera is sufficient for extracting most valuable informations required by a fully autonomous robotic architecture. These quantities include:
* Depth in 2D image, (x,y)-->(x,y,z)
* Instantaneous Position and Orientation of the camera as pose(x,y,z,roll,pitch,yaw)
* Continuous 3D map of the environment from stitching estimated 3D image wrt pose
* Process this 3D map to find regions of interest for applications in search and rescue robotic systems
2. Another objective we plan to achieve by the end of this project is to make the methods available as an open source package fully compatible with the filesystem of Robot Operating System(ROS) over a Linux kernel. This allows a plug and play functionality for Robotic and CV developers.
2D cameras cannot perceive depth in any way, but we can estimate the depth purely based on how each pixel changes from frame to frame. This of course presents its set of challenges:
1. The depth estimation proceeds via computational optimization problem, hence the depth estimate is completely random at t=0 and as time progresses, this estimate converges to an optimal estimate, accurate estimate at t=infinity.
2. The camera pose estimation based on feature changes in frame sequence is subject to errors due to camera distortions that accumulate over time.
3. Processing every pixel of an image exponentially increases the computational cost and makes real time implementation almost impossible.
4. While mapping depth images, camera might move to new areas before previous frames depth is mapped, which causes localization loss.
Processing an entire image data for 3D reconstruction is computationally extremely heavy.
Hence we use algorithm described by [5],ORB/SIFT features to detect certain keypoints in image that describe most significant features in the image
Once we have detected significant keypoints in an image, we can track these keypoints from one frame to another.
We use a feature matching step to find out how each keypoint moved in the current frame wrt previous frame.
Here, Red and Blue are features in 2 frames respectively and Green represents the one to one match.

## 3D Transformation and Pose Estimation
The Features we have detected till now are in the 2D plane
Based on the feature tracking, we estimate how each feature has moved in one frame with respect to the previous frame.[4],[6]
Based on this estimated movement and the fact each feature only varies from nth to (n+dn)th frame only if the surface feature is a part of a significant 3D surface.
This mathematical model relates the features from one frame to another


Dense PointCloud w/ Stereo reconstruction
<file_sep>/PyUtils/graph_match.py
import matplotlib.pyplot as plt
import cv2
import numpy as np
import glob
import tqdm
import colorama as clr
import networkx as nx
from matplotlib import style
style.use("ggplot")
impath = "/home/gautham/Documents/Datasets/SfM_quality_evaluation/Benchmarking_Camera_Calibration_2008/castle-P30/images/"
#impath = "/home/gautham/Documents/Datasets/Home/"
#impath = "/home/gautham/Documents/Datasets/Navona/"
class ImageKit:
def __init__(self):
self.ID = -1
self.Img = None
self.Kp = None
self.desc = None
self.R = None
self.t = None
self.P = None
self.matchlis = dict()
class InterFrame:
def __init__(self, f_len, pp):
self.match = None
self.inlier1 = None
self.inlier2 = None
self.F = None
self.focal = f_len
self.pp = pp
self.K1 = np.array([f_len, 0, pp[0], 0, f_len, pp[1], 0, 0, 1]).reshape(3,3)
self.K2 = np.array([f_len, 0, pp[0], 0, f_len, pp[1], 0, 0, 1]).reshape(3,3)
self.R = None
self.t = None
self.P = None
self.mode = -1
def FmatEstimate(self,pts1,pts2):
pts1 = np.int32(pts1)
pts2 = np.int32(pts2)
self.F, mask = cv2.findFundamentalMat(pts1,pts2,method=cv2.RANSAC,ransacReprojThreshold=0.1,confidence=0.99)
i1 = []
i2 = []
k1_inv = np.linalg.inv(self.K1)
k2_inv = np.linalg.inv(self.K2)
self.inlier1 = pts1[mask.ravel()==1]
self.inlier2 = pts2[mask.ravel()==1]
for i in range(len(mask)):
if mask[i]:
i1.append(k1_inv.dot([pts1[i][0], pts1[i][1], 1]))
i2.append(k2_inv.dot([pts2[i][0], pts2[i][1], 1]))
E = self._ERtEstimate()
R1, R2, t = cv2.decomposeEssentialMat(E)
if not (self.in_front_of_both_cameras(i1, i2, R1, t)):
self.R = R1
self.t = t
self.mode = 1
elif not (self.in_front_of_both_cameras(i1, i2, R1, -1*t)):
self.R = R1
self.t = -1*t
self.mode = 2
elif not (self.in_front_of_both_cameras(i1, i2, R2, t)):
self.R = R2
self.t = t
self.mode = 3
elif not (self.in_front_of_both_cameras(i1, i2, R2, -1*t)):
self.R = R2
self.t = -1*t
self.mode = 4
else:
pass
def _ERtEstimate(self):
E, mask = cv2.findEssentialMat(self.inlier1,self.inlier2,focal=self.focal, pp = self.pp)
R1,R2,t = cv2.decomposeEssentialMat(E)
self.R = cv2.Rodrigues(R2)[0]
self.t = t
return E
def in_front_of_both_cameras(self,first_points, second_points, rot, trans):
rot_inv = rot
for first, second in zip(first_points, second_points):
first_z = np.dot(rot[0, :] - second[0]*rot[2, :], trans) / np.dot(rot[0, :] - second[0]*rot[2, :], second)
first_3d_point = np.array([first[0] * first_z, first[1] * first_z, first_z])
second_3d_point = np.dot(rot.T, first_3d_point) - np.dot(rot.T, trans)
if first_3d_point[2] < 0 or second_3d_point[2] < 0:
return False
return True
class SFMnode:
def __init__(self):
self.images = []
self.matches = dict()
self.g = nx.DiGraph()
def RtTransform(self):
Rp = np.ones((3,3))
tp = np.ones((3,1))
count = 0
for i in self.images:
if(count==0):
count+=1
continue
for j,ifr in i.matchlis.items():
print(j.R, i.R)
Rp = (j.R).dot(i.R)
tp = i.t + (Rp.dot(j.t))
print(tp)
print("\n\n")
def graphLogging(self,metadata=False):
print("\n--------GRAPH LINK SUMMARY--------")
for i in self.images:
links = []
meta = []
skp = i.Kp
sdes = i.desc
for j,ifr in i.matchlis.items():
links.append(j.ID)
self.g.add_edge(i.ID,j.ID)
print("\nNode {} linked to : {}".format(i.ID,links))
def plotLinks(self):
nx.draw_kamada_kawai(self.g,with_labels=True)
plt.show()
def rescale(im1,factor):
scale_percent = factor
width = int(im1.shape[1] * scale_percent / 100)
height = int(im1.shape[0] * scale_percent / 100)
dim = (width, height)
resized = cv2.resize(im1, dim, interpolation = cv2.INTER_AREA)
return resized
counter = 0
sfm = SFMnode()
print("--------CONSTRUCTING GRAPH--------")
prevR = np.ones((3,3))
prevt = np.ones((3,1))
n_frame = 0
for f in glob.glob(impath+"*.jpg"):
im = cv2.imread(f)
SCALE_FACTOR = 30
#FOCAL_LENGTH = 2780 * (SCALE_FACTOR/100)
FOCAL_LENGTH = 3600 * (SCALE_FACTOR/100)
#FOCAL_LENGTH = 1190 * (SCALE_FACTOR/100)
PP = (im.shape[1]*(SCALE_FACTOR/100)//2, im.shape[0]*(SCALE_FACTOR/100)//2)
MATCH_THRESH = 12
im = rescale(im,SCALE_FACTOR)
ikt = ImageKit()
ikt.Img = im
ikt.ID = counter
#detector = cv2.xfeatures2d.SIFT_create(1000)
detector = cv2.ORB_create(1000)
#detector = cv2.AKAZE_create()
# FLANN_INDEX_KDTREE = 0
# index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
# search_params = dict(checks=50)
# flann = cv2.FlannBasedMatcher(index_params,search_params)
bf = cv2.BFMatcher()
kps, desc = detector.detectAndCompute(im,None)
ikt.Kp = kps
ikt.desc = desc
#print("n_features in node {} : {}".format(ikt.ID,len(kps)))
if(counter==0):
sfm.images.append(ikt)
n_frame+=1
counter+=1
continue
counter+=1
translation = []
for ims in sfm.images:
ifr = InterFrame(FOCAL_LENGTH, PP)
matches = bf.knnMatch(ikt.desc ,ims.desc, k=2)
good = []
pts1 = []
pts2 = []
for m,n in matches:
if m.distance < 0.8*n.distance:
good.append(m)
pts2.append(ims.Kp[m.trainIdx].pt)
pts1.append(ikt.Kp[m.queryIdx].pt)
if(len(good)<MATCH_THRESH):
print(f"{clr.Fore.RED}unlinking bad nodes {ikt.ID} and {ims.ID} with low matches : {len(good)}{clr.Style.RESET_ALL}")
continue
ifr.match = good
ifr.FmatEstimate(np.array(pts1), np.array(pts2))
if(len(ifr.inlier1)<MATCH_THRESH or len(ifr.inlier2)<MATCH_THRESH):
#print(f"{clr.Fore.RED}unlinking bad nodes {ikt.ID} and {ims.ID} with low Inlier count : {len(ifr.inlier1)}, {len(ifr.inlier2)}{clr.Style.RESET_ALL}")
continue
if(ifr.mode==-1):
print("--X unlinking bad nodes {} and {} with uncompatible modes : {}".format(ikt.ID, ims.ID, len(good)))
continue
#print(ifr.R,ifr.t)
print(f"{clr.Fore.GREEN}--> Node {ikt.ID} connected to {ims.ID} in mode : {ifr.mode}{clr.Style.RESET_ALL}")
if(n_frame==1):
prevR = ifr.R
prevt = ifr.t
n_frame+=1
else:
prevt = prevt + (ifr.R.dot(ifr.t))
prevR = ifr.R.dot(prevR)
"""
--> matched ims.image , ikt.image stored edge data in ifr [x]
--> extract x,y from matches [x]
--> compute F/E [x]
--> recoverpose
--> push to ifr
"""
ims.matchlis.update({ikt : ifr})
ikt.matchlis.update({ims : ifr})
n_frame=1
sfm.images.append(ikt)
sfm.graphLogging()
sfm.plotLinks()
#sfm.RtTransform()
for i in sfm.images:
skp = i.Kp
sdes = i.desc
for j,ifr in i.matchlis.items():
out = cv2.drawMatches(i.Img, skp, j.Img, j.Kp, ifr.match , None)
cv2.imshow("mats",out)
if cv2.waitKey(100) & 0xFF == ord('q'):
break
<file_sep>/SFM_pipeline/MVRcompile.sh
#!/bin/sh
g++ -g -std=c++11 -O3 multiview_reconstruct.cpp -o mview -I/usr/include/eigen3 -L/usr/local/lib -lopencv_core -lopencv_highgui -lopencv_imgproc -lopencv_features2d -lopencv_calib3d -lopencv_imgcodecs -lopencv_xfeatures2d -lgtsam -lboost_system -ltbb
<file_sep>/visualOdometry/include/monoOdometry.h
/*
-->GauthWare, LSM, 01/2021
*/
#ifndef ODOM_H
#define ODOM_H
#include <opencv2/core.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/xfeatures2d.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/features2d/features2d.hpp>
#include "DBoW2/DBoW2.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include "poseGraph.h"
#include "DloopDet.h"
#include "TemplatedLoopDetector.h"
using namespace cv;
using namespace std;
using namespace DLoopDetector;
using namespace DBoW2;
typedef TemplatedDatabase<DBoW2::FORB::TDescriptor, DBoW2::FORB> KeyFrameSelection;
struct imageMetadata{
Mat im1, im2, R, t;
vector<Point2f> refPts, trkPts;
vector<Point3f> pts3d;
};
class monoOdom{
public:
int iter = 0;
int LCidx = 0;
int cooldownTimer = 0;
int inLength = 0;
bool LC_FLAG = false;
const char* lFptr;
const char* rFptr;
Mat im1, im2, R, t, rvec, tvec, Rmono, tmono;
double focal_x = 7.188560000000e+02;
double cx = 6.071928000000e+02;
double focal_y = 7.188560000000e+02;
double cy = 1.852157000000e+02;
vector<Mat> trajectory;
Mat canvas = Mat::zeros(1000,1500, CV_8UC3);
Mat debug1, debug2, debug3;
Mat K = (Mat1d(3,3) << focal_x, 0, cx, 0, focal_y, cy, 0, 0, 1);
Mat im1prev, im2prev;
std::shared_ptr<OrbLoopDetector> loopDetector;
std::shared_ptr<OrbVocabulary> voc;
std::shared_ptr<KeyFrameSelection> KFselector;
std::string vocfile = "/home/gautham/Documents/Projects/LargeScaleMapping/orb_voc00.yml.gz";
vector<Point2f> prevFeatures;
vector<Point3f> prev3d;
imageMetadata imMeta;
imageMetadata prevImMeta;
globalPoseGraph poseGraph;
std::string LC_debug_status = "No loop closure found yet";
monoOdom(int seq, const char* lptr, const char* rptr){
lFptr = lptr; rFptr = rptr;
Params param;
param.image_rows = 1241;
param.image_cols = 376;
param.use_nss = true;
param.alpha = 0.9;
param.k = 1;
param.geom_check = GEOM_DI;
param.di_levels = 2;
voc.reset(new OrbVocabulary());
cerr<<"Loading vocabulary file : "<<vocfile<<endl;
voc->load(vocfile);
cerr<<"Done"<<endl;
loopDetector.reset(new OrbLoopDetector(*voc, param));
loopDetector->allocate(4000);
}
void restructure (cv::Mat& plain, vector<FORB::TDescriptor> &descriptors){
const int L = plain.rows;
descriptors.resize(L);
for (unsigned int i = 0; i < (unsigned int)plain.rows; i++) {
descriptors[i] = plain.row(i);
}
}
void checkLoopDetector(Mat img, int idx);
void relocalize(int start, Mat imL, Mat imR, Mat&inv_transform, vector<Point2f>&ftrPts, vector<Point3f>&pts3d);
void PyrLKtrackFrame2Frame(Mat refimg, Mat curImg, vector<Point2f>refPts, vector<Point3f>ref3dpts,
vector<Point2f>&refRetpts, vector<Point3f>&ref3dretPts);
vector<KeyPoint> denseKeypointExtractor(Mat img, int stepSize);
void stageForPGO(Mat Rl, Mat tl, Mat Rg, Mat tg, bool loopClose);
Mat drawDeltas(Mat im, vector<Point2f> in1, vector<Point2f> in2);
void monoTriangulate(Mat img1, Mat img2,vector<Point2f>&ref2dPts, vector<Point2f>&trk2dPts,vector<Point3f>&ref3dpts);
Mat drawDeltasErr(Mat img1, vector<Point2f>inlier1, vector<Point2f>inlier2);
void pyrLKtracking(Mat refImg, Mat curImg, vector<Point2f>&refPts, vector<Point2f>&trackPts);
void FmatThresholding(vector<Point2f>&refPts, vector<Point2f>&trkPts);
void relocalizeFrames(int start, Mat img1, Mat img2, Mat&invTransform, vector<Point2f>&ftrPts, vector<Point3f>pts3d);
Mat loadImage(int iter);
void updateOdometry(vector<Eigen::Isometry3d>&T);
void initSequence();
void loopSequence();
void pureMonocularSequence();
};
#endif
|
ffea9e89b5298cfe8420bf4b41e203358666072c
|
[
"CMake",
"Markdown",
"Python",
"C",
"C++",
"Shell"
] | 26 |
C++
|
Gautham-JS/LargeScaleMapping
|
e8e88f0a8a79a9d0abf4e2afe26aa94a741b3ab9
|
97e4072f9fe9709760e35604898fca121722c7d6
|
refs/heads/master
|
<repo_name>talmor/LWC-For-Canary<file_sep>/src/com/griefcraft/util/Updater.java
package com.griefcraft.util;
import com.griefcraft.LWCInfo;
import com.griefcraft.logging.Logger;
// import com.sun.net.ssl.internal.ssl.Provider;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.security.Security;
import java.util.ArrayList;
import java.util.List;
public class Updater {
private Logger logger = Logger.getLogger(getClass().getSimpleName());
// private static final String UPDATE_SITE =
// "https://github.com/Hidendra/LWC/raw/master/";
private static final String UPDATE_SITE = "https://github.com/talmor/LWC-For-Canary/raw/master/DIST/";
private static final String VERSION_FILE = "VERSION";
private static final String DIST_FILE = "LWC.jar";
private List<UpdaterFile> needsUpdating = new ArrayList();
public Updater() {
// enableSSL();
}
public void check() {
String[] paths = { "lib/sqlite.jar", "lib/" + getOSSpecificFileName() };
for (String path : paths) {
File file = new File(path);
if ((file != null) && (!file.exists()) && (!file.isDirectory())) {
UpdaterFile updaterFile = new UpdaterFile(UPDATE_SITE + path+"?raw=true");
updaterFile.setLocalLocation(path);
this.needsUpdating.add(updaterFile);
}
}
double latestVersion = getLatestVersion();
if (latestVersion > LWCInfo.VERSIONF) {
this.logger.info("Update detected for LWC");
this.logger.info("Latest version: " + latestVersion);
}
}
public boolean checkDist() {
double latestVersion = getLatestVersion();
if (latestVersion > LWCInfo.VERSIONF) {
UpdaterFile updaterFile = new UpdaterFile(UPDATE_SITE + DIST_FILE);
updaterFile.setLocalLocation("plugins/LWC.jar");
this.needsUpdating.add(updaterFile);
try {
update();
this.logger.info("Updated successful");
return true;
} catch (Exception e) {
this.logger.info("Update failed: " + e.getMessage());
e.printStackTrace();
}
}
return false;
}
public double getLatestVersion() {
try {
URL url = new URL(UPDATE_SITE + VERSION_FILE);
InputStream inputStream = url.openStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
double version = Double.parseDouble(bufferedReader.readLine());
bufferedReader.close();
return version;
} catch (Exception e) {
e.printStackTrace();
}
return 0.0D;
}
// private void enableSSL()
// {
// Security.addProvider(new Provider());
// System.setProperty("java.protocol.handler.pkgs",
// "com.sun.net.ssl.internal.www.protocol");
// }
public String getOSSpecificFileName() {
String osname = System.getProperty("os.name").toLowerCase();
String arch = System.getProperty("os.arch");
if (osname.contains("windows")) {
osname = "win";
arch = "x86";
} else if (osname.contains("mac")) {
osname = "mac";
arch = "universal";
} else if (osname.contains("nix")) {
osname = "linux";
} else if (osname.equals("sunos")) {
osname = "linux";
}
if ((arch.startsWith("i")) && (arch.endsWith("86"))) {
arch = "x86";
}
return osname + "-" + arch + ".lib";
}
public void update() throws Exception {
if (this.needsUpdating.size() == 0) {
return;
}
File folder = new File("lib");
if ((folder.exists()) && (!folder.isDirectory()))
throw new Exception("Folder \"lib\" cannot be created ! It is a file!");
if (!folder.exists()) {
this.logger.info("Creating folder : lib");
folder.mkdir();
}
this.logger.info("Need to download " + this.needsUpdating.size() + " object(s)");
for (UpdaterFile item : this.needsUpdating) {
this.logger.info(" - Downloading file : " + item.getRemoteLocation());
URL url = new URL(item.getRemoteLocation());
File file = new File(item.getLocalLocation());
if (file.exists()) {
file.delete();
}
InputStream inputStream = url.openStream();
OutputStream outputStream = new FileOutputStream(file);
saveTo(inputStream, outputStream);
inputStream.close();
outputStream.close();
this.logger.info(" + Download complete");
}
}
private void saveTo(InputStream inputStream, OutputStream outputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) > 0)
outputStream.write(buffer, 0, len);
}
}
<file_sep>/src/com/griefcraft/util/Performance.java
package com.griefcraft.util;
import com.griefcraft.logging.Logger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Performance
{
private static Logger logger = Logger.getLogger("Performance");
private static long startTime = 0L;
private static int physDBQueries = 0;
private static int memDBQueries = 0;
private static int playersOnline = 0;
private static int chestCount = 0;
private static List<String> generatedReport = new ArrayList();
public static void add(String paramString)
{
logger.info(paramString);
generatedReport.add(paramString);
}
public static void addMemDBQuery()
{
memDBQueries += 1;
}
public static void addPhysDBQuery()
{
physDBQueries += 1;
}
public static void clear()
{
generatedReport.clear();
}
public static double getAverageQueriesSecond(int paramInt)
{
return paramInt / getTimeRunningSeconds();
}
public static List<String> getGeneratedReport()
{
if (generatedReport.size() == 0)
report();
return generatedReport;
}
public static int getTimeRunningSeconds()
{
return (int)((System.currentTimeMillis() - startTime) / 1000L);
}
public static void init()
{
startTime = System.currentTimeMillis();
}
public static void report()
{
add(" ************ Start Report ************ ");
add(" ");
add(" + Date:\t" + new Date());
add(" + Time:\t" + getTimeRunningSeconds() + " seconds");
add(" + Players:\t" + playersOnline);
add(" + Protections:\t" + chestCount);
add(" ");
add(" - Physical database");
add(" + Queries:\t" + physDBQueries);
add(" + Average:\t" + getAverageQueriesSecond(physDBQueries) + " /second");
add(" ");
add(" - Memory database");
add(" + Queries:\t" + memDBQueries);
add(" + Average:\t" + getAverageQueriesSecond(memDBQueries) + " /second");
add(" ");
add(" ************ End Report ************ ");
}
public static void setChestCount(int paramInt)
{
chestCount = paramInt;
}
public static void setPlayersOnline(int paramInt)
{
playersOnline = paramInt;
}
}
/* Location: D:\dev\Minecraft Mods\server_1.6.Crow_b1.1.7\plugins\LWC.jar
* Qualified Name: com.griefcraft.util.Performance
* JD-Core Version: 0.6.0
*/<file_sep>/src/CPConverter.java
import com.griefcraft.model.Entity;
import com.griefcraft.sql.PhysDB;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ConnectException;
public class CPConverter implements Runnable {
private String[] CHESTS_FILES = { "../lockedChests.txt", "lockedChests.txt" };
private int converted = 0;
private Player player;
private PhysDB physicalDatabase;
public static void main(String[] paramArrayOfString) throws Exception {
new CPConverter();
}
public CPConverter() {
new Thread(this).start();
this.physicalDatabase = new PhysDB();
}
public CPConverter(Player paramPlayer) {
this();
this.player = paramPlayer;
}
public void convertChests() throws FileNotFoundException, IOException {
File localFile = null;
for (String localObject2 : this.CHESTS_FILES) {
localFile = new File((String) localObject2);
if ((localFile != null) && (localFile.exists()))
break;
}
if ((localFile == null) || (!localFile.exists()))
throw new FileNotFoundException("No Chest Protect chest database found");
int count = 0;
BufferedReader localBufferedReader = new BufferedReader(new FileReader(localFile));
String line = "";
while ((line = localBufferedReader.readLine()) != null) {
line = line.trim();
count++;
if (line.startsWith("#"))
continue;
String[] split = line.split(",");
if (split.length < 5)
continue;
String str1 = split[0];
int k = Integer.parseInt(split[1]);
int m = Integer.parseInt(split[2]);
int n = Integer.parseInt(split[3]);
int i1 = Integer.parseInt(split[4]);
int i2 = -1;
String str2 = "";
if (i1 == 1) {
i1 = 0;
} else if (i1 > 1) {
if (i1 == 3)
i2 = 0;
else if (i1 == 4)
i2 = 1;
i1 = 2;
}
if (split.length > 5)
str2 = split[5].trim();
log(String.format("Registering chest to %s at location {%d,%d,%d}", new Object[] { str1,
Integer.valueOf(k), Integer.valueOf(m), Integer.valueOf(n) }));
this.physicalDatabase.registerProtectedEntity(0, i1, str1, "", k, m, n);
this.converted += 1;
if (i2 == -1)
continue;
int i3 = this.physicalDatabase.loadProtectedEntity(0, k, m, n).getID();
String[] arrayOfString1 = str2.split(";");
for (String str3 : arrayOfString1) {
this.physicalDatabase.registerProtectionRights(i3, str3, 0, i2);
log(String.format(" -> Registering rights to %s on chest %d",
new Object[] { str3, Integer.valueOf(i3) }));
}
}
}
public void log(String paramString) {
System.out.println(paramString);
if (this.player != null)
this.player.sendMessage(paramString);
}
public void run() {
try {
log("LWC Conversion tool for Chest Protect chests");
log("");
log("Initializing sqlite");
boolean bool = this.physicalDatabase.connect();
if (!bool)
throw new ConnectException("Failed to connect to the sqlite database");
this.physicalDatabase.load();
log("Done.");
log("Starting conversion of Chest Protect chests");
log("");
convertChests();
log("Done.");
log("");
log("Converted >" + this.converted + "< Chest Protect chests to LWC");
log("LWC database now holds " + this.physicalDatabase.entityCount() + " protected chests!");
} catch (Exception localException) {
localException.printStackTrace();
}
}
}
/*
* Location: D:\dev\Minecraft Mods\server_1.6.Crow_b1.1.7\plugins\LWC.jar
* Qualified Name: CPConverter JD-Core Version: 0.6.0
*/<file_sep>/src/com/griefcraft/sql/Database.java
package com.griefcraft.sql;
import com.griefcraft.logging.Logger;
import com.griefcraft.util.ConfigValues;
import java.sql.Connection;
import java.sql.DriverManager;
public abstract class Database {
private Logger logger = Logger.getLogger(getClass().getSimpleName());
public Connection connection = null;
private static boolean connected = false;
public static boolean isConnected() {
return connected;
}
public boolean connect() throws Exception {
if (this.connection != null) {
return true;
}
Class.forName("org.sqlite.JDBC");
this.connection = DriverManager.getConnection("jdbc:sqlite:" + getDatabasePath());
connected = true;
return true;
}
public String getDatabasePath() {
return ConfigValues.DB_PATH.getString();
}
public abstract void load();
public void log(String str) {
this.logger.info(str);
}
}
<file_sep>/src/com/griefcraft/util/Config.java
/* */ package com.griefcraft.util;
/* */
/* */ import com.griefcraft.logging.Logger;
/* */ import java.io.File;
/* */ import java.io.FileInputStream;
/* */ import java.io.FileOutputStream;
/* */ import java.io.InputStream;
/* */ import java.io.OutputStream;
/* */ import java.util.Properties;
/* */
/* */ public class Config extends Properties
/* */ {
/* 58 */ private Logger logger = Logger.getLogger(getClass().getSimpleName());
/* */ private static Config instance;
/* */
/* */ public static void destroy()
/* */ {
/* 36 */ instance = null;
/* */ }
/* */
/* */ public static Config getInstance()
/* */ {
/* 43 */ return instance;
/* */ }
/* */
/* */ public static void init()
/* */ {
/* 50 */ if (instance == null)
/* 51 */ instance = new Config();
/* */ }
/* */
/* */ private Config()
/* */ {
/* 69 */ for (ConfigValues value : ConfigValues.values()) {
/* 70 */ setProperty(value.getName(), value.getDefaultValue());
/* */ }
/* */
/* */ try
/* */ {
/* 79 */ File conf = new File("lwc.properties");
/* */
/* 81 */ if (!conf.exists()) {
/* 82 */ save();
/* 83 */ return;
/* */ }
/* */
/* 86 */ Object inputStream = new FileInputStream(conf);
/* 87 */ load((InputStream)inputStream);
/* 88 */ ((InputStream)inputStream).close();
/* */
/* 90 */ this.logger.info("Loaded " + size() + " config entries");
/* */ } catch (Exception e) {
/* 92 */ e.printStackTrace();
/* */ }
/* */ }
/* */
/* */ public void save() {
/* */ try {
/* 98 */ File file = new File("lwc.properties");
/* */
/* 100 */ if (!file.exists()) {
/* 101 */ file.createNewFile();
/* */ }
/* */
/* 104 */ OutputStream outputStream = new FileOutputStream(file);
/* */
/* 106 */ store(outputStream, "# LWC configuration file\n\n# + Github project page: https://github.com/Hidendra/LWC\n# + hMod thread link: http://forum.hey0.net/showthread.php?tid=837\n");
/* 107 */ outputStream.close();
/* */ } catch (Exception e) {
/* 109 */ e.printStackTrace();
/* */ }
/* */ }
/* */ }
/* Location: D:\dev\Minecraft Mods\server_1.6.Crow_b1.1.7\plugins\LWC.jar
* Qualified Name: com.griefcraft.util.Config
* JD-Core Version: 0.6.0
*/<file_sep>/src/Command_Modes.java
import com.griefcraft.sql.MemDB;
import com.griefcraft.util.StringUtils;
public class Command_Modes
implements LWC_Command
{
public void execute(LWC lwc, Player player, String[] args)
{
if (args.length < 2) {
lwc.sendSimpleUsage(player, "/lwc -p <persist|droptransfer>");
return;
}
String mode = args[1].toLowerCase();
if (mode.equals("persist")) {
if ((!lwc.isAdmin(player)) && (lwc.isModeBlacklisted(mode))) {
player.sendMessage("§4That mode is currently disabled");
return;
}
lwc.getMemoryDatabase().registerMode(player.getName(), mode);
player.sendMessage("§2Persistance mode activated");
player.sendMessage("§2Type §6/lwc -r modes§2 to undo (or logout)");
}
else if (mode.equals("droptransfer")) {
mode = "dropTransfer";
if (mode.equals("dropTransfer")) {
player.sendMessage("§4Mode currently disabled.");
return;
}
if ((!lwc.isAdmin(player)) && (lwc.isModeBlacklisted(mode))) {
player.sendMessage("§4That mode is currently disabled");
return;
}
if (args.length < 3) {
player.sendMessage("§2LWC Drop Transfer");
player.sendMessage("");
player.sendMessage("§a/lwc -p droptransfer select - Select a chest to drop transfer to");
player.sendMessage("§a/lwc -p droptransfer on - Turn on drop transferring");
player.sendMessage("§a/lwc -p droptransfer off - Turn off drop transferring");
player.sendMessage("§a/lwc -p droptransfer status - Check the status of drop transferring");
return;
}
String action = args[2].toLowerCase();
String playerName = player.getName();
if (action.equals("select")) {
if (lwc.isPlayerDropTransferring(playerName)) {
player.sendMessage("§4Please turn off drop transfer before reselecting a chest.");
return;
}
lwc.getMemoryDatabase().unregisterMode(playerName, mode);
lwc.getMemoryDatabase().registerAction("dropTransferSelect", playerName, "");
player.sendMessage("§2Please left-click a registered chest to set as your transfer target.");
} else if (action.equals("on")) {
int target = lwc.getPlayerDropTransferTarget(playerName);
if (target == -1) {
player.sendMessage("§4Please register a chest before turning drop transfer on.");
return;
}
lwc.getMemoryDatabase().unregisterMode(playerName, "dropTransfer");
lwc.getMemoryDatabase().registerMode(playerName, "dropTransfer", "t" + target);
player.sendMessage("§2Drop transfer is now on.");
player.sendMessage("§2Any items dropped will be transferred to your chest.");
} else if (action.equals("off")) {
int target = lwc.getPlayerDropTransferTarget(playerName);
if (target == -1) {
player.sendMessage("§4Please register a chest before turning drop transfer off.");
return;
}
lwc.getMemoryDatabase().unregisterMode(playerName, "dropTransfer");
lwc.getMemoryDatabase().registerMode(playerName, "dropTransfer", "f" + target);
player.sendMessage("§2Drop transfer is now off.");
} else if (action.equals("status")) {
if (lwc.getPlayerDropTransferTarget(playerName) == -1) {
player.sendMessage("§2You have not registered a drop transfer target.");
}
else if (lwc.isPlayerDropTransferring(playerName))
player.sendMessage("§2Drop transfer is currently active.");
else
player.sendMessage("§2Drop transfer is currently inactive.");
}
}
}
public boolean validate(LWC lwc, Player player, String[] args)
{
return StringUtils.hasFlag(args, "p");
}
}
|
2821d6d777532c5393d03ffef2042565b6702e03
|
[
"Java"
] | 6 |
Java
|
talmor/LWC-For-Canary
|
569770a20d8f68c1d5cfb6c197acc178fbe197f9
|
e33d33625da26993ee317ed153a3ea7100934d5b
|
refs/heads/master
|
<repo_name>hjw0968/shuadan<file_sep>/js/page/taobao_account.js
var km = new Vue({
el: '#seek_apper',
data: {
BindingList: ""
},
methods: {
getdatd() {
var BindingList = {},
th = this
BindingList.key = localStorage.token
BindingList.platformType = 1
m_ajax("/api/buyer/getAccountBindingList", BindingList, function (data) {
th.BindingList = data.list
})
}
},
mounted: function () {
this.getdatd()
},
filters: { //过滤器 页面上调用{{dt.state|lei}}
sd_ert(num) {
var sd_serrt = ""
if (num == 1) {
sd_serrt = "未审核"
}
if (num == 2) {
sd_serrt = "审核通过"
}
if (num == 3) {
sd_serrt = "审核不通过"
}
return sd_serrt
}
}
})
window.addEventListener('refresh', function (e) {
km.getdatd()
})
<file_sep>/js/zujian/test.js
"use strict";
Vue.component("banner", {
props: {
banner: ""
},
template: "\n \n ",
data: function() {
return {}
},
mounted: function() {},
methods: {}
});<file_sep>/js/page/index_er.js
var km = new Vue({
el: '#seek_apper',
data: {
index_s: ""
},
methods: {
get_dads: function() {
var getIndex = {},
th = this
getIndex.key = localStorage.token
getIndex.mobileOs = mui.os.ios ? 2 : 1
getIndex.version = version
m_ajax("/api/account/getIndex", getIndex, function(data) {
th.index_s = data
if(data.isPassedTask == 0) {
mui.confirm("请先完成新手任务!", "温馨提示", ["取消", "确定"], function(e) {
if(e.index == 1) {
}
}, "div")
}
})
}
},
mounted: function() {
this.get_dads()
}
})
function chusu_e() {
km.get_dads()
}<file_sep>/js/page/user_center.js
new Vue({
el: '#seek_apper',
data: {
user_icon: "",
sd: "",
user_meat: [{
size: "16",
clsss_s: "aa", //class名字
jindu: "",
icon: "icon-fenxiang", //图标名字
name: "账号绑定",
url_er: "bind_account" //跳转地址
},
{
size: "18",
clsss_s: "ab", //class名字
icon: "icon-shezhi", //图标名字
name: "设置",
jindu: "",
url_er: "setting" //跳转地址
},
{
size: "22",
clsss_s: "ac", //class名字
icon: "icon-zhuyi", //图标名字
name: "完成率",
jindu: "33%",
url_er: "percentage_complete" //跳转地址
},
{
size: "18",
clsss_s: "ad", //class名字
icon: "icon-lingdang", //图标名字
name: "新手教学",
jindu: "",
url_er: "tutorial" //跳转地址
}, {
size: "20",
clsss_s: "ae", //class名字
icon: "icon-laba", //图标名字
name: "推广赚金",
jindu: "",
url_er: "expand_gold" //跳转地址
}, {
size: "20",
clsss_s: "af", //class名字
icon: "icon-feiji", //图标名字
name: "帮助与客服",
jindu: "",
url_er: "customer_service" //跳转地址
}, {
size: "16",
clsss_s: "ag", //class名字
icon: "icon-banbenqiehuan", //图标名字
jindu: "",
name: "版本信息",
url_er: "versions" //跳转地址
}
]
},
methods: {
tishi: function(dateer) {
var th = this
get_TE(function(dtrt_ds) {
sc.xz('', function(url_wr) {
putb64(url_wr, dtrt_ds, function(url_e) {
th.user_icon = url_e
th.shcuang(url_e)
})
})
})
},
shcuang: function(avatarUrl) {
var doAvatar = {},
th = this
doAvatar.key = localStorage.token
doAvatar.avatarUrl = avatarUrl
m_ajax("/api/buyer/doAvatar", doAvatar, function(data) {
})
},
getImage: function() {
//outSet( "开始拍照:" );
var cmr = plus.camera.getCamera(),
th = this
cmr.captureImage(function(p) {
//outLine( "成功:"+p );
plus.io.resolveLocalFileSystemURL(p, function(entry) {
th.user_icon = entry.toLocalURL()
}, function(e) {
//outLine( "读取拍照文件错误:"+e.message );
});
}, function(e) {
//outLine( "失败:"+e.message );
}, {
filename: "_doc/camera/",
index: 1
});
},
galleryImgs: function() {
// 从相册中选择图片
var th = this
plus.gallery.pick(function(e) {
th.user_icon = e.files[0]
}, function(e) {
}, {
filter: "image",
multiple: true,
system: false
});
},
tiaos_sd:function(url){
this.zhu(url)
}
},
mounted: function() {
var sd_je = {},
th = this
sd_je.key = localStorage.token
m_ajax("/api/buyer/getIndex", sd_je, function(data) {
th.user_icon = data.avatar
th.sd = data
th.user_meat[2].jindu = data.completionRate + "%"
})
}
})<file_sep>/js/page/commission_account.js
var km = new Vue({
el: '#seek_apper',
data: {
page: 1,
sd: []
},
methods: {
get_data: function(call_back) {
var getCapitalLog = {},
th = this
getCapitalLog.key = localStorage.token
getCapitalLog.page = this.page
getCapitalLog.type = 3
m_ajax("/api/account/getCommissionLog", getCapitalLog, function(data) {
try{
call_back(data.list||[])
}catch(e){
}
data.list.map(function(a) {
th.sd.push(a)
})
})
}
},
mounted: function() {
}
})
mui.init({
pullRefresh: {
container: '#pullrefresh',
up: {
contentrefresh: '正在加载...',
callback: pullupRefresh
}
}
});
function pullupRefresh() {
km.page++
var th=this
km.get_data(function(dads_e){
if(dads_e>=10){
th.endPullupToRefresh(false)
}else{
th.endPullupToRefresh(true)
}
})
}
window.addEventListener('refresh', function(e) {
km.page = 1
km.sd = []
km.get_data()
})<file_sep>/js/page/retrieve_password.js
//找回密码
new Vue({
el: '#seek_apper',
data: {
yzm: "",
form: {
key: "",
mobile: "", // 手机号
verifyCode: "", //验证码
jpassword: "", //第一次输入密码
password: "" //<PASSWORD>
}
},
methods: {
huoqu_er: function () { //获取验证码按钮触发
if (!yanza.phone(this.form.mobile)) {
mui.toast("手机号格式不正确");
return
}
var sendCode = {},
th = this
sendCode.mobile = this.form.mobile
sendCode.event = 2
sendCode.key = localStorage.key_s
// 获取验证码接口
m_ajax("/api/sms/sendCode", sendCode, function (data) {
},true)
},
queren_s: function () { //确认按钮触发
if (!yanza.phone(this.form.mobile)) {
mui.toast("手机号格式不正确");
return
}
if (!this.form.verifyCode) {
mui.toast("请输入验证码");
return
}
if (!this.form.jpassword) {
mui.toast("请输入密码");
return
}
if (!this.form.password) {
mui.toast("请输入确认密码");
return
}
if (this.form.jpassword != this.form.password) {
mui.toast("两次输入的密码不一致");
return
}
this.form.key = localStorage.key_s
var th = this
m_ajax("/api/index/resetPwd", this.form, function (data, user_in) {
localStorage.user_info = JSON.stringify(user_in)
th.zhu("login")
},true)
}
},
mounted: function () {
}
})
<file_sep>/percentage_complete.html
<!--完成率-->
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>完成率</title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<link href="css/iconfont.css" rel="stylesheet" />
<link href="css/mui.min.css" rel="stylesheet" />
<link href="css/mui.picker.min.css" rel="stylesheet" />
<link href="css/base.css" rel="stylesheet" />
<link href="css/style.css" rel="stylesheet" />
<style>
body {
background: #fff;
}
</style>
</head>
<body>
<section id="seek_apper">
<header class="mui-bar mui-bar-nav asd_uy_dftx">
<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left cf"></a>
<h1 class="mui-title cf">规则说明</h1>
</header>
<div class="mui-content pl20 pr20">
<p class=" pt20">
<img src="img/xiaols_bg.png" class="w100">
</p>
<p class="mt30 cen">
<span class="sd_jh_derterter">
<span class="z3">接单规则</span>
</span>
</p>
<p class="z6">
平台采用派单机制,用户打开APP,登录平台后,需开启接单模式,选择 愿意接单的任务类型等条件,等待系统派单,系统有订单时,会根据如下 几个规则综合后选择用户派单:
</p>
<p class="mt10 fz12 z9">
1.开启接单模式的用户<br /> 2.符合商家对账号的要求
<br /> 3.符合平台对时间间隔和订单数量的要求
<br /> 4.优先给完成率高、被投诉率低、接单量少的用户
</p>
<p class="mt30 cen">
<span class="sd_jh_derterter">
<span class="z3">完成率</span>
</span>
</p>
<p class="z6">
完成率是指你完成的订单数占所有系统派送给你的订单总数百分比。
</p>
<p class="mt10 fz12 z9">
1.系统派单之后不去操作,造成超时系统自动取消订单<br> 2.用户要求商家取消订单(或商家要求用户取消订单)
<br> 3.用户自行取消订单
<br> 4.管理员撤销的订单
</p>
<p class="mt10 fz12 z9">
维持高完成率可以保持平台对商家和用户的可靠性,也会增加系统 派送订单给你的优先级。
</p>
</div>
</section>
<script src="js/mui.min.js"></script>
<script src="js/vue.js"></script>
<script src="js/base.js"></script>
<script>
new Vue({
el: '#seek_apper',
data: {
},
methods: {
},
mounted: function() {
}
})
</script>
</body>
</html><file_sep>/README.md
独行工匠-刷单app
===
接口文档
https://www.eolinker.com/#/home/project/inside/api/list?groupID=-1&projectName=%E5%B0%8F%E7%99%BD%E5%85%94&projectHashKey=<KEY>
原型地址
http://html.xiaobay.com/#g=1&p=%E7%99%BB%E5%BD%95
<file_sep>/js/zujian/gjz.js
//垫付任务类型一:关键字
Vue.component("gjz", {
props: {
keyanswer: "",
wangwang: "",
shuju_e: ""
},
template: `
<section>
<p class="pd pt5 pm5 z6">
<i class="dx icon-bianji fz20 cz"></i> <span class="cz">任务步骤</span>
</p>
<section class="pd pt10 pm10 bgff">
<p class="fz16">
<span class="ls"> 第一步货比三家</span> <span class="ye">点击查看示例</span>
</p>
<section class=" fz14 df_jh_deert">
·请确认使用<span class="red">{{wangwang}}</span>买号登录手机淘宝应用<br> ·打开淘宝/天猫手机客户端后请手动输入关键词,关 键词不可自行修改。
<br> ·找到目标商品前可浏览至少2个同类产品,至少浏览1分钟,复制并上传分享链接
</section>
<p class="ls mt10">货比商品1</p>
<p class="f_b dsf_jerh_dert pr">
<input type="text" placeholder="货比商品链接1" v-model="huobi_a" readonly ="">
</p>
<a class="mui-btn msd_jh_drt yj4 ml10 ab" @tap="set_huobi_a(1)">粘贴</a>
<p class="ls mt10">货比商品2</p>
<p class="f_b dsf_jerh_dert pr">
<input type="text" placeholder="货比商品链接2" v-model="huobi_b" readonly ="">
</p>
<a class="mui-btn msd_jh_drt yj4 ml10 ab" @tap="set_huobi_a(2)">粘贴</a>
</section>
<section class="pd pt10 pm10 bgff btm">
<p class="fz16">
<span class="ls"> 第二步浏览店铺</span> <span class="ye">点击查看示例</span>
</p>
<section class=" fz14 df_jh_deert">
·根据商品主图、价格、名称等找到目标商品<br> ·浏览店内任意两个商品,至少浏览1分钟,复制并上传 商品分享链接。
<br> ·回到目标商品,至上向下至少浏览3分钟,在目标商 品的详情中找到以下问题的答案。
</section>
<p class="ls mt10">店铺商品1</p>
<p class="f_b dsf_jerh_dert pr">
<input type="text" placeholder="店铺商品链接1" v-model="dianpu_a" readonly ="" >
</p>
<a class="mui-btn msd_jh_drt yj4 ml10 ab" @tap="set_huobi_a(3)">粘贴</a>
<p class="ls mt10">店铺商品2</p>
<p class="f_b dsf_jerh_dert pr">
<input type="text" placeholder="店铺商品链接2" v-model="dianpu_b" readonly ="">
</p>
<a class="mui-btn msd_jh_drt yj4 ml10 ab" @tap="set_huobi_a(4)">粘贴</a>
<p class="fz14 mt10">
请在<span class="red">目标商品详情中</span>找到以下答案<span class="ye">如何找到答案</span> 答案提示{{keyanswer}}:
</p>
<p class="f_b dsf_jerh_dert pr">
<input type="text" placeholder="请输入答案" v-model="s_ddrts">
</p>
<a class="mui-btn msd_jh_drt yj4 ml10 " @tap="yanzheng">验证</a>
</section>
<section class="btm bgff pd">
<p class=" pt10 pm10 fz16">
<span class="ls">第三步 下单支付</span> <span class="ye">点击查看示例</span>
</p>
<p>点击"联系客服"按钮,和商家客服至少进行4个问题的互动</p>
<p>
把商品加入购物车,确认件数、颜色尺码和留言要求,下单付款
</p>
<p>
付款完成后,在支付宝里截一张付款图
</p>
<section class="mui-row bgff pm10 mt10">
<section class="mui-col-xs-4 pr10 mb10" v-for="(sd,idx) in fdgf_sdf" @tap="shangchuan(sd)">
<section>
<section class="dsf_jh_der_r fz12 cen pr">
<img :src="sd.url" v-if="sd.url">
<span class="sd_jh_ceertx" v-if="!sd.url">点击上传图片</span>
<i class="dx icon-tupian dsf_hj_deert" v-if="!sd.url"></i>
</section>
<p class="cen fz14 mt10">
{{sd.name}}
</p>
</section>
</section>
<p class="qc"></p>
</section>
<section class="btm bgff pd">
<p class=" pt10 pm10 fz16">
<span class="ls">第四步 填写实付金额</span> <span class="ye">点击查看示例</span>
</p>
<p>实际金额参考:{{jiner_se}}元(填写实际支付款项)</p>
<p>
<input type="number" v-model="jiner_se" class="pl0 fz14" placeholder="请输入实际付款金额">
</p>
<p>订单编号:</p>
<p>
<input type="text" placeholder="请粘贴订单编号" class="pl0 fz14" v-model="ddbianhao">
</p>
</section>
<section class="btm bgff pd pt20 pm20">
<button class="w100 f1z6" @tap="tijiao_rt">提交任务</button>
</section> </section>
`,
data: function() {
return {
is_yz: false, //地址是否验证
jiner_se: 0,
fdgf_sdf: [{
url: "",
name: "聊天"
}, {
url: "",
name: "下单支付"
}],
huobi_a: "", //货比三家
huobi_b: "",
dianpu_a: "", //店铺商品
dianpu_b: '',
s_ddrts: "", //目标详情的答案
ddbianhao: "" //订单编号
}
},
mounted: function() {},
methods: {
set_huobi_a(ty) {
if(ty == 1) {
this.huobi_a = getClipbordText()
} else if(ty == 2) {
this.huobi_b = getClipbordText()
} else if(ty == 3) {
this.dianpu_a = getClipbordText()
} else if(ty == 4) {
this.dianpu_b = getClipbordText()
}
},
yanzheng: function() { //核对
if(!this.s_ddrts) {
mui.toast("请输入目标详情的答案")
return
}
var doValidateKeyword = {}
doValidateKeyword.key = localStorage.token
doValidateKeyword.keyAnswer = this.s_ddrts
doValidateKeyword.type = 4
doValidateKeyword.orderId = this.shuju_e.orderId
m_ajax("/api/order/doValidateKeyword", doValidateKeyword, function(data, san, datasi) {
if(datasi.status == 1) {
mui.toast("验证成功")
th.is_yz = true
}
})
},
shangchuan: function(sd) { //上传图片
var th = this
get_TE(function(dtrt_ds) {
var sd_deerrt = "请上传" + sd.name
sc.xz(sd_deerrt, function(url) {
putb64(url, dtrt_ds, function(url_e) {
sd.url = url_e
})
})
})
},
tijiao_rt: function() { //提交任务
if(!this.s_ddrts) {
mui.toast("请核对关键字")
return
}
if(!this.huobi_a) {
mui.toast("请粘贴货比商品链接1")
return
}
if(!this.huobi_b) {
mui.toast("请粘贴货比商品链接2")
return
}
if(!this.dianpu_a) {
mui.toast("店铺商品1")
return
}
if(!this.dianpu_b) {
mui.toast("店铺商品2")
return
}
if(!this.s_ddrts) {
mui.toast("请输入目标详情的答案")
return
}
var sd_drrt = true
for(var i = 0; i < this.fdgf_sdf.length; i++) {
if(!this.fdgf_sdf[i].url) {
mui.toast("请上传" + this.fdgf_sdf[i].name)
return
}
}
if(!this.ddbianhao) {
mui.toast("请输入订单编号")
return
}
var doTaskOrder = {}
doTaskOrder.key = localStorage.token
doTaskOrder.orderId = this.shuju_e.orderId
doTaskOrder.thirdOrderId = this.ddbianhao //第三方平台订单号
doTaskOrder.compareGoods = [this.huobi_a, this.huobi_b] //货比三家
doTaskOrder.browseStore = [this.dianpu_a, this.dianpu_b] //浏览店铺
doTaskOrder.keyAnswer = this.s_ddrts //关键词
doTaskOrder.goodsPrice = this.jiner_se //实付金额
doTaskOrder.chatOrder=[this.fdgf_sdf[0].url,this.fdgf_sdf[1].url]
m_ajax("/api/order/doTaskOrder", doTaskOrder, function(data) {
mui.toast(data_is.msg)
})
},
}
});<file_sep>/js/page/bank_information.js
new Vue({
el: '#seek_apper',
data: {
form: {
bank: "", // 银行
bankCity: "", // 银行所在城市
bankAddress: "", // 开户行
bankAccount: "" //银行账号
}
},
methods: {
baocun_s: function() {
if(!this.form.bank) {
mui.toast("请输入银行");
return
}
if(!this.form.bankCity) {
mui.toast("请输入银行所在城市");
return
}
if(!this.form.bankAddress) {
mui.toast("请输入开户行");
return
}
if(!this.form.bankAccount) {
mui.toast("请输入银行账号");
return
}
this.form.key = localStorage.token
m_ajax("/api/buyer/doBindingBank", this.form, function(data) {
mui.back()
})
}
},
mounted: function() {
var th = this
mui.plusReady(function() {
var self = plus.webview.currentWebview();
var kmn = self.bank_s;
if(kmn) {
var getBank = {}
getBank.key = localStorage.token
m_ajax("/api/buyer/getBank", getBank, function(data) {
th.form = data
})
}
})
}
})
mui.init({
beforeback: function() {
//获得列表界面的webview
var list = plus.webview.currentWebview().opener(); //获取父窗口
//触发列表界面的自定义事件(refresh),从而进行数据刷新
mui.fire(list, 'refresh');
//返回true,继续页面关闭逻辑
return true;
}
});<file_sep>/js/zujian/llrw_jt.js
//浏览任务类型一:关键字
Vue.component("llrw_jt", {
props: {
wangwang: "",
orderId: "",
shuju_e: ""
},
template: `
<section>
<p class="pd pt5 pm5 z6">
<i class="dx icon-bianji fz20 cz"></i> <span class="cz">任务步骤</span>
</p>
<section class="pd pt10 pm10 bgff">
<p class="fz16">
<span class="ls">浏览任务</span> <span class="ye">点击查看示例</span>
</p>
<section class=" fz14 df_jh_deert">
·请确认使用<span class="red">{{wangwang}}</span> 买号登录手机淘宝应用
<br> ·打开淘宝/天猫手机客户端后请手动输入关键词,关 键词不可自行修改。
<br> ·找到目标商品 ,至少向下浏览3分钟,在详情中找到以下问题答案,并复制上传商品分享链接
</section>
<section class="mui-row bgff pm10">
<section class="mui-col-xs-4 pr10 mb10" v-for="(sd,idx) in fdgf_sdf" @tap="shangchuan(sd)" v-if="idx<3">
<section>
<section class="dsf_jh_der_r fz12 cen pr">
<img :src="sd.url" v-if="sd.url">
<span class="sd_jh_ceertx" v-if="!sd.url">点击上传图片</span>
<i class="dx icon-tupian dsf_hj_deert" v-if="!sd.url"></i>
</section>
<p class="cen fz14 mt10">
{{sd.name}}
</p>
</section>
</section>
<p class="qc"></p>
</section>
</section>
<section class="btm bgff pt10 pm10 pd">
<p class=" pt10 pm10 fz16">
<span class="red">核对店铺及商品是否正确点击</span> <span class="ye">查看示例</span>
</p>
<p class="fz14 z3 ">
1. 商家旺旺名:{{wangwang}}
</p>
<div class="fz14 z3 mt10">
2.
<p class="f_b dsf_jerh_dert pr">
<input type="text" placeholder="请点击粘贴地址" readonly :value="s_ddrts">
<a class="mui-btn mui-btn-yellow fz12 df_jher_deert" @tap="zandie">粘贴</a>
</p>
<a class="mui-btn msd_jh_drt yj4 ml10" @tap="yanzheng">核对</a>
</div>
</section>
<section class="btm bgff pd">
<p class=" pt10 pm10 fz16">
<span class="ls">收藏领券</span> <span class="ye">点击查看示例</span>
</p>
<p>
1.收藏目标商品,2.将目标商品加入购物车,3分别在商品收藏夹,购物车里显示目标商品的页面截图并上传
</p>
<section class="mui-row bgff pm10 pt10">
<section class="mui-col-xs-4 pr10 mb10" v-for="(sd,idx) in fdgf_sdf" @tap="shangchuan(sd)" v-if="idx>2">
<section>
<section class="dsf_jh_der_r fz12 cen pr">
<img :src="sd.url" v-if="sd.url">
<span class="sd_jh_ceertx" v-if="!sd.url">点击上传图片</span>
<i class="dx icon-tupian dsf_hj_deert" v-if="!sd.url"></i>
</section>
<p class="cen fz14 mt10">
{{sd.name}}
</p>
</section>
</section>
<p class="qc"></p>
</section>
<section class="btm bgff pd pt20 pm20">
<button class="w100 f1z6" @click="tijiao_rt">提交任务</button>
</section>
</section>`,
data: function() {
return {
is_yz: false, //地址是否验证
s_ddrts: "【花花公子男士背心纯棉青年透气修身型紧身运动健身打底衫跨栏夏季】夏季】http://m.tb.cn/h.34hzWmL 点击链 点击链接,再选择浏览器咑閞;或復·制这段描述€6j0gb2LSORq€后到淘♂寳♀", //目标商品
fdgf_sdf: [{
url: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534529476587&di=d25fcbf9555def2cddc6401609fe3450&imgtype=0&src=http%3A%2F%2Fimg3.100bt.com%2Fupload%2Fscrawl%2F20130512%2F1368358339253.jpg",
name: "搜索结果"
}, {
url: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534529476587&di=d25fcbf9555def2cddc6401609fe3450&imgtype=0&src=http%3A%2F%2Fimg3.100bt.com%2Fupload%2Fscrawl%2F20130512%2F1368358339253.jpg",
name: "目标商品头部"
}, {
url: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534529476587&di=d25fcbf9555def2cddc6401609fe3450&imgtype=0&src=http%3A%2F%2Fimg3.100bt.com%2Fupload%2Fscrawl%2F20130512%2F1368358339253.jpg",
name: "目标商品尾部"
}]
}
},
mounted: function() {
if(this.shuju_e.sub.task_sub_type1 == 1) {
this.fdgf_sdf.push({
url: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534529476587&di=d25fcbf9555def2cddc6401609fe3450&imgtype=0&src=http%3A%2F%2Fimg3.100bt.com%2Fupload%2Fscrawl%2F20130512%2F1368358339253.jpg",
name: "收藏商品"
})
}
if(this.shuju_e.sub.task_sub_type2 == 1) {
this.fdgf_sdf.push({
url: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534529476587&di=d25fcbf9555def2cddc6401609fe3450&imgtype=0&src=http%3A%2F%2Fimg3.100bt.com%2Fupload%2Fscrawl%2F20130512%2F1368358339253.jpg",
name: "加购物车"
})
}
if(this.shuju_e.sub.task_sub_type3 == 1) {
this.fdgf_sdf.push({
url: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534529476587&di=d25fcbf9555def2cddc6401609fe3450&imgtype=0&src=http%3A%2F%2Fimg3.100bt.com%2Fupload%2Fscrawl%2F20130512%2F1368358339253.jpg",
name: "关注店铺列表"
})
}
if(this.shuju_e.sub.task_sub_type4 == 1) {
this.fdgf_sdf.push({
url: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534529476587&di=d25fcbf9555def2cddc6401609fe3450&imgtype=0&src=http%3A%2F%2Fimg3.100bt.com%2Fupload%2Fscrawl%2F20130512%2F1368358339253.jpg",
name: "优惠券列表"
})
}
},
methods: {
zandie: function() { //粘贴
this.s_ddrts = getClipbordText()
},
yanzheng: function() { //核对
var doValidateKeyword = {},
th = this
doValidateKeyword.key = localStorage.token
doValidateKeyword.keyAnswer = this.s_ddrts
doValidateKeyword.type = 3
doValidateKeyword.orderId = this.shuju_e.orderId
m_ajax("/api/order/doValidateKeyword", doValidateKeyword, function(data, da, datasi) {
if(datasi.status == 1) {
mui.toast("验证成功")
th.is_yz = true
}
})
},
shangchuan: function(sd) { //上传图片
var th = this
get_TE(function(dtrt_ds) {
var sd_deerrt = "请上传" + sd.name
sc.xz(sd_deerrt, function(url) {
putb64(url, dtrt_ds, function(url_e) {
sd.url = url_e
})
})
})
},
tijiao_rt: function() { //提交任务
var sd_drrt = true
if(!this.is_yz) {
mui.toast("请核对店铺及商品是否正确")
return
}
for(var i = 0; i < this.fdgf_sdf.length; i++) {
if(!this.fdgf_sdf[i].url) {
mui.toast("请上传" + this.fdgf_sdf[i].name)
return
}
}
var doTaskOrder = {},
th = this
doTaskOrder.key = localStorage.token
doTaskOrder.orderId = this.shuju_e.orderId
doTaskOrder.keyAnswer = this.s_ddrts
doTaskOrder.sub = []
doTaskOrder.browseStore = []
this.fdgf_sdf.map(function(a, b) {
if(b < 3) {
doTaskOrder.browseStore.push(a.url)
}
if(b > 3) {
doTaskOrder.sub.push(a.url)
}
})
m_ajax("/api/order/doTaskOrder", doTaskOrder, function(data, dat, data_is) {
mui.toast(data_is.msg)
})
},
}
});<file_sep>/js/zujian/czrw.js
//垫付任务类型二:截图
Vue.component("renwu", {
props: {
wangwang: "",
shuju_e:""
},
template: `
<section>
<p class="pd pt5 pm5 z6">
<i class="dx icon-bianji fz20 cz"></i> <span class="cz">任务步骤</span>
</p>
<section class="pd pt10 pm10 bgff">
<p class="fz16">
<span class="ls"> 第一步货比三家</span> <span class="ye">点击查看示例</span>
</p>
<section class=" fz14 df_jh_deert">
<!--·请确认使用这么麻烦恶心买号登录手机淘宝应用<br> -->·打开淘宝/天猫手机客户端后请手动输入关键词,关 键词不可自行修改。
<br> ·找到目标商品,对搜索结果页面截图一张,依次点开 列表页任务2个商品,浏览3-5分钟分别截图
</section>
</section>
<section class="bgff">
<section class="mui-row bgff pl10">
<section class="mui-col-xs-4 pr10 mb10" v-for="(sd,idx) in fdgf_sdf" v-if="idx<3" @tap="shangchuan(sd)">
<section >
<section class="dsf_jh_der_r fz12 cen pr">
<img :src="sd.url" v-if="sd.url">
<span class="sd_jh_ceertx" v-if="!sd.url">点击上传图片</span>
<i class="dx icon-tupian dsf_hj_deert" v-if="!sd.url"></i>
</section>
<p class="cen fz14 mt10">
{{sd.name}}
</p>
</section>
</section>
<p class="qc"></p>
<!--<section class="pr10 pl10 ">
<p class="cen bgye fz16 pt10 pm10">一键上传图片</p>
</section>-->
</section>
<section class="btm bgff mt10 pd">
<p class=" pt10 pm10 fz16">
<span class="red">核对店铺及商品是否正确点击</span> <span class="ye">查看示例</span>
</p>
<p class="fz14 z3 ">
1. 商家旺旺名:{{wangwang}}
</p>
<div class="fz14 z3 mt10">
2.
<p class="f_b dsf_jerh_dert pr">
<input type="text" placeholder="请点击粘贴地址" readonly :value="s_ddrts">
<a class="mui-btn mui-btn-yellow fz12 df_jher_deert" @tap="zandie">粘贴</a>
</p>
<a class="mui-btn msd_jh_drt yj4 ml10" @tap="yanzheng">核对</a>
</div>
<p class=" pt10 pm10 fz16">
<span class="ls">第二步浏览店铺点击</span> <span class="ye">查看示例</span>
</p>
<section class=" fz14 df_jh_deert">
·根据商品主图、价格、名称等找到目标商品<br> ·点击“进入店铺”按钮依次点开店铺里面任意2个商 品,分另」截图,商品浏览需要慢慢滑动到详情底部返回 到目标商品详情页,从头到尾慢慢浏览,停留至少3分 钟,并在页面头部和底部时分别截图
</section>
</section>
</section>
<section class="mui-row bgff pm10">
<section class="mui-col-xs-4 pr10 mb10 pl10" v-for="(sd,idx) in fdgf_sdf" v-if="idx>2&&idx<7" @tap="shangchuan(sd)">
<section >
<section class="dsf_jh_der_r fz12 cen pr">
<img :src="sd.url" v-if="sd.url">
<span class="sd_jh_ceertx" v-if="!sd.url">点击上传图片</span>
<i class="dx icon-tupian dsf_hj_deert" v-if="!sd.url"></i>
</section>
<p class="cen fz14 mt10">
{{sd.name}}
</p>
</section>
</section>
<p class="qc"></p>
<!--<section class="pr10 pl10">
<p class="cen bgye fz16 pt10 pm10">一键上传图片</p>
</section>-->
</section>
<section class="btm bgff pd">
<p class=" pt10 pm10 fz16">
<span class="ls">第三步聊天下单支付</span> <span class="ye">点击查看示例</span>
</p>
<section class=" fz14 df_jh_deert">
·点击“联系客服”按钮,和商家客服至少进行4个问 题的互动,完成后截图一张
<br> ·把商品加入购物车,确认件数、颜色尺码和留言要 求,下单付款
<br> ·付款完成后,点击进入订单详情页面,截图一张
</section>
</section>
<section class="mui-row bgff pm10">
<section class="mui-col-xs-4 pr10 mb10 pl10" v-for="(sd,idx) in fdgf_sdf" v-if="idx>6" @tap="shangchuan(sd)">
<section >
<section class="dsf_jh_der_r fz12 cen pr">
<img :src="sd.url" v-if="sd.url">
<span class="sd_jh_ceertx" v-if="!sd.url">点击上传图片</span>
<i class="dx icon-tupian dsf_hj_deert" v-if="!sd.url"></i>
</section>
<p class="cen fz14 mt10">
{{sd.name}}
</p>
</section>
</section>
<p class="qc"></p>
<!--<section class="pr10 pl10">
<p class="cen bgye fz16 pt10 pm10">一键上传图片</p>
</section>-->
</section>
<section class="btm bgff pd">
<p class=" pt10 pm10 fz16">
<span class="ls">第四步 填写实付金额</span> <span class="ye">点击查看示例</span>
</p>
<p>实际金额参考:{{shifu}}元(填写实际支付款项)</p>
<p>
<input type="number" v-model="shifu" class="pl0 fz14" placeholder="请输入实际付款金额">
</p>
<p>订单编号:</p>
<p>
<input type="text" placeholder="请粘贴订单编号" class="pl0 fz14" v-model="ddbianhao">
</p>
</section>
<section class="btm bgff pd pt20 pm20">
<button class="w100 f1z6" @tap="tijiao_rt">提交任务</button>
</section></section>`,
data: function() {
return {
is_yz:false,//地址是否验证
s_ddrts: "",
s_ddrts: "",
fdgf_sdf: [{
url: "",
name: "搜索结果"
}, {
url: "",
name: "商品1"
}, {
url: "",
name: "商品2"
}, {
url: "",
name: "店内商品1"
}, {
url: "",
name: "店内商品2"
}, {
url: "",
name: "目标商品头部"
}, {
url: "",
name: "目标商品尾部"
}, {
url: "",
name: "聊天"
}, {
url: "",
name: "下单支付"
}],
shifu: "", //实际支付款
ddbianhao: "" //订单编号
}
},
mounted: function() {
},
methods: {
zandie: function() { //粘贴
this.s_ddrts = getClipbordText()
},
yanzheng: function() { //核对
var doValidateKeyword = {},
th=this
doValidateKeyword.key = localStorage.token
doValidateKeyword.keyAnswer = this.s_ddrts
doValidateKeyword.type = 3
doValidateKeyword.orderId=this.shuju_e.orderId
m_ajax("/api/order/doValidateKeyword", doValidateKeyword, function(data,data_er,datasi) {
if(datasi.status==1){
mui.toast("验证成功")
th.is_yz=true
}
})
},
shangchuan: function(sd) { //上传图片
var th = this
get_TE(function(dtrt_ds) {
var sd_deerrt = "请上传" + sd.name
sc.xz(sd_deerrt, function(url) {
putb64(url, dtrt_ds, function(url_e) {
sd.url = url_e
})
})
})
},
tijiao_rt: function() { //提交任务
if(!this.s_ddrts) {
mui.toast("请核对地址")
return
}
var sd_drrt = true
if(!this.is_yz){
mui.toast("请验证地址")
return
}
for(var i = 0; i < this.fdgf_sdf.length; i++) {
if(!this.fdgf_sdf[i].url) {
mui.toast("请上传" + this.fdgf_sdf[i].name)
return
}
}
if(!this.shifu) {
mui.toast("请输入实际付款金额")
return
}
if(!this.ddbianhao) {
mui.toast("请输入订单编号")
return
}
var doTaskOrder = {},
th=this
doTaskOrder.key = localStorage.token
doTaskOrder.orderId = this.shuju_e.orderId
doTaskOrder.thirdOrderId = this.ddbianhao //第三方平台订单号
doTaskOrder.compareGoods = [] //货比三家
doTaskOrder.browseStore = [] //浏览店铺
doTaskOrder.chatOrder = [] //聊天记录
doTaskOrder.goodsPrice = this.shifu
doTaskOrder.keyAnswer = this.s_ddrts
this.fdgf_sdf.map(function(a, b) {
if(b < 3) {
doTaskOrder.compareGoods.push(a.url)
}
if(b > 2 && b < 7) {
doTaskOrder.browseStore.push(a.url)
}
if(b > 6) {
doTaskOrder.chatOrder.push(a.url)
}
})
console.log(doTaskOrder)
m_ajax("/api/order/doTaskOrder", doTaskOrder, function(data,dat,data_is) {
mui.toast(data_is.msg)
// mui.back()
})
},
}
});<file_sep>/js/page/taobao_account_bj.js
var km = new Vue({
el: '#seek_apper',
data: {
gender: "", //性别
age: "", //年龄
orderCount: "",
id_sdf: "",
form: {
accountName: "", //第三方账号
shippingName: "", //收货人
shippingPhone: "", //收货人电话
shippingProvince: "", //收货人省份
shippingCity: "", //收货人地级市
shippingCounty: "", //市县级市
shippingStreet: "", //详细地址
accountAttribute: { //账号属性
grade: "", //淘宝账号登记
category: "" //分类id
},
images: "" //图片多个已逗号分割
},
xinxs: "",
is_fen: false,
picker: "",
picker_dj: "",
sd_de_e: "",
sd_h_xdf: "",
sd_hjh_der: [{
img_url: "",
name: "实名认证"
}, {
img_url: "",
name: "信誉信息"
}, {
img_url: "",
name: "花呗信息"
}],
fenlei: "" //分类
},
methods: {
gengia_d: function () { //更改信息点击触发
var th = this
mui.confirm("修改收货信息需要进行人工审核,审核期间无法接受任务,如需紧急处理可在工作时间联系在线客服", '温馨提示', ['确认修改', '取消修改'], function (e) {
if (e.index == 1) {
} else {
th.zhu("receipt_information", "", {
id_y: th.id_sdf
})
}
}, 'div')
},
sd_jgh(sd) {
var sd_dff = 0,
sd_de = 0
this.fenlei.map(function (a, b) {
if (a.cls == "act") {
sd_dff++
sd_de = b
}
})
if (sd_dff >= 3) {
this.fenlei[sd_de].cls = ""
}
if (sd.cls == "act") {
sd.cls = ""
} else {
sd.cls = "act"
}
var sd_drert = [],
ide_sd = []
this.fenlei.map(function (a, b) {
if (a.cls == "act") {
sd_drert.push(a.name)
ide_sd.push(a.id)
}
})
this.form.accountAttribute.category = ide_sd.join(",")
this.sd_h_xdf = sd_drert.join("/")
},
get_sdf: function () {
var th = this
mui.plusReady(function () {
var self = plus.webview.currentWebview();
var getAccountBinding = {}
getAccountBinding.key = localStorage.token
getAccountBinding.id = self.id_y
th.id_sdf = self.id_y
alert(th.id_sdf)
m_ajax("/api/buyer/getAccountBinding", getAccountBinding, function (data) {
th.form = data
th.sd_de_e = data.shippingProvince + "-" + data.shippingCity + "-" + data.shippingCounty
var sd_drert = [],
ide_sd = []
th.fenlei.map(function (a) {
data.accountAttribute.category.split(",").map(function (b) {
if (a.id == b) {
a.cls = "act"
sd_drert.push(a.name)
ide_sd.push(a.id)
}
})
})
th.form.accountAttribute.category = ide_sd.join(",")
th.sd_h_xdf = sd_drert.join("/")
var sd_ddrr = data.images.split(",")
th.sd_hjh_der[0].img_url = sd_ddrr[0]
th.sd_hjh_der[1].img_url = sd_ddrr[1]
th.sd_hjh_der[2].img_url = sd_ddrr[2]
th.gender = data.accountAttribute.gender == 1 ? '男' : '女'
th.age = data.accountAttribute.age
th.orderCount = data.orderCount
var sd_xeer = parseFloat(th.form.accountAttribute.grade) - 1
th.xinxs = dengji[sd_xeer].text
})
})
}
},
mounted: function () {
this.picker = new mui.PopPicker({
"layer": [3]
});
this.picker.setData(cityData3)
this.fenlei = fenlei
mui.previewImage();
this.get_sdf()
}
})
mui.previewImage();
window.addEventListener('refresh', function (e) {
km.get_sdf()
})
|
7375df9f4c2f263a60fbbece7443919b7eaf0502
|
[
"JavaScript",
"HTML",
"Markdown"
] | 13 |
JavaScript
|
hjw0968/shuadan
|
84c9727b703385ce427705e77261f785a2fec2b0
|
857dc89d4b379881d7881b5686d2ec20c5087972
|
refs/heads/master
|
<repo_name>natdew/coding_final<file_sep>/sketch.js
//final project
//interactive illustration narrative
//give variable to the first page
var currentPage = "actOne";
//give variables to each image
//variables for the backgrounds
var actOne;
var checkPhone;
var actOnePartTwo;
var actTwo;
var actTwoPartTwo;
var actTwoPartThree;
var actTwoPartFour;
var actThree;
var actThreePartTwo;
//variables for the main character
var womanOne;
var womanTwo;
var womanThree;
//load the images
function preload() {
//load the backgrounds
actOne = loadImage("images/actOne.png");
checkPhone = loadImage("images/phone.png");
actOnePartTwo = loadImage("images/actOnePartTwo.png");
actTwo = loadImage("images/actTwo.png");
actTwoPartTwo = loadImage("images/actTwoPartTwo.png");
actTwoPartThree = loadImage("images/actTwoPartThree.png");
actTwoPartFour = loadImage("images/actTwoPartFour.png");
actThree = loadImage("images/actThree.png");
actThreePartTwo = loadImage("images/actThreePartTwo.png");
//load the main character
womanOne = loadImage("images/womanOne.png");
womanTwo = loadImage("images/womanTwo.png");
womanThree = loadImage("images/womanThree.png");
}
//create a place to draw
function setup() {
createCanvas(800, 600);
}
function draw() {
//make user able to change scenes
if (currentPage === "checkPhone") {
drawPageCheckPhone();
} else if (currentPage === "actOne") {
drawPageActOne();
} else if (currentPage === "actOnePartTwo") {
drawPageActOnePartTwo();
} else if (currentPage === "actTwo") {
drawPageActTwo();
} else if (currentPage === "actTwoPartTwo") {
drawPageActTwoPartTwo();
} else if (currentPage === "actTwoPartThree") {
drawPageActTwoPartThree();
} else if (currentPage === "actTwoPartFour") {
drawPageActTwoPartFour();
} else if (currentPage === "actThree") {
drawPageActThree();
} else if (currentPage === "actThreePartTwo") {
drawPageActThreePartTwo();
}
}
function drawPageActOne() {
//actOne - at the party
//add background image
image(actOne, 0, 0);
//add text
fill(0);
textSize(20);
textFont("Avenir");
text("I wonder what time it is...", 445, 50);
text("I should check my phone.", 445, 73);
//mouse pressing on phone goes to next scene
if (mouseIsPressed) {
if (mouseY > 270 && mouseY < 309 && mouseX > 533 && mouseX < 551) {
currentPage = "checkPhone";
}
}
}
function drawPageCheckPhone() {
//check phone
//add image of phone
image(checkPhone, 0, 0);
//add text
fill(255);
textSize(20);
textFont("Avenir");
text("Oh shit, I should head home!", 280, 40);
text("Press the home button on the iPhone.", 280, 65);
//mouse pressing on home button goes to next scene
if (mouseIsPressed) {
if (mouseY > 486 && mouseY < 533 && mouseX > 377 && mouseX < 422) {
currentPage = "actOnePartTwo";
}
}
}
function drawPageActOnePartTwo() {
//act one part two - leaving the party
//add background image and moving image of main character
image(actOnePartTwo, 0, 0);
image(womanOne, mouseX, 90);
//mouse pressing on door goes to next scene
if (mouseIsPressed) {
if (mouseX > 521 && mouseX < 709 && mouseY > 60 && mouseY < 411) {
currentPage = "actTwo";
}
}
}
function drawPageActTwo() {
//act two - in the street
//add background image and image of main character
image(actTwo, 0, 0);
image(womanTwo, 600, 430);
//add text
fill(0);
textSize(13);
textFont("Avenir");
text("Hey baby,", 50, 310);
text("how are you doing tonight?", 50, 325);
fill(255);
textSize(20);
textFont("Avenir");
text("Oh no, a fuckboy. Click on him to make him go away!", 180, 40);
//mouse pressing on fuckboy goes to next scene
if (mouseIsPressed) {
if (mouseX > 14 && mouseX < 38 && mouseY > 364 && mouseY < 493) {
currentPage = "actTwoPartTwo";
}
}
}
function drawPageActTwoPartTwo() {
//act two part two - fuckboy is gone! yay!
//add background image and image of main character
image(actTwoPartTwo, 0, 0);
image(womanTwo, 600, 430);
//add text
fill(255);
textSize(20);
textFont("Avenir");
text("Yay he's gone and I'm safe! Click on me to continue.", 180, 40);
//click on main character to go to next scene
if (mouseIsPressed) {
if (mouseX > 608 && mouseX < 622 && mouseY > 434 && mouseY < 582) {
currentPage = "actTwoPartThree";
}
}
}
function drawPageActTwoPartThree() {
//act two part three - cockroach at feet
//add background image and cockroach images
image(actTwoPartThree, 0, 0);
//add text
fill(0);
textSize(20);
textFont("Avenir");
text("Ew!! A cockroach! Step on it!", 290, 40);
//click on cockroach to get to next scene
if (mouseIsPressed) {
if (mouseX > 149 && mouseX < 247 && mouseY > 129 && mouseY < 221) {
currentPage = "actTwoPartFour";
}
}
}
function drawPageActTwoPartFour() {
//act two part four - almost home
//add background image
image(actTwoPartFour, 0, 0);
//add text
fill(255);
textSize(20);
textFont("Avenir");
text("Almost home! Click on the fire hydrant to continue.", 173, 40);
//click on fire hydrant to get home
if (mouseIsPressed) {
if (mouseX > 34 && mouseX < 114 && mouseY > 438 && mouseY < 578) {
currentPage = "actThree";
}
}
}
function drawPageActThree() {
//act three - finally home!
//add background image and image of main character
image(actThree, 0, 0);
image(womanThree, 20, 90);
//add text
fill(255);
textSize(20);
textFont("Avenir");
text("Finally home! Time to get in bed...", 250, 40);
//click on bed to get in
if (mouseIsPressed) {
if (mouseX > 143 && mouseX < 647 && mouseY > 282 && mouseY < 478) {
currentPage = "actThreePartTwo";
}
}
}
function drawPageActThreePartTwo() {
//act three part two - at home and in bed
// add background image
image(actThreePartTwo, 0, 0);
// add text
fill(255);
textSize(15);
textFont("Avenir");
text("Z", 546, 311)
textSize(20);
textFont("Avenir");
text("Z", 566, 307)
textSize(25);
textFont("Avenir");
text("Z", 586, 303);
text("Restart", 67, 554);
//mouse pressing "restart" button restarts interaction
if (mouseIsPressed) {
if (mouseX > 38 && mouseX < 179 && mouseY > 523 && mouseY < 575) {
currentPage = "actOne";
}
}
}
|
6aba80f455786f53abc5e80920831ae0ea21703f
|
[
"JavaScript"
] | 1 |
JavaScript
|
natdew/coding_final
|
cef2db6451b0855c3b0ddc86e2133e0b866ecf22
|
93a5d2c1a4a8a342bcb5d027a66772cec2d1d020
|
refs/heads/master
|
<repo_name>XInTheDark/simple_functions<file_sep>/f2.py
def read_source_code(website):
import urllib.request
page = urllib.request.urlopen(website)
content = page.read()
print(content)
content = str(content)
file = open('source-code.txt', 'w')
file.write(content)
file.close()
print("The file named 'source-code.txt' has been created and saved. The source code is stored in that file.")
def rock_paper_scissors():
import random
x = 0
# rock=1
# paper=2
# scissors=3
hscore = 0
cscore = 0
draw = 0
while x == 0:
comp = random.randint(1, 3)
human = input('rock (r), paper (p) or scissors (s)? Or enter x to exit the game. Enter>>>')
if human != 'r':
if human != 'p':
if human != 's':
if human != 'x':
print('Invalid entry! Exiting the game...')
break
if human == 'r':
if comp == 2:
print('Computer wins! Rock vs Paper')
cscore = cscore + 1
elif comp == 1:
print('Draw! Rock vs Rock')
draw = draw + 1
else:
print('Human wins! Rock vs Scissors')
hscore = hscore + 1
if human == 'p':
if comp == 1:
print('Human wins! Paper vs Rock')
hscore = hscore + 1
elif comp == 2:
print('Draw! Paper vs Paper')
draw = draw + 1
else:
print('Computer wins! Paper vs Scissors')
cscore = cscore + 1
if human == 's':
if comp == 1:
print('Computer wins! Scissors vs Rock')
cscore = cscore + 1
if comp == 2:
print('Human wins! Scissors vs Paper')
hscore = hscore + 1
else:
print('Draw! Scissors vs Scissors')
draw = draw + 1
if human == 'x':
print('Game over.')
print('Human Score: ' + str(hscore) + '. Computer Score: ' + str(cscore) + '. Draws: ' + str(draw))
break
def encrypt_msg(message):
from cryptography.fernet import Fernet
import pyperclip
print("For this program to work, please send the file named 'pwkey' and the encrypted code to the other user.")
key = Fernet.generate_key()
file = open('pwkey', 'wb')
file.write(key)
file.close()
print('File Generated')
message2 = message.encode()
f = Fernet(key)
encrypted = f.encrypt(message2)
encrypted = encrypted.decode("ascii")
print('Encrypted:', encrypted)
pyperclip.copy(encrypted)
print('Please tell the other user to input the encrypted code in the Decrypt program')
print('(Code copied to Clipboard)')
print("Note: Please delete the 'pwkey' file after sending it to the other user. It is for one-time use only.")
def decrypt_msg(encrypted):
from cryptography.fernet import Fernet
print("For this program to work, make sure you have the file named 'pwkey' in your Python folder and the encrypted "
"code.")
file = open('pwkey', 'rb')
key = file.read()
file.close()
print('Key Retrieved')
encrypted = bytes(encrypted, 'utf-8')
f = Fernet(key)
decrypted = f.decrypt(encrypted)
decrypted = decrypted.decode()
print('Decrypted Message:')
print(decrypted)
print("Note: Please delete the 'pwkey' file after getting the decrypted message. It is for one-time use only.")
def sys_info():
import os
import platform
import sys
osname = os.name
platname = platform.system()
platrelease = platform.release()
processor = platform.processor()
platver = platform.version()
machine = platform.machine()
pyfolder = sys.executable
# The variables below are Python info
vinfo = sys.version_info
version = sys.version
apiv = sys.api_version
cright = sys.copyright
print('Below is Python system info')
print('\nVersion:', version) # \n to make a new line
print('Version Info:', vinfo)
print('API Version:', apiv)
print('Python folder path:', pyfolder)
print(cright)
print('\nBelow is This Computer system info')
print('Processor:', processor)
print('\nProcessor Architecture:', machine)
print('OS Name:', osname)
print('Platform name:', platname)
print('Platform Version:', platname, platrelease, '(' + str(platver) + ')')
def sort_nums(numlist: list, order):
z = []
numlist = str(numlist)
y = numlist.split(',')
for i in y:
num = int(i)
z.append(num)
numlist = z
# print(x)
# list.sort(x)
# print(x)
z = []
if order == 'a':
list.sort(numlist)
for j in numlist:
num2 = str(j)
z.append(num2)
z = ','.join(z)
print(z)
elif order == 'd':
list.sort(numlist, reverse=True)
for j in numlist:
num2 = str(j)
z.append(num2)
z = ','.join(z)
print(z)
<file_sep>/f1.py
def generate_insult(repeat):
import random
insults1 = ['fucking', 'shitty', 'arrogant', 'bad', 'boastful', 'bitchy', 'callous', 'nasty', 'bossy',
'sucking',
'gross', 'smelly', 'disgusting']
insults2 = ['dung', 'shit', 'sucker', 'faeces', 'jerk', 'dunce', 'dipstick', 'wanker', 'arsehole', 'bonehead',
'bugger',
'dork', 'idiot']
repeatnum = 0
def generate():
insultnum1 = random.randint(0, len(insults1) - 1)
insultnum2 = random.randint(0, len(insults1) - 1)
insult_phrase = str(insults1[insultnum1]) + ' ' + str(insults2[insultnum2])
if str(insults1[insultnum1][0]) == 'a' or str(insults1[insultnum1][0]) == 'e' or str(
insults1[insultnum1][0]) == 'i' or str(insults1[insultnum1][0]) == 'o' or str(
insults1[insultnum1][0]) == 'u':
print(f'Your insult:\nYou are an {insult_phrase}!')
else:
print(f'Your insult:\nYou are a {insult_phrase}!')
while repeatnum < repeat:
generate()
repeatnum += 1
def calc(num1, num2, method):
from sys import exit
try:
float(num1)
except ValueError:
print('Invalid!')
exit()
try:
float(num2)
except ValueError:
print('Invalid!')
exit()
if method == '+':
result = float(num1) + float(num2)
if result == int(num1) + int(num2):
result = int(num1) + int(num2)
print('Result:', result)
else:
print('Result:', result)
elif method == '-':
result = float(num1) - float(num2)
if result == int(num1) - int(num2):
result = int(num1) - int(num2)
print('Result:', result)
else:
print('Result:', result)
elif method == '*':
result = float(num1) * float(num2)
if result == int(num1) * int(num2):
result = int(num1) * int(num2)
print('Result:', result)
else:
print('Result:', result)
elif method == '/':
result = float(num1) / float(num2)
if result == int(int(num1) / int(num2)):
result = int(int(num1) / int(num2))
print('Result:', result)
else:
print('Result:', result)
else:
print("Invalid! Enter only '+', '-', '*' or '/'!")
def convert_emoji(message):
words = message.split(' ')
emoji_list = {
":)": "😊",
":(": "😢",
":D": "😆",
"LOL": "😂",
"ROFL": "🤣",
":|": "😶"
}
result = ""
for word in words:
result += emoji_list.get(word, word) + " "
print(result)
def test_prime(num):
import sys
import math
for i in range(2, math.ceil((math.sqrt(num)))):
for j in range(2, math.ceil((math.sqrt(num))) + 1):
if num % j == 0:
print('This number is composite!')
sys.exit()
print('This number is prime!')
def english_cmd():
import os
print("Note: This cmd does not work well on non-English devices.")
os.system('cmd')
def pingweb():
def pingbasic():
import ping3
print('Starting ping. Please wait a few seconds.')
ping3.ping('google.com')
import ping3
pingcount = 0
while pingcount < 5:
if (pingbasic()) is None:
print('Ping successful. Ping time (in sec):')
print(ping3.ping('google.com'))
pingcount += 1
def calc_circle(radius, method):
import decimal
decimal.getcontext().prec = 50
if method == 'area':
calc_result = decimal.Decimal(3.14159265358979323846264338327950288419716939937510 * radius * radius)
elif method == 'perimeter':
calc_result = decimal.Decimal(3.14159265358979323846264338327950288419716939937510 * radius * 2)
elif method == 'volume':
calc_result = decimal.Decimal(3.14159265358979323846264338327950288419716939937510 * (4 / 3) * (radius ** 3))
elif method == 'surface':
calc_result = decimal.Decimal(3.14159265358979323846264338327950288419716939937510 * 4 * radius * radius)
else:
print('Invalid! Exiting program...')
exit('Exit Successfully')
print('Your result is', str(calc_result) + '!')
calc_circle(1, 'lol;9')
<file_sep>/README.md
# simple_functions
Simple functions for use.
|
28492749fb597e3c52b21a9888e5ffe58797c341
|
[
"Markdown",
"Python"
] | 3 |
Python
|
XInTheDark/simple_functions
|
ca9b8fefe73d339c1b5517801b8acc26ae4914ec
|
07d669ff154a4725eee17939e844d8d79d0af687
|
refs/heads/master
|
<file_sep><?php
$config = array(
'url' => array(
'host' => 'http://www.stats.gov.cn',
'province' => '/tjsj/tjbz/tjyqhdmhcxhfdm/2015/index.html',
'city' => '/tjsj/tjbz/tjyqhdmhcxhfdm/2015/{$province}.html',
'xian' => '/tjsj/tjbz/tjyqhdmhcxhfdm/2015/{$province}/{$city}.html',
'xiang' => '/tjsj/tjbz/tjyqhdmhcxhfdm/2015/{$province}/{$city}/{$xian}.html',
'cun' => '/tjsj/tjbz/tjyqhdmhcxhfdm/2015/{$province}/{$city}/{$xian}/{$xiang}.html'
),
'db' => array(
'host' => 'localhost',
'user' => 'root',
'password' => '<PASSWORD>',
'dbname' => 'test',
'port' => '3306'
),
'reg_province' => array(
'step1' => "/<tr class='provincetr'>.+/i",
'step2' => "/<a href='\d+.html'>\W+/i",
'step3' => "/(<a href=')|(.html'>)|</i",
'step4' => "/\d+/i"
),
'reg_city' => array(
'step1' => "/<tr class='citytr'>.+/i",
'step2' => "/<a href='\d+\/\d+.html'>\W+/i",
'step3' => "/(<a href=')|(.html'>)|(<\/)/i",
'step4' => "/\d+/i"
),
'reg_xian' => array(
'step1' => "/<tr class='countytr'>.+/i",
'step2' => "/(<a href='\d+\/\d+.html'>\W+)|(<td>\W+<\/td>)/i",
'step3' => "/(<a href=')|(.html'>)|(<\/)/i",
'step4' => "/\d+/i",
'step5' => "/<td>\d+<\/td><td>\W+<\/td>/i"
),
'reg_xiang' => array(
'step1' => "/<tr class='towntr'>.+/i",
'step2' => "/<a href='\d+\/\d+.html'>\W+/i",
'step3' => "/(<a href=')|(.html'>)|(<\/)/i",
'step4' => "/\d+/i"
),
'reg_cun' => array(
'step1' => "/<tr class='villagetr'>.+/i",
'step2' => "/<td>\d+<\/td><td>\d+<\/td><td>\W+<\/td>/i",
),
'init_sql' => array(
'province' => 'CREATE TABLE `province` (`id` int(11) NOT NULL,`name` varchar(45) DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;',
'city' => "CREATE TABLE `city` (`id` int(11) NOT NULL,`name` varchar(45) DEFAULT NULL,`pid` int(11) DEFAULT NULL,`type` int(11) DEFAULT NULL COMMENT '0下级是县,1下级是乡镇',PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
'xian' => 'CREATE TABLE `xian` (`id` int(11) NOT NULL,`name` varchar(45) DEFAULT NULL,`pid` int(11) DEFAULT NULL,`cid` int(11) DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;',
'xiang' => 'CREATE TABLE `xiang` (`id` int(11) NOT NULL,`name` varchar(45) DEFAULT NULL,`pid` int(11) DEFAULT NULL,`cid` int(11) DEFAULT NULL,`xid` int(11) DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;',
'cun' => 'CREATE TABLE `cun` (`id` bigint NOT NULL,`name` varchar(45) DEFAULT NULL,`pid` int(11) DEFAULT NULL,`cid` int(11) DEFAULT NULL,`xid` int(11) DEFAULT NULL,`xgid` int(11) DEFAULT NULL,`type` int(11) DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;'
),
'sleep_time' => 0,
'error_sleep_time' => 3,
'max_cun_data' => 1000, // 村的数据量太大,分批次进行,一批的条数
# 市 下级直接是乡镇,没有县
'special_city' => array(
0 => 4419, // 广东省 东莞市
1 => 4420 // 广东省 中山市
),
# 县 没有下级
'special_xian' => array(
0 => '市辖区', // 所有市 下级有市辖区的 都是没有下级的
1 => '西沙群岛', // 海南省 三沙市
2 => '南沙群岛', // 海南省 三沙市
3 => '中沙群岛的岛礁及其海域', // 海南省 三沙市
4 => '金门县' // 福建省 泉州市 金门县
),
# 市辖区 有下级
'special_xian1' => array(
0 => 620201 // 甘肃省 嘉峪关市
),
# php utf-8不支持的地名
'special_charset' => array(
# 县 xian
'410304' => '瀍河回族区', // 河南省 洛阳市
'420505' => '猇亭区',
'341302' => '埇桥区', // 安徽省 宿州市
'411502' => '浉河区', // 河南省 信阳市
'420104' => '硚口区',
# 乡 xiang
'110112106' => '漷县镇', // 北京市 市辖区 通州区
'120117205' => '俵口乡', // 天津市 市辖区 宁河区
'130207110' => '柳树酄镇', // 河北省 唐山市 丰南区
'130208003' => '浭阳街道办事处', // 河北省 唐山市 丰润区
'130224100' => '倴城镇', // 河北省 唐山市 滦南县
'130429100' => '临洺关镇', // 河北省 邯郸市 永年县
'130523204' => '獐獏乡', // 河北省 邢台市 内丘县
'130533100' => '洺州镇', // 河北省 邢台市 威县
'130723202' => '哈咇嘎乡', // 河北省 张家口市 康保县
'130823110' => '桲椤树镇', // 河北省 承德市 平泉县
'130982104' => '鄚州镇', // 河北省 沧州市 任丘市
'131082002' => '泃阳西大街街道办事处', // 河北省 廊坊市 三河市
'131082100' => '泃阳镇', // 河北省 廊坊市 三河市
'140423104' => '虒亭镇', // 山西省 长治市 襄垣县
'140621206' => '薛圐圙乡', // 山西省 朔州市 山阴县
'140823102' => '畖底镇', // 山西省 运城市 闻喜县
'141034102' => '勍香镇', // 山西省 临汾市 汾西县
'141123209' => '圪垯上乡', // 山西省 吕梁市 兴县
'150124202' => '韮菜庄乡', // 内蒙古自治区 呼和浩特市 清水河县
'152528201' => '宝格达音髙勒苏木', // 内蒙古自治区 锡林郭勒盟 镶黄旗
'211422201' => '牤牛营子乡', // 辽宁省 葫芦岛市 建昌县
'320312003' => '垞城街道', // 江苏省 徐州市 铜山区
'320623100' => '栟茶镇', // 江苏省 南通市 如东县
'320981121' => '弶港镇', // 江苏省 盐城市 东台市
'321023101' => '氾水镇', // 江苏省 扬州市 宝应县
'330206002' => '新碶街道', // 浙江省 宁波市 北仑区
'330206004' => '大碶街道', // 浙江省 宁波市 北仑区
'330211100' => '澥浦镇', // 浙江省 宁波市 镇海区
'330212003' => '石碶街道', // 浙江省 宁波市 鄞州区
'330304007' => '三垟街道', // 浙江省 温州市 瓯海区
'330328100' => '大峃镇', // 浙江省 温州市 文成县
'330328101' => '百丈漈镇', // 浙江省 温州市 文成县
'330328108' => '峃口镇', // 浙江省 温州市 文成县
'330382005' => '翁垟街道办事处', // 浙江省 温州市 乐清市
'330681122' => '浬浦镇', // 浙江省 绍兴市 诸暨市
'331002003' => '葭沚街道', // 浙江省 台州市 椒江区
'331003204' => '上垟乡', // 浙江省 台州市 黄岩区
'331121201' => '黄垟乡', // 浙江省 丽水市 青田县
'331121213' => '汤垟乡', // 浙江省 丽水市 青田县
'331123210' => '垵口乡', // 浙江省 丽水市 遂昌县
'331126002' => '濛洲街道', // 浙江省 丽水市 庆元县
'331127208' => '大漈乡', // 浙江省 丽水市 景宁畲族自治县
'331127215' => '毛垟乡', // 浙江省 丽水市 景宁畲族自治县
'331181101' => '上垟镇', // 浙江省 丽水市 龙泉市
'331181203' => '竹垟畲族乡', // 浙江省 丽水市 龙泉市
'340181105' => '中垾镇', // 安徽省 合肥市 巢湖市
'340181107' => '烔炀镇', // 安徽省 合肥市 巢湖市
'340203005' => '瀂港街道', // 安徽省 芜湖市 弋江区
'340221100' => '湾沚镇', // 安徽省 芜湖市 芜湖县
'341021103' => '富堨镇', // 安徽省 黄山市 歙县
'341302001' => '埇桥街道', // 安徽省 宿州市 埇桥区
'341322115' => '永堌镇', // 安徽省 宿州市 萧县
'350122113' => '苔菉镇', // 福建省 福州市 连江县
'350125204' => '洑口乡', // 福建省 福州市 永泰县
'350521113' => '小岞镇', // 福建省 泉州市 惠安县
'350982105' => '磻溪镇', // 福建省 宁德市 福鼎市
'360112100' => '石埠镇', // 江西省 南昌市 新建区
'360430102' => '马垱镇', // 江西省 九江市 彭泽县
'360430108' => '瀼溪镇', // 江西省 九江市 彭泽县
'360482201' => '苏家垱乡', // 江西省 九江市 共青城市
'360821112' => '浬田镇', // 江西省 吉安市 吉安县
'360830103' => '浬田镇', // 江西省 吉安市 永新县
'360881201' => '黄垇乡', // 江西省 吉安市 井冈山市
'360926105' => '大塅镇', // 江西省 宜春市 铜鼓县
'361029200' => '珀玕乡', // 江西省 抚州市 东乡县
'361181203' => '昄大乡', // 江西省 上饶市 德兴市
'370832215' => '赵堌堆乡', // 山东省 济宁市 梁山县
'370921105' => '堽城镇', // 山东省 泰安市 宁阳县
'371702103' => '黄堽镇', // 山东省 菏泽市 牡丹区
'410221106' => '阳堌镇', // 河南省 开封市 杞县
'410225101' => '堌阳镇', // 河南省 开封市 兰考县
'410304002' => '瀍西街道办事处', // 河南省 洛阳市 瀍河回族区
'410304200' => '瀍河回族乡', // 河南省 洛阳市 瀍河回族区
'410621004' => '伾山街道办事处', // 河南省 鹤壁市 浚县
'411081103' => '神垕镇', // 河南省 许昌市 禹州市
'411325110' => '岞岖镇', // 河南省 南阳市 内乡县
'411421208' => '禇庙乡', // 河南省 商丘市 民权县
'411502104' => '浉河港镇', // 河南省 信阳市 浉河区
'411525203' => '马堽集乡', // 河南省 信阳市 固始县
'411625001' => '洺南办事处', // 河南省 周口市 郸城县
'411625002' => '洺北办事处', // 河南省 周口市 郸城县
'420114002' => '奓山街道办事处', // 湖北省 武汉市 蔡甸区
'420115087' => '豹澥街道办事处', // 湖北省 武汉市 江夏区
'420682002' => '酂阳街道办事处', // 湖北省 襄阳市 老河口市
'420984002' => '汈东街道办事处', // 湖北省 孝感市 汉川市
'420984108' => '垌塚镇', // 湖北省 孝感市 汉川市
'421022112' => '斑竹垱镇', // 湖北省 荆州市 公安县
'421125109' => '丁司垱镇', // 湖北省 黄冈市 浠水县
'422823101' => '东瀼口镇', // 湖北省 恩施土家族苗族自治州 巴东县
'430223207' => '槚山乡', // 湖南省 株洲市 攸县
'430224004' => '洣江街道办事处', // 湖南省 株洲市 茶陵县
'430381203' => '育塅乡', // 湖南省 湘潭市 湘乡市
'430528102' => '崀山镇', // 湖南省 邵阳市 新宁县
'430702100' => '河洑镇', // 湖南省 常德市 武陵区
'430721104' => '官垱镇', // 湖南省 常德市 安乡县
'430723107' => '大堰垱镇', // 湖南省 常德市 澧县
'430922208' => '鲊埠回族乡', // 湖南省 益阳市 桃江县
'431224200' => '洑水湾乡', // 湖南省 怀化市 溆浦县
'440103018' => '茶滘街道', // 广东省 广州市 荔湾区
'440103019' => '东漖街道', // 广东省 广州市 荔湾区
'440606102' => '北滘镇', // 广东省 佛山市 顺德区
'441502004' => '田墘街道', // 广东省 汕尾市 城区
'441521105' => '鮜门镇', // 广东省 汕尾市 海丰县
'441624112' => '浰源镇', // 广东省 河源市 和平县
'441823110' => '大崀镇', // 广东省 清远市 阳山县
'441900124' => '道滘镇', // 广东省 东莞市
'441900129' => '高埗镇', // 广东省 东莞市
'445122123' => '汫洲镇', // 广东省 潮州市 饶平县
'445321114' => '簕竹镇', // 广东省 云浮市 新兴县
'450422104' => '埌南镇', // 广西壮族自治区 梧州市 藤县
'450603101' => '大菉镇', // 广西壮族自治区 防城港市 防城区
'450722102' => '石埇镇', // 广西壮族自治区 钦州市 浦北县
'500101138' => '瀼渡镇', // 重庆市 市辖区 万州区
'510422204' => '鳡鱼彝族乡', // 四川省 攀枝花市 盐边县
'511011110' => '椑木镇', // 四川省 内江市 东兴区
'511011112' => '椑南镇', // 四川省 内江市 东兴区
'511528101' => '僰王山镇', // 四川省 宜宾市 兴文县
'513221109' => '绵虒镇', // 四川省 阿坝藏族羌族自治州 汶川县
'513426100' => '鲹鱼河镇', // 四川省 凉山彝族自治州 会东县
'520203106' => '牂牁镇', // 贵州省 六盘水市 六枝特区
'520324206' => '桴㯊乡', // 贵州省 遵义市 正安县
'520522210' => '永燊乡', // 贵州省 毕节市 黔西县
'522626100' => '思旸镇', // 贵州省 黔东南苗族侗族自治州 岑巩县
'522629106' => '磻溪镇', // 贵州省 黔东南苗族侗族自治州 剑河县
'522731002' => '濛江街道', // 贵州省 黔南布依族苗族自治州 惠水县
'530181006' => '禄脿街道办事处', // 云南省 昆明市 安宁市
'532322103' => '法脿镇', // 云南省 楚雄彝族自治州 双柏县
'610122101' => '洩湖镇', // 陕西省 西安市 蓝田县
'610304103' => '磻溪镇', // 陕西省 宝鸡市 陈仓区
'610331106' => '王家堎镇', // 陕西省 宝鸡市 太白县
'610502103' => '下邽镇', // 陕西省 渭南市 临渭区
'610631206' => '崾崄乡', // 陕西省 延安市 黄龙县
'610826103' => '定仙墕镇', // 陕西省 榆林市 绥德县
'610828108' => '朱家坬镇', // 陕西省 榆林市 佳县
'620821200' => '汭丰乡', // 甘肃省 平凉市 泾川县
'622901101' => '枹罕镇', // 甘肃省 临夏回族自治州 临夏市
)
);
?><file_sep><?php
function select_db($sql) {
$result = array();
$conn = connect_db();
try {
$result1 = mysqli_query($conn, $sql);
while ($tmp = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
$result[] = $tmp;
}
} catch (Exception $e) {
die(mysqli_error($conn));
}
mysqli_close($conn);
return $result;
}
function insert_db($sql) {
$conn = connect_db();
try {
$arr_sql = explode(';', $sql);
mysqli_autocommit($conn, false);
foreach ($arr_sql as $str_sql) {
if ($str_sql) {
mysqli_query($conn, $str_sql);
}
}
mysqli_commit($conn);
} catch (Exception $e) {
mysqli_rollback($conn);
die(mysqli_error($conn).'^^^^^^'.$e);
}
mysqli_close($conn);
}
function init_db($dbname, $arr_table_sql) {
$arr_table = array_keys($arr_table_sql);
$table_name = implode("','", $arr_table);
$select_sql = "select `table_name` from `information_schema`.`tables` where `table_schema`='{$dbname}' and `table_name` in ('{$table_name}');";
$arr_table_db = select_db($select_sql);
$arr_table_db1 = array();
foreach ($arr_table_db as $table_db) {
$arr_table_db1[] = $table_db['table_name'];
}
$arr_table_diff = array_diff($arr_table, $arr_table_db1);
$arr_sql = array();
foreach ($arr_table_diff as $table_diff) {
$arr_sql[] = $arr_table_sql[$table_diff];
}
if (count($arr_sql) > 0) {
$insert_sql = implode(';', $arr_sql);
insert_db($insert_sql);
}
}
function connect_db() {
global $config;
$conn = mysqli_connect($config['db']['host'], $config['db']['user'], $config['db']['password'], $config['db']['dbname'], $config['db']['port']);
if (mysqli_connect_errno($conn)) {
die('连接失败,'.mysqli_connect_error());
}
return $conn;
}
?><file_sep>## db
> 查询数据库表结构
> php5 mysql
## pacong
> 抓取省市县乡村数据,自动创建所需表
> php5 mysql
## 本项目提供的所有功能,仅供技术研究学习时使用<file_sep><?php
# 临时变量
$data = array(
'province' => array(),
'city' => array(),
'xian' => array(),
'xiang' => array(),
'special_city' => array()
);
# begin run
require_once('config.php');
require_once('mysql.php');
# utf-8字符集不支持的中文地名
$arr_special_charset = array_keys($config['special_charset']);
init_db($config['db']['dbname'], $config['init_sql']);
# 0全部重新抓取, 1(市)忽略省, 2(县)忽略省市, 3(乡)忽略省市县, 4(村)仅抓取村的数据
run(0);
# end
function run($type) {
global $config;
global $data;
global $arr_special_charset;
# 省 province
if ($type < 1) {
$url_province = $config['url']['host'].$config['url']['province'];
$data['province'] = get_province($url_province);
$sql = '';
foreach ($data['province'] as $province) {
$name_province_temp = mb_convert_encoding($province['name'], 'utf-8', 'gb2312');
$sql .= "insert into `{$config['db']['dbname']}`.`province` (`id`, `name`) values ({$province['id']},'{$name_province_temp}');";
}
insert_db($sql);
echo "province success:".count($data['province'])."\n";
} else if ($type == 1) {
$sql_province = "select * from `{$config['db']['dbname']}`.`province`;";
$data['province'] = select_db($sql_province);
if (count($data['province']) == 0) {
die('no province data');
}
}
# 市 city
if ($type < 2) {
foreach ($data['province'] as $province) {
$url_city = $config['url']['host'].str_replace('{$province}', $province['id'], $config['url']['city']);
$data['city'] = array_merge($data['city'], get_city($url_city, $province));
}
$sql = '';
foreach ($data['city'] as $city) {
$name_city_temp = mb_convert_encoding($city['name'], 'utf-8', 'gb2312');
$sql .= "insert into `{$config['db']['dbname']}`.`city` (`id`, `name`, `pid`, `type`) values ({$city['id']},'{$name_city_temp}',{$city['pid']},{$city['type']});";
}
insert_db($sql);
echo "city success:".count($data['city'])."\n";
} else if ($type == 2) {
$sql_city = "select * from `{$config['db']['dbname']}`.`city`;";
$data['city'] = select_db($sql_city);
if (count($data['city']) == 0) {
die('no city data');
}
foreach ($data['city'] as $city_temp) {
if (in_array($city_temp['id'], $config['special_city'])) {
$data['special_city'][] = $city_temp;
}
}
}
# 县/区 xian
if ($type < 3) {
foreach ($data['city'] as $city) {
if (in_array($city['id'], $config['special_city'])) {
continue;
}
$url_xian = $config['url']['host'].str_replace('{$city}', $city['id'], str_replace('{$province}', $city['pid'], $config['url']['xian']));
$data['xian'] = array_merge($data['xian'], get_xian($url_xian, $city));
}
$sql = '';
foreach ($data['xian'] as $xian) {
$name_xian_temp = '';
if (in_array($xian['id'], $arr_special_charset)) {
$name_xian_temp = $config['special_charset'][$xian['id']];
} else {
$name_xian_temp = mb_convert_encoding($xian['name'], 'utf-8', 'gb2312');
}
$sql .= "insert into `{$config['db']['dbname']}`.`xian` (`id`, `name`, `pid`, `cid`) values ('{$xian['id']}','{$name_xian_temp}','{$xian['pid']}','{$xian['cid']}');";
}
insert_db($sql);
echo "xian success:".count($data['xian'])."\n";
} else if ($type == 3) {
$sql_xian = "select * from `{$config['db']['dbname']}`.`xian` where `name` not in ('".implode("','", $config['special_xian'])."') union select * from `{$config['db']['dbname']}`.`xian` where `id` in (".implode("','", $config['special_xian1']).");";
$data['xian'] = select_db($sql_xian);
if (count($data['xian']) == 0) {
die('no xian data');
}
$sql_city = "select * from `{$config['db']['dbname']}`.`city` where `type` = 1;";
$data['special_city'] = select_db($sql_city);
}
# 乡/镇 xiang
if ($type < 4) {
foreach ($data['xian'] as $xian) {
if (in_array($xian['name'], $config['special_xian'])) {
continue;
}
$url_xiang = $config['url']['host'].str_replace('{$xian}', $xian['id'], str_replace('{$city}', str_replace($xian['pid'], '', $xian['cid']), str_replace('{$province}', $xian['pid'], $config['url']['xiang'])));
$data['xiang'] = array_merge($data['xiang'], get_xiang($url_xiang, $xian));
}
foreach ($data['special_city'] as $special_city) {
$url_xiang1 = $config['url']['host'].str_replace('{$city}', $special_city['id'], str_replace('{$province}', $special_city['pid'], $config['url']['xian']));
$xian = array('id' => 0, 'name' => $special_city['name'], 'pid' => $special_city['pid'], 'cid' => $special_city['id']);
$data['xiang'] = array_merge($data['xiang'], get_xiang($url_xiang1, $xian));
}
$sql = '';
foreach ($data['xiang'] as $xiang) {
$name_xiang_temp = '';
if (in_array($xiang['id'], $arr_special_charset)) {
$name_xiang_temp = $config['special_charset'][$xiang['id']];
} else {
$name_xiang_temp = mb_convert_encoding($xiang['name'], 'utf-8', 'gb2312');
}
$sql .= "insert into `{$config['db']['dbname']}`.`xiang` (`id`, `name`, `pid`, `cid`, `xid`) values ('{$xiang['id']}','{$name_xiang_temp}','{$xiang['pid']}','{$xiang['cid']}','{$xiang['xid']}');";
}
insert_db($sql);
echo "xiang success:".count($data['xiang'])."\n";
} else if ($type == 4) {
$sql_xiang = "select * from `{$config['db']['dbname']}`.`xiang`;";
$data['xiang'] = select_db($sql_xiang);
if (count($data['xiang']) == 0) {
die('no xiang data');
}
}
# 村/社区 cun
if ($type < 5) {
$count = 0;
$arr_cun = array();
foreach ($data['xiang'] as $xiang) {
$url_cun = '';
if ($xiang['xid'] == 0) {
$url_cun = $config['url']['host'].str_replace('{$xian}', $xiang['id'], str_replace('{$city}', str_replace($xiang['pid'], '', $xiang['cid']), str_replace('{$province}', $xiang['pid'], $config['url']['xiang'])));
} else {
$url_cun = $config['url']['host'].str_replace('{$xiang}', $xiang['id'], str_replace('{$xian}', str_replace($xiang['cid'], '', $xiang['xid']), str_replace('{$city}', str_replace($xiang['pid'], '', $xiang['cid']), str_replace('{$province}', $xiang['pid'], $config['url']['cun']))));
}
$arr_cun = array_merge($arr_cun, get_cun($url_cun, $xiang));
if (count($arr_cun) >= $config['max_cun_data']) {
insert_cun($arr_cun);
$arr_cun = array();
$count++;
}
}
$cnt = count($arr_cun);
if ($cnt > 0) {
insert_cun($arr_cun);
$count++;
}
echo "cun success:".$count*$config['max_cun_data'] + $cnt."\n";
}
}
function insert_cun($arr_cun) {
global $config;
$sql = '';
foreach ($arr_cun as $cun) {
$name_cun_temp = mb_convert_encoding($cun['name'], 'utf-8', 'gb2312');
$sql .= "insert into `{$config['db']['dbname']}`.`cun` (`id`, `name`, `pid`, `cid`, `xid`, `xgid`, `type`) values ({$cun['id']},'{$name_cun_temp}',{$cun['pid']},{$cun['cid']},{$cun['xid']},{$cun['xgid']},{$cun['type']});";
}
insert_db($sql);
}
function get_province($url) {
global $config;
if ($config['sleep_time']) {
sleep($config['sleep_time']);
}
echo "get_province().........begin...........";
$result = array();
try {
$html_province = @file_get_contents($url);
if (!$html_province) {
throw new Exception('http_304');
}
} catch (Exception $e) {
echo ".........error...........\n";
if ($config['error_sleep_time']) {
sleep($config['error_sleep_time']);
}
return get_province($url);
}
preg_match_all($config['reg_province']['step1'], $html_province, $match_province1);
if (count($match_province1[0]) == 0) {
return $result;
}
$str_province1 = $match_province1[0][0];
preg_match_all($config['reg_province']['step2'], $str_province1, $match_province2);
if (count($match_province2[0]) == 0) {
die('match2 error');
}
foreach ($match_province2[0] as $str_province_temp) {
$str_province3 = preg_replace($config['reg_province']['step3'], '', $str_province_temp);
preg_match_all($config['reg_province']['step4'], $str_province3, $match_province4);
if (count($match_province4) == 0) {
die('match4 error:'.$str_province_temp);
}
foreach ($match_province4[0] as $str_province_temp) {
$str_province5 = str_replace($str_province_temp, '', $str_province3);
$result[] = array('id' => $str_province_temp, 'name' => $str_province5);
}
}
echo ".........end.............".count($result).".....\n";
return $result;
}
function get_city($url, $province) {
global $config;
if ($config['sleep_time']) {
sleep($config['sleep_time']);
}
echo "get_city({$province['id']}).........begin...........";
$result = array();
try {
$html_city = @file_get_contents($url);
if (!$html_city) {
throw new Exception('http_304');
}
} catch (Exception $e) {
echo ".........error...........\n";
if ($config['error_sleep_time']) {
sleep($config['error_sleep_time']);
}
return get_city($province['id']);
}
preg_match_all($config['reg_city']['step1'], $html_city, $match_city1);
if (count($match_city1[0]) == 0) {
echo ".........error2...........\n";
if ($config['error_sleep_time']) {
sleep($config['error_sleep_time']);
}
return get_city($province['id']);
}
$str_city1 = $match_city1[0][0];
preg_match_all($config['reg_city']['step2'], $str_city1, $match_city2);
if (count($match_city2[0]) == 0) {
return $result;
}
foreach ($match_city2[0] as $str_city_temp) {
$str_city3 = str_replace($province['id'].'/', '', preg_replace($config['reg_city']['step3'], '', $str_city_temp));
preg_match_all($config['reg_city']['step4'], $str_city3, $match_city4);
if (count($match_city4) == 0) {
die('city match4 error:'.$str_city_temp);
}
foreach ($match_city4[0] as $str_city_temp) {
$str_city5 = str_replace($str_city_temp, '', $str_city3);
$type = 0;
if (in_array($str_city_temp, $config['special_city'])) {
$type = 1;
$data['special_city'][] = array('pid' => $province['id'], 'id' => $str_city_temp, 'name' => $str_city5, 'type' => $type);
}
$result[] = array('pid' => $province['id'], 'id' => $str_city_temp, 'name' => $str_city5, 'type' => $type);
}
}
echo ".........end.............".count($result).".....\n";
return $result;
}
function get_xian($url, $city) {
global $config;
if ($config['sleep_time']) {
sleep($config['sleep_time']);
}
echo "get_xian({$city['id']}).........begin...........";
$result = array();
try {
$html_xian = @file_get_contents($url);
if (!$html_xian) {
throw new Exception('http_304');
}
} catch (Exception $e) {
echo ".........error1...........\n";
if ($config['error_sleep_time']) {
sleep($config['error_sleep_time']);
}
return get_xian($url, $city);
}
preg_match_all($config['reg_xian']['step1'], $html_xian, $match_xian1);
if (count($match_xian1[0]) == 0) {
echo "...no xian...\n";
return $result;
}
$str_xian1 = $match_xian1[0][0];
preg_match_all($config['reg_xian']['step2'], $str_xian1, $match_xian2);
if (count($match_xian2[0]) == 0) {
die('xian match2 error');
}
foreach ($match_xian2[0] as $str_xian_temp) {
$str_xian3 = '';
if (strripos($str_xian_temp, 'td') > 0) {
$str_xian_temp1 = str_replace('</td>','', $str_xian_temp);
$reg_xian5 = "/<td>\d+<\/td>".$str_xian_temp1."<\/td>/i";
preg_match_all($reg_xian5, $str_xian1, $match_xian5);
if (count($match_xian5[0]) == 0) {
die('xian match5 error');
}
$str_xian3 = str_replace('000000', '', str_replace('<td>', '', str_replace('</td>', '', $match_xian5[0][0])));
} else {
$str_xian3 = str_replace(str_replace($city['pid'] ,'', $city['id']).'/', '', preg_replace($config['reg_xian']['step3'], '', $str_xian_temp));
}
preg_match_all($config['reg_xian']['step4'], $str_xian3, $match_xian4);
if (count($match_xian4[0]) == 0) {
die('xian match4 error:'.$str_xian_temp);
}
foreach ($match_xian4[0] as $str_xian_temp) {
$str_xian5 = str_replace($str_xian_temp, '', $str_xian3);
$result[] = array('pid' => $city['pid'], 'id' => $str_xian_temp, 'name' => $str_xian5, 'cid' => $city['id']);
}
}
echo ".........end.............".count($result).".....\n";
return $result;
}
function get_xiang($url, $xian) {
global $config;
if ($config['sleep_time']) {
sleep($config['sleep_time']);
}
echo "get_xiang({$xian['id']}).........begin...........";
$result = array();
try {
$html_xiang = @file_get_contents($url);
if (!$html_xiang) {
throw new Exception('http_304');
}
} catch (Exception $e) {
echo ".........error...........\n";
if ($config['error_sleep_time']) {
sleep($config['error_sleep_time']);
}
return get_xiang($url, $xian);
}
preg_match_all($config['reg_xiang']['step1'], $html_xiang, $match_xiang1);
if (count($match_xiang1[0]) == 0) {
echo "...no xiang...\n";
return $result;
}
$str_xiang1 = $match_xiang1[0][0];
preg_match_all($config['reg_xiang']['step2'], $str_xiang1, $match_xiang2);
if (count($match_xiang2[0]) == 0) {
die('xiang match2 error');
}
foreach ($match_xiang2[0] as $str_xiang_temp) {
$str_xiang3_temp = str_replace($xian['cid'],'', $xian['id']).'/';
if ($xian['id'] == 0) {
$str_xiang3_temp = str_replace($xian['pid'],'', $xian['cid']).'/';
}
$str_xiang3 = str_replace($str_xiang3_temp, '', preg_replace($config['reg_xiang']['step3'], '', $str_xiang_temp));
preg_match_all($config['reg_xiang']['step4'], $str_xiang3, $match_xiang4);
if (count($match_xiang4[0]) == 0) {
die('xiang matchg4 error:'.$str_xiang_temp);
}
foreach ($match_xiang4[0] as $str_xiang_temp) {
$str_xiang5 = str_replace($str_xiang_temp, '', $str_xiang3);
$result[] = array('pid' => $xian['pid'], 'id' => $str_xiang_temp, 'name' => $str_xiang5, 'cid' => $xian['cid'], 'xid' => $xian['id']);
}
}
echo ".........end.............".count($result).".....\n";
return $result;
}
function get_cun($url, $xiang) {
global $config;
if ($config['sleep_time']) {
sleep($config['sleep_time']);
}
echo "get_cun({$xiang['id']}).........begin...........";
$result = array();
try {
$html_cun = @file_get_contents($url);
if (!$html_cun) {
throw new Exception('http_304');
}
} catch (Exception $e) {
echo ".........error...........\n";
if ($config['error_sleep_time']) {
sleep($config['error_sleep_time']);
}
return get_cun($url, $xiang);
}
preg_match_all($config['reg_cun']['step1'], $html_cun, $match_cun1);
if (count($match_cun1[0]) == 0) {
echo "...no cun...\n";
return $result;
}
$str_cun1 = $match_cun1[0][0];
preg_match_all($config['reg_cun']['step2'], $str_cun1, $match_cun2);
if (count($match_cun2[0]) == 0) {
die('cun match2 error');
}
foreach ($match_cun2[0] as $str_cun_temp) {
$str_cun3 = '</td>'.$str_cun_temp.'<td>';
$arr_cun3 = explode('</td><td>', $str_cun3);
if (count($arr_cun3) != 5) {
die($str_cun_temp.'^^^^^^ error3 ^^^^^^');
}
$result[] = array('pid' => $xiang['pid'], 'id' => $arr_cun3[1], 'name' => $arr_cun3[3], 'cid' => $xiang['cid'], 'xid' => $xiang['xid'], 'xgid' => $xiang['id'], 'type' => $arr_cun3[2]);
}
echo ".........end.............".count($result).".....\n";
return $result;
}
?><file_sep><?php
$dbname = 'test';
$conn = @new mysqli('127.0.0.1', 'root', 'root', $dbname, '3306');
$sql = "select table_name,table_comment from information_schema.tables where table_schema='$dbname' order by table_name";
$ispost = $_SERVER['REQUEST_METHOD'] == 'POST';
$posttablename = @$_POST['tablename'];
if (empty($posttablename)) {
$ispost = false;
} else if ($ispost && !empty($posttablename)) {
$sql = "select c.column_name as name,c.column_comment as `comment`,c.data_type as datatype,case when c.character_maximum_length is null then 0 else character_maximum_length end as length,case when c.is_nullable='YES' then 1 else 0 end as nullable,case when c.column_default is null then '' else column_default end as defaultvalue,case when c.column_key='PRI' then 1 else 0 end as isprimary, case when c.extra='auto_increment' then 1 else 0 end as autocreate,c.TABLE_NAME as tablename,t.table_comment as tablecomment from information_schema.COLUMNS c left join information_schema.tables t on c.table_name=t.table_name and c.table_schema=t.table_schema where c.TABLE_SCHEMA='$dbname' and c.TABLE_NAME in (select distinct table_name from information_schema.COLUMNS where TABLE_SCHEMA='$dbname') and c.table_name='$posttablename';";
}
$result = @mysqli_query($conn, $sql);
$data = array();
while ($tmp = @mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$data[] = $tmp;
}
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0,user-scalable=no">
<title>数据库表结构</title>
<style type="text/css">
td,th { width:220px;text-align: left;border:none; }
.mouseover { background-color: #ccc; }
</style>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function mouseover(o) {
$(o).addClass('mouseover');
}
function mouseout(o) {
$(o).removeClass('mouseover');
}
</script>
</head>
<body>
<form action="index.php" method="post">
<div style="height: 35px;position:fixed;background: #fff;top:0px;margin: 0px;width: 100%;padding: 10px 0px 0px 0px;">
<label for="tablename">tablename:</label>
<input type="text" name="tablename" id="tablename" value="<?php echo $posttablename;?>">
<input type="submit" value="select"/>
<hr>
</div>
</form>
<table rules=rows>
<tr style="height: 35px;position: fixed;background: #fff;top: 44px;margin: 0px; width: 100%;padding: 10px 0px 0px 0px;">
<?php if (!$ispost) { ?>
<th>tablename</th>
<th>comment</th>
<?php } else { ?>
<th>columnname</th>
<th>comment</th>
<th>datatype</th>
<th>length</th>
<th>nullable</th>
<th>defaultvalue</th>
<th>isprimary</th>
<th>autocreate</th>
<th>tablename</th>
<th>tablecomment</th>
<?php } ?>
</tr>
<tr style="height:80px;"></tr>
<?php foreach ($data as $item) { ?>
<tr onmouseover="mouseover(this)" onmouseout="mouseout(this)">
<?php foreach ($item as $value) { ?>
<td><?php echo $value; ?></td>
<?php } ?>
</tr>
<?php } ?>
</table>
</body>
</html>
|
280256244453da8e7a129dbf400dcd9c8f556581
|
[
"Markdown",
"PHP"
] | 5 |
PHP
|
idsyn/dbschema
|
ee9a8b8864fd3a4b5dfe7bbc6be4e3ec5daf9a15
|
8cd65f22a310bf73b1e58bfa82775120e5bc6322
|
refs/heads/master
|
<file_sep>import React from 'react';
import { Link, graphql } from 'gatsby';
import Img from 'gatsby-image';
import Theme from '../styles/Theme';
import { Container } from '../styles/styledComponent';
import Layout from '../components/layout';
import TextContent from '../components/textContent';
export const query = graphql`
query($slug: String!) {
contentfulBlogPost(slug: { eq: $slug }) {
title
publishedDate(fromNow: true)
featuredImage {
fluid(maxWidth: 1000) {
...GatsbyContentfulFluid_withWebp
}
}
bodyMd {
childMarkdownRemark {
html
}
}
tag
}
}
`;
const Post = (props) => {
// const options = {
// renderNode: {
// 'embedded-asset-block': (node) => {
// const alt = node.data.target.fields.title['en-US'];
// const url = node.data.target.fields.file['en-US'].url;
// return <img alt={alt} src={url} />;
// }
// }
// };
const title = props.data.contentfulBlogPost.title;
const publishedDate = props.data.contentfulBlogPost.publishedDate;
const bodyMD = props.data.contentfulBlogPost.bodyMd.childMarkdownRemark.html;
const tags = props.data.contentfulBlogPost.tag;
// const danger_dom = <div dangerouslySetInnerHTML={{ __html: bodyMD }} />;
// const dom = <div>{danger_dom}</div>;
return (
<Theme>
<Layout>
{props.data.contentfulBlogPost.featuredImage && (
<Img fluid={props.data.contentfulBlogPost.featuredImage.fluid} alt="" />
)}
<Container>
<h1>{title}</h1>
<div>{publishedDate}</div>
<ul>
{tags.map((tag, index) => {
return <li key={index}>{tag}</li>;
})}
</ul>
<TextContent content={bodyMD} />
<nav>
<ul>
<li>
{props.pageContext.previous && (
<Link to={`/blog/${props.pageContext.previous.slug}`} rel="prev">
prev
</Link>
)}
</li>
<li>
{props.pageContext.next && (
<Link to={`/blog/${props.pageContext.next.slug}`} rel="next">
next
</Link>
)}
</li>
</ul>
</nav>
</Container>
</Layout>
</Theme>
);
};
export default Post;
<file_sep>import React, { useState } from 'react';
import { InView } from 'react-intersection-observer';
import { graphql, useStaticQuery, Link } from 'gatsby';
import styled from 'styled-components';
import Theme from '../styles/Theme';
import Layout from '../components/layout';
import { Container } from '../styles/styledComponent';
import { WorksStyled } from '../styles/worksStyled';
const Anchor = styled(Link)`
display: block;
text-align: right;
padding-right: 4em;
`;
const SectionTitle = styled.h1`
position: fixed;
z-index: 999;
right: 10vw;
top: 10%;
text-align: right;
padding: 0;
margin: 0;
font-size: 4rem;
font-weight: 800;
opacity: 0;
transition: opacity 0.5s ease-in-out;
&.--inView {
opacity: 1;
}
&.--notInView {
opacity: 0;
}
`;
const Works = (props, inView) => {
const setInViewWorkTitle = (inView, entry) => {
if (!inView) {
setTimeout(() => {
setInViewEl(false);
}, 500);
} else {
setTimeout(() => {
setCurrentWork(entry.target.title);
setInViewEl(true);
}, 500);
}
console.log(entry);
};
const [ currentWork, setCurrentWork ] = useState('');
const [ inViewEl, setInViewEl ] = useState(false);
const data = useStaticQuery(graphql`
query {
allContentfulProject {
edges {
node {
title
slug
description
descriptionLong {
descriptionLong
}
body {
body
}
featuredImage {
file {
url
}
}
gallery {
file {
url
}
}
}
}
}
}
`);
// console.log('Inview:', inView, entry)
return (
<Theme>
<Layout>
<SectionTitle className={`${!inViewEl ? '--notInView' : '--inView'}`}>{currentWork} </SectionTitle>
<Container>
{data.allContentfulProject.edges.map((edge, index) => {
return (
<WorksStyled className={`${!inViewEl ? '--notInView' : '--inView'}`}>
<InView
key={index}
threshold="1"
title={edge.node.title}
onChange={setInViewWorkTitle}
/>
<div className="workText">
<h3>{edge.node.title}</h3>
{/* <p>{edge.node.descriptionLong.descriptionLong}</p> */}
<Anchor to={`/portfolio/${edge.node.slug}`}>go to project</Anchor>
</div>
<div className="workVisual">
{/* <img src={edge.node.featuredImage.file.url} alt="" /> */}
{edge.node.gallery ? ( //IF not empty
edge.node.gallery.map((img, index) => {
return <img key={index} src={img.file.url} alt={edge.node.title} />;
})
) : null}
</div>
<InView />
</WorksStyled>
);
})}
</Container>
</Layout>
</Theme>
);
};
export default Works;
<file_sep>import React from 'react';
import { graphql, useStaticQuery } from 'gatsby';
import Img from 'gatsby-image';
const Hero = () => {
const data = useStaticQuery(graphql`
query {
file(relativePath: { eq: "heroImage.jpg" }) {
childImageSharp {
fixed(width: 400, height: 250) {
...GatsbyImageSharpFixed
}
}
}
}
`);
return (
<section>
{/* {data.file.childImageSharp.fluid} */}
<Img fixed={data.file.childImageSharp.fixed} draggable={false} alt="This is a picture of my face." />
<div>
<h1>Hi, I like websites.</h1>
<p>Sometimes I make them.</p>
</div>
</section>
);
};
export default Hero;
<file_sep>import React from 'react';
import { StaticQuery, graphql } from 'gatsby';
import styled from 'styled-components';
import SinglePostInt from './singlePostInt';
import SinglePostExt from './singlePostExt';
const PostsSection = styled.section`
.postContainer {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
`;
export default () => (
<StaticQuery
query={graphql`
query {
allContentfulBlogPost(sort: { fields: publishedDate, order: DESC }) {
edges {
node {
title
link
slug
publishedDate(fromNow: true)
tag
featuredImage {
fluid(maxWidth: 600) {
...GatsbyContentfulFluid_withWebp
}
}
bodyMd {
childMarkdownRemark {
excerpt
html
}
}
}
}
}
}
`}
render={(data) => (
<>
<PostsSection>
<h2>
<span>in</span>sight
</h2>
<div className="postContainer">
{data.allContentfulBlogPost.edges.map((edge, index) => {
if (index < 9) {
let target, postProps;
edge.node.link ? (target = edge.node.link) : (target = `/blog/${edge.node.slug}`);
postProps = {
slug: `/blog/${edge.node.slug}`,
imgPost: edge.node.featuredImage.fluid.src,
externalLink: edge.node.link,
tags: edge.node.tag,
title: edge.node.title,
body: edge.node.bodyMd.childMarkdownRemark.html,
date: edge.node.publishedDate,
excerpt: edge.node.bodyMd.childMarkdownRemark.excerpt,
target: target
};
return !postProps.externalLink ? (
<SinglePostInt key={index} postProps={postProps} />
) : (
<SinglePostExt key={index} postProps={postProps} />
);
} else {
return null;
}
})}
</div>
</PostsSection>
</>
)}
/>
);
// const PostList = () => {
// const data = useStaticQuery(graphql`
// query {
// allContentfulBlogPost(sort: { fields: publishedDate, order: DESC }) {
// edges {
// node {
// title
// link
// slug
// publishedDate(fromNow: true)
// tag
// featuredImage {
// fluid(maxWidth: 600) {
// ...GatsbyContentfulFluid_withWebp
// }
// }
// bodyMd {
// childMarkdownRemark {
// excerpt
// html
// }
// }
// }
// }
// }
// }
// `);
// const PostsSection = styled.section`
// display: flex;
// flex-wrap: wrap;
// justify-content: space-between;
// `;
// return (
// <React.Fragment>
// <h2>
// <span>in</span>sight
// </h2>
// <PostsSection>
// {data.allContentfulBlogPost.edges.map((edge, index) => {
// if (index < 9) {
// let target, postProps;
// edge.node.link ? (target = edge.node.link) : (target = `/blog/${edge.node.slug}`);
// postProps = {
// slug: `/blog/${edge.node.slug}`,
// imgPost: edge.node.featuredImage.fluid.src,
// externalLink: edge.node.link,
// tags: edge.node.tag,
// title: edge.node.title,
// body: edge.node.bodyMd.childMarkdownRemark.html,
// date: edge.node.publishedDate,
// excerpt: edge.node.bodyMd.childMarkdownRemark.excerpt,
// target: target
// };
// return !postProps.externalLink ? (
// <SinglePostInt key={index} postProps={postProps} />
// ) : (
// <SinglePostExt key={index} postProps={postProps} />
// );
// } else {
// return null;
// }
// })}
// </PostsSection>
// </React.Fragment>
// );
// };
// export default PostList;
<file_sep>import React from 'react';
import styled from 'styled-components';
const Intro = () => {
const IntroSection = styled.section`
padding-top: 45vh;
position: relative;
.infos {
position: fixed;
left: 0.5em;
top: 84vh;
transform: rotate(-90deg);
transform-origin: left top 0;
font-size: 0.7rem;
display: block;
}
.avatar {
position: absolute;
right: 0;
top: 25vh;
width: 20vw;
}
p {
max-width: 45vw;
margin-top: 0.5em;
}
.underline {
display: inline-block;
color: ${(props) => props.theme.colors.primary};
/* border-bottom: 0.2em solid ${(props) => props.theme.colors.primary}; */
line-height: 0.5;
}
@media only screen and (max-width: 600px) {
padding-top: 55vh;
h1 {
font-size: 3.5rem;
letter-spacing: -3px;
}
h2 {
font-size: 2.5rem;
}
p {
max-width:90vw;
font-size: 0.95rem
}
.infos {
padding-top: 0;
position: static;
font-size: 0.8rem;
}
.underline {
background-position-y: calc(100% - 6px);
}
}
`;
return (
<IntroSection>
<span className="infos"><NAME> __ Product Manager</span>
<h1>
Solving<br /> problems <br />with <span className="underline">design </span>
</h1>
<p>
I love figuring out digital solutions to complex challenges and simplifying it to make a positive
impact.
</p>
<div className="avatar">{/* <Img fluid={data.avatar.childImageSharp.fluid} /> */}</div>
</IntroSection>
);
};
export default Intro;
<file_sep>import React from 'react';
import { graphql, useStaticQuery } from 'gatsby';
import styled from 'styled-components';
const Footer = () => {
const StyledFooter = styled.footer`
background: ${(props) => props.theme.colors.primary};
margin: 30vh auto 0 auto;
padding: 3em 20vw 0.5em 20vw;
color: #fff;
h2 {
font-size: 2.5rem;
font-weight: 800;
line-height: 1;
}
ul {
margin: 0;
margin-top: 1em;
list-style-type: none;
font-weight: 300;
font-size: 2rem;
li {
display: inline-block;
padding: 0.1em;
&:nth-child(-n + 2):after {
content: " /";
}
a {
color: inherit;
text-decoration: none;
transition: all 0.3s linear;
&:hover {
color: #222;
}
}
}
}
.credits {
margin: 0;
font-size: 0.65rem;
font-weight: bold;
padding-top: 4em;
}
@media only screen and (max-width: 600px) {
padding: 2em 1em;
h2 {
font-size: 2rem;
letter-spacing: -2px;
}
ul {
font-size: 1.3rem;
}
}
`;
const data = useStaticQuery(graphql`
query {
site {
siteMetadata {
title
author
}
}
}
`);
return (
<StyledFooter>
<h2>
Hey!<br />I'm always up for new challenge 💪
</h2>
<ul className="contatcs">
<li>
<a href="https://www.linkedin.com/in/stefanoperelli/" target="_blank" rel="noopener noreferrer">
Linkedin
</a>
</li>
<li>
<a href="https://www.instagram.com/ste.esse" target="_blank" rel="noopener noreferrer">
Instagram
</a>
</li>
<li>
<a href="mailto:<EMAIL>" target="_blank" rel="noopener noreferrer">
Mail
</a>
</li>
</ul>
<p className="credits">
{data.site.siteMetadata.title} . made with GatsbyJs & hosted on Netlify <br />
</p>
</StyledFooter>
);
};
export default Footer;
<file_sep>import React from 'react';
import { graphql } from 'gatsby';
import Img from 'gatsby-image';
import Theme from '../styles/Theme';
import { Container, ImageWrapper } from '../styles/styledComponent';
import Layout from '../components/layout';
import Head from '../components/head';
import Intro from '../components/intro';
import Timeline from '../components/timeline';
import Quote from '../components/quote';
import LastWorks from '../components/lastWorks';
import PostsList from '../components/postsList';
const IndexPage = (props) => {
return (
<Theme>
<Layout>
<Container>
<Head title="Home" />
<Intro />
<Quote />
<section className="knowhow">
<h2 className="align-right">
know<span>how</span>
</h2>
<p>
In every project is necessary to <span>listen</span> what people are saying and{' '}
<span>ask</span> the right questions. On <span>UX</span> side, I'm fluent with most areas
that the field offers, i love <span>minimal UI</span> and clean <span>typography</span>.
Thanks to my experience as <span>dev</span> and <span>creative</span>, i can understand both
creation sides of a digital product always keeping an eye on <span>business</span> and{' '}
<span>costs</span> specifics. In the small projects, i can <span>lead</span> all the entire
process without losing myself, with the big ones i can <span>manage</span> the project
throught <span>AGILE</span> or <span>LEAN</span> methodology cooperating closely with the
whole <span>team</span>.
</p>
</section>
<ImageWrapper sidePadding="15vw">
<Img fluid={props.data.intersection.childImageSharp.fluid} />
</ImageWrapper>
<section className="toolkit">
<h2>
tool<span>kit</span>
</h2>
<div className="content">
<p>
I have always tried to begin following a <span>content first</span> approach, so after
the contents have been clarified i open <span>Sketch</span> to give a primal shape to
the idea and to organize a sort of <span>mind map</span>. Once finally the idea has
achieved a satisfying shape i always googling to check if i can introducing some new
skill in my comfort zone or if it's better to hold off for a better time. Sometimes i’ve
used tools like <span>Adobe XD</span> or <span>Framer</span> to show some{' '}
<span>POC</span> to the customers. After this, as a supporter of <span>JAMStack</span>{' '}
architecture, i start with the tech side figuring out which <span>javascript</span>{' '}
library or framework is better to achieve the specific goal. I like the flexibility of{' '}
<span>React</span> and its whole ecosystem, <span>styled components</span> and the{' '}
<span>stylesheet</span> declinations (obviously <span>SCSS</span> remain the king), all
connected togheter by <span>headless API</span> with content managed through an{' '}
<span>headless CMS</span> and released as <span>responsive</span> products ready for
every touchpoint.
</p>
</div>
</section>
<ImageWrapper>
<Img className="cycle" fluid={props.data.cycle.childImageSharp.fluid} />
</ImageWrapper>
<Timeline />
{/* <PostsList /> */}
<LastWorks />
</Container>
</Layout>
</Theme>
);
};
export default IndexPage;
export const query = graphql`
query {
intersection: file(relativePath: { eq: "intersection.png" }) {
childImageSharp {
fluid(maxWidth: 900) {
...GatsbyImageSharpFluid
}
}
}
cycle: file(relativePath: { eq: "cycle.png" }) {
childImageSharp {
fluid(maxWidth: 900) {
...GatsbyImageSharpFluid
}
}
}
avatar: file(relativePath: { eq: "steperelli.jpeg" }) {
childImageSharp {
fluid(maxWidth: 500) {
...GatsbyImageSharpFluid
}
}
}
}
`;
<file_sep>import React from 'react';
import { Link } from 'gatsby';
import styled from 'styled-components';
const SinglePostInt = ({ postProps }) => {
const StyledLink = styled(Link)`
position: relative;
display: flex;
flex-flow: column;
padding: 0.5em;
width: calc(33% - 1em);
transition: all 0.3s linear;
text-decoration: none;
color: #111;
background: #222;
h2 {
color: #fff;
font-family: 'Oswald';
text-transform: uppercase;
margin: 0;
font-size: 1.5rem;
line-height: 1;
font-weight: 900;
transition: all 0.3s linear;
}
.date {
color: #fff;
text-align: right;
font-size: 0.6em;
padding-top: 1em;
transition: all 0.3s linear;
}
p {color: #fff;
font-size: 0.8em;
margin: 0;
margin-top: 0.5em;
padding-bottom: 2em;
}
.tags {
list-style-type: none;
margin: 0;
display: flex;
font-size: 0.6rem;
text-transform: uppercase;
font-weight: 800;
transition: all 0.4s linear;
li {
margin: 0;
margin-right: 10px;
color: ${(props) => props.theme.colors.primary};
}
}
&:hover {
background: ${(props) => props.theme.colors.primary};
h2,
span,
li {
color: #fff;
}
}
@media only screen and (max-width: 600px) {
width: 100%;
padding: 0;
h2 {
letter-spacing: -1px;
}
.by {
font-size: 0.8rem;
}
}
`;
const ImgPost = styled.div`
opacity: 0;
top: -120px;
right: -2vw;
position: absolute;
height: 150px;
width: 200px;
background: url(${(props) => props.background});
background-position: center center;
background-size: cover;
transition: all 0.4s ease-in;
border: 0.3em solid #fff;
${StyledLink}:hover & {
opacity: 1;
}
`;
return (
<StyledLink to={postProps.target}>
<ImgPost background={postProps.imgPost} />
<ul className="tags">
{postProps.tags.map((tag, index) => {
return <li key={index}>{tag}</li>;
})}
</ul>
<div className="flexed">
<h2>{postProps.title}</h2>
<span className="date">{postProps.date}</span>
</div>
{/* <p>{postProps.excerpt}</p> */}
</StyledLink>
);
};
export default SinglePostInt;
<file_sep>import React from 'react';
import { graphql, useStaticQuery } from 'gatsby';
import '../styles/index.scss';
// Searching for images to show and link to original size
const AboutPage = () => {
const data = useStaticQuery(graphql`
query {
allImageSharp {
edges {
node {
fluid(maxWidth: 1500, fit: CONTAIN) {
src
originalImg
}
}
}
}
}
`);
return (
<div>
{data.allImageSharp.edges.map((edge, index) => {
return (
<div className="fullWidth">
<a key={index} href={edge.node.fluid.originalImg}>
{' '}
<img src={edge.node.fluid.src} />
</a>
</div>
);
})}
</div>
);
};
export default AboutPage;
<file_sep>import React from 'react';
import { ThemeProvider } from 'styled-components';
const theme = {
colors: {
primary: '#fe003f',
red: '#fe003f',
yellow: '#fbff62',
green: '#62ffaa',
lightpurple: '#caafff',
water: '#2ee8b6',
softpink: '#ffdff1',
purple: '7505d8'
},
fonts: [ 'sans-serif', 'Roboto' ],
fontSizes: {
small: '1em',
medium: '2em',
large: '3em'
}
};
const Theme = ({ children }) => <ThemeProvider theme={theme}>{children}</ThemeProvider>;
export default Theme;
<file_sep>import React from 'react';
import { graphql, useStaticQuery, Link } from 'gatsby';
import styled from 'styled-components';
import { getRandomColor, Container, SectionTitle } from '../styles/styledComponent';
import { WorksStyled } from '../styles/worksStyled';
const Anchor = styled(Link)`
display: block;
text-align: right;
padding-right: 4em;
`;
const Works = (props) => {
const data = useStaticQuery(graphql`
query {
allContentfulProject {
edges {
node {
title
slug
description
descriptionLong {
descriptionLong
}
body {
body
}
featuredImage {
file {
url
}
}
gallery {
file {
url
}
}
}
}
}
}
`);
return (
<React.Fragment>
<SectionTitle>works </SectionTitle>
<Container>
{data.allContentfulProject.edges.map((edge, index) => {
return (
<WorksStyled key={index}>
<div className="workText">
<h3>{edge.node.title}</h3>
<p>{edge.node.descriptionLong.descriptionLong}</p>
<Anchor to={`/portfolio/${edge.node.slug}`}>go to project</Anchor>
</div>
<div className="workVisual">
{/* <img src={edge.node.featuredImage.file.url} alt="" /> */}
{edge.node.gallery ? ( //IF not empty
edge.node.gallery.map((img, index) => {
return <img key={index} src={img.file.url} />;
})
) : null}
</div>
</WorksStyled>
);
})}
</Container>
</React.Fragment>
);
};
export default Works;
<file_sep>import React from 'react';
import { Link, graphql, useStaticQuery } from 'gatsby';
import Img from 'gatsby-image';
import Theme from '../styles/Theme';
import { Container } from '../styles/styledComponent';
import Layout from '../components/layout';
import Head from '../components/head';
import styled from 'styled-components';
const PostList = styled.div`
padding-top: 20vh;
min-height: 100vh;
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
`;
const StyledLink = styled(Link)`
background: ${(props) => props.theme.colors.primary};
color: #fff;
/* color: #222; */
box-shadow: 10px 10px 50px -6px rgba(240,240,240,1);
text-decoration: none;
width: 48%;
margin: 1em 0;
.container {
padding: 2em 1em;
.tags {
list-style-type: none;
margin: 0;
display: flex;
font-size: 0.6rem;
text-transform: uppercase;
font-weight: 800;
li {
margin-right: 10px;
color: ${(props) => props.theme.colors.primary};;
background: #fff;
padding: 0.1em 0.5em;
}
}
p {
padding-bottom: 2em;
font-size: 0.9em;
}
}
h2 {
margin-top: 0.2em;
font-family: 'Montserrat';
text-transform: uppercase;
font-size: 1.8rem;
letter-spacing: -1px;
line-height: 0.9;
font-weight: 900;
}
`;
const BlogPage = () => {
const data = useStaticQuery(graphql`
query {
allContentfulBlogPost(sort: { fields: publishedDate, order: DESC }) {
edges {
node {
title
slug
publishedDate(fromNow: true)
tag
featuredImage {
fluid(maxWidth: 400) {
...GatsbyContentfulFluid_withWebp
}
}
bodyMd {
childMarkdownRemark {
excerpt
}
}
}
}
}
}
`);
return (
<Theme>
<Layout>
<Container>
<Head title="Words" />
{/* <Pagetitle title="Words" description="some description" /> */}
<PostList>
{data.allContentfulBlogPost.edges.map((edge, index) => {
return (
<StyledLink key={index} to={`/blog/${edge.node.slug}`}>
{/* <Img fluid={edge.node.featuredImage.fluid} /> */}
<div className="container">
<ul className="tags">
{edge.node.tag.map((tag, index) => {
return <li key={index}>{tag}</li>;
})}
</ul>
<h2>{edge.node.title}</h2>
<p>{edge.node.bodyMd.childMarkdownRemark.excerpt}</p>
<span>{edge.node.publishedDate}</span>
</div>
</StyledLink>
);
})}
</PostList>
</Container>
</Layout>
</Theme>
);
};
export default BlogPage;
<file_sep>import React from 'react';
import styled from 'styled-components';
const SinglePostExt = ({ postProps }) => {
const cleanUrl = (url) => {
let urlCleaned = url.replace(/^(?:https?:\/\/)?(?:www\.)?/i, '').split('/')[0];
return urlCleaned;
};
const StyledLink = styled.a`
position: relative;
display: flex;
flex-flow: column;
padding: 0.5em;
width: calc(33% - 1em);
transition: all 0.3s linear;
text-decoration: none;
color: #111;
.flexed {
flex-flow: column;
}
h2 {
font-family: 'Oswald';
text-transform: uppercase;
margin: 0;
font-size: 1.5rem;
letter-spacing: -2px;
line-height: 1;
font-weight: 900;
transition: all 0.3s linear;
}
.date {
text-align: right;
font-size: 0.6em;
padding-top: 1em;
transition: all 0.3s linear;
}
p {
font-size: 0.8em;
margin: 0;
margin-top: 0.5em;
padding-bottom: 2em;
}
.tags {
list-style-type: none;
margin: 0;
display: flex;
font-size: 0.6rem;
text-transform: uppercase;
font-weight: 800;
transition: all 0.4s linear;
li {
margin: 0;
margin-right: 10px;
color: ${(props) => props.theme.colors.primary};
}
}
.by {
font-size: 0.5em;
padding: 0.5em 0;
margin: 0;
span {
font-weight: 800;
}
}
.body {
font-size: 0.7em;
}
&:hover {
background: ${(props) => props.theme.colors.primary};
h2,
span,
li,
p {
color: #fff;
}
}
@media only screen and (max-width: 600px) {
width: 100%;
padding: 0;
h2 {
letter-spacing: -1px;
}
.by {
font-size: 0.8rem;
}
}
`;
// const ImgPost = styled.div`
// opacity: 0;
// top: -120px;
// right: -2vw;
// position: absolute;
// height: 150px;
// width: 200px;
// background: url(${(props) => props.background});
// background-position: center center;
// background-size: cover;
// transition: all 0.4s ease-in;
// border: 0.3em solid #fff;
// ${StyledLink}:hover & {
// opacity: 1;
// }
// `;
const ImgPost = styled.div`
opacity: 0;
top: 10vh;
right: 0;
position: fixed;
height: 250px;
width: 350px;
background: url(${(props) => props.background});
background-position: center center;
background-size: cover;
transition: all 0.4s ease-in;
z-index: -1;
${StyledLink}:hover & {
opacity: 1;
}
`;
return (
<StyledLink href={postProps.target}>
<ImgPost background={postProps.imgPost} />
<ul className="tags">
{postProps.tags.map((tag, index) => {
return <li key={index}>{tag}</li>;
})}
</ul>
<div className="flexed">
<h2>{postProps.title}</h2>
{/* <span className="date">{postProps.date}</span> */}
<p className="by">
by <span>{cleanUrl(postProps.target)}</span>
</p>
</div>
{/* <p className="body">{postProps.excerpt}</p> */}
</StyledLink>
);
};
export default SinglePostExt;
<file_sep>import React from 'react';
import { useStaticQuery } from 'gatsby';
import styled from 'styled-components';
const LastWorks = () => {
const data = useStaticQuery(graphql`
query {
allContentfulProject {
edges {
node {
title
slug
description
body {
body
}
featuredImage {
file {
url
}
}
gallery {
fluid {
src
}
}
}
}
}
}
`);
const WorksSection = styled.section`
position: relative;
min-height: 100vh;
ul {
margin: 0;
padding: 3em 0;
list-style-type: none;
display: flex;
flex-direction: column;
li {
display: block;
&:hover {
&:first-child .placeholder {
opacity: 0;
}
}
&:first-child .placeholder {
visibility: visible;
opacity: 1;
}
}
}
.hover-box {
text-align: right;
position: relative;
z-index: 3;
.title {
font-family: 'Oswald', sans-serif;
margin: 0;
text-transform: uppercase;
font-size: 3rem;
letter-spacing: -5px;
font-weight: 900;
line-height: 0.9;
pointer-events: auto;
cursor: pointer;
transition: all 0.3s linear;
}
.description {
opacity: 0;
font-weight: 300;
margin-right: 0;
margin-left: 30vw;
transition: all 0.3s linear;
line-height: 1;
height: 0;
padding-top: 0.5em;
}
&:hover {
.title {
color: ${(props) => props.theme.colors.primary};
}
.description {
opacity: 1;
height: 4em;
}
}
}
.hover-box:hover + .hover-image {
opacity: 1;
pointer-events: none;
}
.hover-image {
position: absolute;
max-width: 80%;
opacity: 0;
z-index: 2;
top: 10vw;
left: -20vw;
bottom: 0;
pointer-events: none;
text-align: right;
transition: all 0.3s ease-in;
}
.hover-image img {
max-width: 100% !important;
max-height: 100% !important;
width: auto !important;
height: auto !important;
margin-bottom: 0;
}
@media only screen and (max-width: 600px) {
min-height: 0;
ul {
padding: 0;
li {
margin-bottom: 0;
}
}
.hover-box {
.title {
font-size: 2rem;
letter-spacing: -3px;
}
.description {
padding-top: 0;
margin-left: 0;
}
&:hover {
.description {
height: 3em;
}
}
}
.hover-image {
display: none;
}
}
`;
return (
<WorksSection>
<h2>
last<span>works</span>
</h2>
<ul>
{data.allContentfulProject.edges.map((edge, index) => {
return (
<li key={index}>
<div className="hover-box">
<div className="title">{edge.node.title}</div>
<div className="description">{edge.node.description}</div>
</div>
<div className="hover-image">
<img src={edge.node.featuredImage.file.url} alt="" />
</div>
</li>
);
})}
</ul>
</WorksSection>
);
};
export default LastWorks;
<file_sep>const path = require('path');
module.exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions;
const blogTemplate = path.resolve('./src/templates/post.js');
const projectTemplate = path.resolve('./src/templates/project.js');
const res = await graphql(`
query {
allContentfulBlogPost {
edges {
node {
slug
}
}
}
allContentfulProject {
edges {
node {
slug
}
}
}
}
`);
const posts = res.data.allContentfulBlogPost.edges;
posts.forEach((edge, index) => {
const previous = index === posts.length - 1 ? null : posts[index + 1].node;
const next = index === 0 ? null : posts[index - 1].node;
createPage({
component: blogTemplate,
path: `/blog/${edge.node.slug}`,
context: {
slug: edge.node.slug,
next,
previous
}
});
});
const projects = res.data.allContentfulProject.edges;
projects.forEach((edge, index) => {
const previous = index === projects.length - 1 ? null : projects[index + 1].node;
const next = index === 0 ? null : projects[index - 1].node;
createPage({
component: projectTemplate,
path: `/portfolio/${edge.node.slug}`,
context: {
slug: edge.node.slug,
next,
previous
}
});
});
};
<file_sep>import React from 'react';
import { Link, graphql, useStaticQuery } from 'gatsby';
import Theme from '../styles/Theme';
import { Container } from '../styles/styledComponent';
import Layout from '../components/layout';
import Head from '../components/head';
import styled from 'styled-components';
import Pagetitle from '../components/pageTitle';
const PostList = styled.div`
margin-top: 10vh;
display: grid;
grid-gap: 2vw;
grid-template-columns:repeat(auto-fit,minmax(22vw,1fr));
/* grid-auto-rows: 20vw;
grid-auto-flow: dense; */
`;
const Post = styled(Link)`
position: relative;
display: flex;
flex-flow: column;
transition: all 0.2s linear;
margin: 0.5em 0;
box-shadow: 0px 1px 35px 0px rgba(0, 0, 0, 0.3);
.date {
position: absolute;
padding: 0.2em 0.4em;
background: ${(props) => props.theme.colors.primary};
text-transform: uppercase;
color: #fff;
right: 0;
font-size: 0.5em;
}
.content {
width: 100%;
padding: 0.6em 1em;
.tags {
list-style-type: none;
margin: 0;
display: flex;
font-size: 0.6rem;
text-transform: uppercase;
font-weight: 800;
li {
margin-right: 10px;
color: ${(props) => props.theme.colors.primary};
}
}
h2 {
font-family: 'Oswald';
text-transform: uppercase;
margin: 0.25em 0;
font-size: 1.2rem;
letter-spacing: -1px;
line-height: 0.95;
font-weight: 900;
transition: all 0.4s linear;
}
p {
font-size: 0.7rem;
padding-bottom: 1em;
margin: 0;
}
}
&:hover {
transform: scale(1.05);
}
@media only screen and (max-width: 600px) {
width: 100%;
padding: 0;
min-height: 0;
h2 {
font-size: 2.8rem;
letter-spacing: -3px;
}
p,
a,
li,
.date {
font-size: 1rem;
}
&:hover {
box-shadow: none;
h2,
a {
color: ${(props) => props.theme.colors.primary};
}
}
}
`;
const ImgPost = styled.div`
height: 200px;
width: 100%;
background: url(${(props) => props.background});
background-position: center center;
background-size: cover;
`;
const BlogPage = () => {
const data = useStaticQuery(graphql`
query {
allContentfulBlogPost(sort: { fields: publishedDate, order: DESC }) {
edges {
node {
title
slug
publishedDate(fromNow: true)
tag
featuredImage {
fluid(maxWidth: 400) {
...GatsbyContentfulFluid_withWebp
}
}
bodyMd {
childMarkdownRemark {
excerpt
}
}
}
}
}
}
`);
return (
<Theme>
<Layout>
<Container>
<Head title="Words" />
<Pagetitle title="Words" description="Stories from the web and stories written by me" />
<PostList>
{data.allContentfulBlogPost.edges.map((edge, index) => {
return (
<Post to={`/blog/${edge.node.slug}`}>
<div className="thumb">
<span className="date">{edge.node.publishedDate}</span>
<ImgPost background={edge.node.featuredImage.fluid.src} />
</div>
<div className="content">
<ul className="tags">
{edge.node.tag.map((tag, index) => {
return <li key={index}>{tag}</li>;
})}
</ul>
<h2>{edge.node.title}</h2>
<p>{edge.node.bodyMd.childMarkdownRemark.excerpt}</p>
</div>
</Post>
);
})}
</PostList>
</Container>
</Layout>
</Theme>
);
};
export default BlogPage;
<file_sep>import React from 'react';
import { Link, graphql } from 'gatsby';
import { documentToReactComponents } from '@contentful/rich-text-react-renderer';
import Theme from '../styles/Theme';
import Layout from '../components/layout';
export const query = graphql`
query($slug: String!) {
contentfulProject(slug: { eq: $slug }) {
title
description
body {
json
}
featuredImage {
file {
url
}
}
}
}
`;
const Project = (props) => {
const options = {
renderNode: {
'embedded-asset-block': (node) => {
const alt = node.data.target.fields.title['en-US'];
const url = node.data.target.fields.file['en-US'].url;
return <img alt={alt} src={url} />;
}
}
};
const title = props.data.contentfulProject.title;
const bodyPost = documentToReactComponents(props.data.contentfulProject.body.json, options);
return (
<Theme>
<Layout>
{/* if != null (in some post the featured images isnt defined) */}
{props.data.contentfulProject.featuredImage && (
<img src={props.data.contentfulProject.featuredImage.file.url} alt="" />
)}
<h1>{title}</h1>
{/* <div>{publishedDate}</div> */}
<div className="bodyPost">{bodyPost}</div>
<nav>
<ul>
<li>
{props.pageContext.previous && (
<Link to={`/portfolio/${props.pageContext.previous.slug}`} rel="prev">
{`Go to ${props.pageContext.previous.slug}`}
</Link>
)}
</li>
<li>
{props.pageContext.next && (
<Link to={`/portfolio/${props.pageContext.next.slug}`} rel="next">
{`Go to ${props.pageContext.next.slug}`}
</Link>
)}
</li>
</ul>
</nav>
</Layout>
</Theme>
);
};
export default Project;
<file_sep>import React from 'react';
import { graphql, useStaticQuery, Link } from 'gatsby';
import vector from '../images/vector.svg';
import styled from 'styled-components';
import { Container } from '../styles/styledComponent';
const Grid = styled.div`
padding: 4em;
display: flex;
max-width: none;
flex-wrap: wrap;
justify-content: space-between;
`;
const GridBox = styled.div`
position: relative;
padding: 0;
display: flex;
width: 45%;
height: 300px;
margin: 3em 0;
justify-content: center;
`;
const getRandomColor = () => {
return `hsla(${360 * Math.random()},70%,80%,1)`;
};
const GridBoxHovering = styled.div`
position: absolute;
left: 0%;
top: 0%;
right: 0%;
bottom: 0%;
z-index: auto;
/* background-image: url(https://uploads-ssl.webflow.com/5ca06830f4c36e4b847dd28d/5d5c71e48ebd510807f1a2f1_Vector1.png); */
mask: url(${vector});
mask-size: contain;
mask-repeat: no-repeat;
mask-position: center;
background: ${getRandomColor};
transition: transform 400ms ease, opacity 300ms ease;
opacity: 0;
/* ${GridBox}:hover & {
transform: rotate(50deg);
opacity: 1;
} */
`;
const GridBoxDescription = styled.p`
position: absolute;
top: 50%;
right: 0%;
bottom: 0%;
width: 100%;
font-weight: 800;
text-align: center;
transition: opacity 200ms ease;
opacity: 0;
${GridBox}:hover & {
opacity: 1;
}
`;
const Anchor = styled(Link)`
position: relative;
z-index: 999;
display: block;
width: 100%;
height: 100%;
box-shadow: 0 2.8px 2.2px rgba(0, 0, 0, 0.034),0 6.7px 5.3px rgba(0, 0, 0, 0.048),0 12.5px 10px rgba(0, 0, 0, 0.06), 0 22.3px 17.9px rgba(0, 0, 0, 0.072), 0 41.8px 33.4px rgba(0, 0, 0, 0.086), 0 100px 80px rgba(0, 0, 0, 0.12);
background-image: url(${(props) => props.img});
background-size: cover;
background-repeat: no-repeat;
transition: all 600ms ease-in-out;
opacity: 1;
${GridBox}:hover & {
/* opacity: 0; */
transform: translate(10px,-10px)
}
`;
const Portfolio = (props) => {
const data = useStaticQuery(graphql`
query {
allContentfulProject {
edges {
node {
title
slug
description
body {
body
}
featuredImage {
file {
url
}
}
gallery {
fluid {
src
}
}
}
}
}
}
`);
return (
<Container fullwidth>
<Grid>
{data.allContentfulProject.edges.map((edge, index) => {
return (
<GridBox key={index}>
<GridBoxHovering />
<GridBoxDescription>{edge.node.description}</GridBoxDescription>
{/* <img src={edge.node.featuredImage.fluid.src} alt="" />
<h1>{edge.node.project}</h1>
<p>{edge.node.description.description}</p> */}
{/* <h2>Gallery</h2>
{edge.node.gallery.map((img, index) => {
return <img key={index} src={img.fluid.src} alt="" />;
})} */}
<Anchor to={`/portfolio/${edge.node.slug}`} img={edge.node.featuredImage.file.url} />
</GridBox>
);
})}
</Grid>
</Container>
);
};
export default Portfolio;
<file_sep>/**
* Configure your Gatsby site with this file.
*
* See: https://www.gatsbyjs.org/docs/gatsby-config/
*/
const path = require('path');
module.exports = {
siteMetadata: {
title: 'stefanoperelli.com',
author: '<NAME>'
},
plugins: [
{
resolve: `gatsby-plugin-manifest`,
options: {
name: 'SP',
short_name: 'SP',
start_url: '/',
background_color: '#fff',
theme_color: '#000',
// Enables "Add to Homescreen" prompt and disables browser UI (including back button)
// see https://developers.google.com/web/fundamentals/web-app-manifest/#display
display: 'standalone',
icon: 'src/images/icon.png', // This path is relative to the root of the site.
// An optional attribute which provides support for CORS check.
// If you do not provide a crossOrigin option, it will skip CORS for manifest.
// Any invalid keyword or empty string defaults to `anonymous`
crossOrigin: `use-credentials`
}
},
{
resolve: `gatsby-plugin-google-fonts`,
options: {
fonts: [ `Muli\:300,400,700,900`, `Oswald\:300,400,700` ],
display: 'swap'
}
},
`gatsby-plugin-styled-components`,
'gatsby-plugin-react-helmet',
{
resolve: 'gatsby-source-contentful',
options: {
spaceId: process.env.CONTENTFUL_SPACE_ID,
accessToken: process.env.CONTENTFUL_ACCESS_TOKEN
}
},
'gatsby-plugin-sass',
{
resolve: 'gatsby-source-filesystem',
options: {
name: 'images',
// path: `${__dirname}/src`
path: path.join(__dirname, `src`, `images`)
}
},
`gatsby-plugin-sharp`,
`gatsby-transformer-sharp`,
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [
{
resolve: `gatsby-remark-prismjs`,
options: {
classPrefix: 'language-',
inlineCodeMarker: true,
aliases: {},
showLineNumbers: false,
noInlineHighlight: false
}
}
]
}
}
]
};
<file_sep>import React from 'react';
import styled from 'styled-components';
const Content = styled.div`
.gatsby-highlight {
margin: 4rem 0;
font-size: 0.7em;
pre {
font-size: 0.7rem;
margin-bottom: 2rem;
}
span.parameter {
font-family: Consolas, Courier New, monospace;
}
}
ul {
list-style: none;
margin-bottom: 2rem;
li {
position: relative;
margin-bottom: 0.8rem;
&:before {
content: '';
position: absolute;
height: 8px;
width: 2px;
top: 0.9rem;
left: -1.5rem;
z-index: 5;
}
&:after {
content: '';
position: absolute;
height: 8px;
width: 2px;
top: 0.9rem;
left: -1.5rem;
z-index: 5;
transform: rotate(90deg);
}
}
}
`;
export default function TextContent({ content }) {
return (
<Content
dangerouslySetInnerHTML={{
__html: content
}}
/>
);
}
<file_sep>import React from 'react';
import styled from 'styled-components';
const Quote = () => {
const QuoteSection = styled.section`
margin-top: 5em;
padding: 2em 1em;
color: #222;
@media only screen and (max-width: 600px) {
margin-top: 0;
}
p {
border-left: 0.2em solid ${(props) => props.theme.colors.primary};
font-family: 'Playfair Display';
font-size: 2rem;
line-height: 1.2;
padding: 1em;
font-weight: 900;
margin: 0;
@media only screen and (max-width: 600px) {
font-size: 1.5rem;
}
span {
font-weight: 300;
font-family: 'Muli';
background: none;
display: block;
font-size: 1rem;
margin-top: 2em;
color: #222;
}
}
`;
return (
<QuoteSection>
<div className="content">
<p>
I never design a building before I've seen the site and met the people who will be using it.
<span><NAME></span>
</p>
</div>
</QuoteSection>
);
};
export default Quote;
<file_sep>import React from "react"
import styled from "styled-components"
const Timeline = () => {
const history = [
{
year: "Present",
role: "Senior Product Manager",
company: "Mangrovia Blockchain Solutions",
},
{
year: "2023",
role: "Product Manager",
company: "FiscoZen",
},
{
year: "2020",
role: "Product Designer",
company: "PAX Italia",
},
{
year: "2018",
role: "UX Designer",
company: "PAX Italia",
},
{
year: "2016",
role: "Fullstack Designer",
company: "Digital Entity - NTTDATA",
},
{
year: "2013",
role: "Frontend Developer",
company: "Digital Entity - NTTDATA",
},
{
year: "2012",
role: "Owner",
company: "skillybiz.com",
},
{
year: "2009",
role: "Web Designer",
company: "Freelance",
},
]
const TimelineSection = styled.section`
.entriesWrapper {
position: relative;
min-height: 80vh;
margin: 0;
overflow: hidden;
&:before {
content: "";
position: absolute;
top: 0;
left: 19px;
bottom: 0px;
width: 4px;
background-color: #000;
@media only screen and (min-width: 700px) {
left: 50%;
}
}
.entries {
width: calc(100% - 80px);
max-width: 800px;
margin: auto;
position: relative;
left: -5px;
@media only screen and (min-width: 700px) {
overflow: hidden;
}
.entry {
width: 100%;
float: right;
padding: 40px 20px;
clear: both;
text-align: left;
&:not(:first-child) {
margin-top: -60px;
}
&:first-child {
.title:before {
content: "";
position: absolute;
background: ${props => props.theme.colors.primary};
border: 4px solid #000;
}
}
@media only screen and (min-width: 700px) {
width: calc(50% - 80px);
}
.title {
font-size: 0.7rem;
color: #a9a9a9;
line-height: 0.8;
position: relative;
&:before {
content: "";
position: absolute;
width: 25px;
height: 25px;
border: 4px solid ${props => props.theme.colors.primary};
background-color: #fff;
border-radius: 100%;
top: 2em;
transform: translateY(-50%);
right: calc(100% + 22px);
z-index: 1000;
@media only screen and (min-width: 700px) {
right: calc(100% + 81px);
}
}
}
.body {
p {
font-size: 1rem;
font-weight: 800;
margin: 0.2em 0;
span {
display: block;
font-size: 0.9rem;
font-weight: 300;
line-height: 0.9;
}
}
}
&:nth-child(2n) {
@media only screen and (min-width: 700px) {
text-align: right;
float: left;
.title {
&:before {
left: calc(100% + 94px);
}
&.big:before {
transform: translate(-8px, -50%);
}
}
}
}
}
}
}
`
return (
<TimelineSection>
<h2 className="align-right">
<span>hi</span>story
</h2>
<div className="entriesWrapper">
<div className="entries">
{history.map((job, index) => {
return (
<div key={index} className="entry">
<div className="title">{job.year}</div>
<div className="body">
<p>
{job.role}
<span>{job.company}</span>
</p>
</div>
</div>
)
})}
</div>
</div>
</TimelineSection>
)
}
export default Timeline
|
0dccbfb7beb61ccc7d38e540526950465f639d1d
|
[
"JavaScript"
] | 22 |
JavaScript
|
devbewill/site2020
|
4ae40bcfb817cec4a476bb1240dc272e72992274
|
621d0e08fa4c6b8250631a61df0d770679445220
|
refs/heads/master
|
<file_sep>package com.panda;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
/**
* 启动程序
*
* @author panda
*/
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
@MapperScan("com.panda.project.*.*.mapper")
public class PandaApplication
{
public static void main(String[] args)
{
// System.setProperty("spring.devtools.restart.enabled", "false");
SpringApplication.run(PandaApplication.class, args);
System.out.println("(♥◠‿◠)ノ゙ Panda启动成功 ლ(´ڡ`ლ)゙ \n" +
" 疯狂源于梦想 \n" +
" 技术成就辉煌 \n" +
" E学习 更快乐 \n" +
" http://dev.ehongqi.cn:8080/PandaFrame \n" +
"-------------------------------------- ");
}
}<file_sep>## 平台简介
一直想做一款后台管理系统,看了很多优秀的开源项目但是发现没有合适的。于是利用空闲休息时间开始自己写了一套后台系统。如此有了熊猫。她可以用于所有的Web应用程序,如网站管理后台,网站会员中心,CMS,CRM,OA。所有前端后台代码封装过后十分精简易上手,出错概率低。同时支持移动客户端访问。系统会陆续更新一些实用功能。
你若不离不弃,我必生死相依
PandaFrame
>PandaFrame从3.0开始,进行模块拆分,将原先的单应用转变为多模块,如需多模块 请购买另外的分布式开发版本
> 推荐使用阿里云部署,通用云产品代金券 :[点我领取](https://promotion.aliyun.com/ntms/yunparter/invite.html?userCode=brki8iof)
## 内置功能
1. 用户管理:用户是系统操作者,该功能主要完成系统用户配置。
2. 部门管理:配置系统组织机构(公司、部门、小组),树结构展现支持数据权限。
3. 岗位管理:配置系统用户所属担任职务。
4. 菜单管理:配置系统菜单,操作权限,按钮权限标识等。
5. 角色管理:角色菜单权限分配、设置角色按机构进行数据范围权限划分。
6. 字典管理:对系统中经常使用的一些较为固定的数据进行维护。
7. 参数管理:对系统动态配置常用参数。
8. 通知公告:系统通知公告信息发布维护。
9. 操作日志:系统正常操作日志记录和查询;系统异常信息日志记录和查询。
10. 登录日志:系统登录日志记录查询包含登录异常。
11. 在线用户:当前系统中活跃用户状态监控。
12. 定时任务:在线(添加、修改、删除)任务调度包含执行结果日志。
13. 代码生成:前后端代码的生成(java、html、xml、sql)支持CRUD下载 。
14. 系统接口:根据业务代码自动生成相关的api接口文档。
15. 在线构建器:拖动表单元素生成相应的HTML代码。
16. 连接池监视:监视当期系统数据库连接池状态,可进行分析SQL找出系统性能瓶颈。
## 在线体验
> admin/admin123
演示地址:http://dev.ehongqi.cn:8080/PandaFrame
## 声明
本产品已申请著作权,禁止倒卖本系统源码,未经本人同意授权倒卖本产品,一经发现产生的一切法律纠纷由倒卖者负责,
你可以学习,和二次开发做内部系统使用。
禁止使用本产品做违反国家法律任何一切活动,如果违反,产生的一切后果和本人开发者没有任何关系。
请知悉。
目前在开发微服务系统,敬请关注
http://www.ehongqi.cn
|
1127dc053f5a00c7c59553b9104735514e94c8a2
|
[
"Markdown",
"Java"
] | 2 |
Java
|
196712yuxin/RuoYi
|
ec9740ec1617e26b9f2ff475fd4bce37208f6f02
|
ad59151cf59e3b8da6ed256a511b6c556476b2cd
|
refs/heads/main
|
<repo_name>lwmqwer/easy-learn-kubescheduler<file_sep>/Chapter1/README.md
# Communicate with the kubernetes cluster
Ok, Let schedule a pod. Wait, what pod should we to schedule and where to schedule. Looks like we lack many inputs. Where can we get them and How?
Sure, these inputs must be in the kubernetes cluster, but how cloud we get from it. This a good question and let see how to get these inputs.
Let up setup a kubernetes cluster for our test, there many guide in the internet to help you to set one.
[Bootstrapping clusters with kubeadm](https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/)
You may face up some problems for this guide to setup the cluster due to pull images from k8s.gcr.io failure. Here is a [script](pull_images.sh) for user to pull it from a mirror and rename it. You need change the version compliant with your kubeadm. This script is for kubernetes v1.20.2. You also can change the mirror to the one fastest in your area. You would better setup a CNI plugin for network, but it is fine without it.
In our whole tutorial, one control node is enough.
## List pods
We can write our first scheduler to get pod information. The full code is here [scheduer.go](scheduler.go). We need a kubeconfig to be authorized by the cluster, we just copy the default scheduler one. The output should like this
```
# sudo cp /etc/kubernetes/scheduler.conf ~
# go run scheduler.go ~/scheduler.conf
add event for pod kube-system/etcd-test
add event for pod kube-system/kube-proxy-khkvc
add event for pod kube-system/coredns-74ff55c5b-8pvsn
add event for pod kube-system/coredns-74ff55c5b-f4sdn
add event for pod kube-system/kube-controller-manager-test
add event for pod kube-system/kube-scheduler-test
add event for pod kube-system/kube-apiserver-test
```
Great, we now could see all the pods in the cluster. The next step is to schedule it. But before that, let see dive more on this. Let us see the snippet of code of our first scheduler.
```
...
informerfactory := NewInformerFactory(client, 0)
informerfactory.Core().V1().Pods().Lister()
// Start all informers.
informerfactory.Start(ctx.Done())
// Wait for all caches to sync before scheduling.
informerfactory.WaitForCacheSync(ctx.Done())
informerfactory.Core().V1().Pods().Informer().AddEventHandler(
cache.ResourceEventHandlerFuncs{
AddFunc: addPod,
},
)
...
```
## List and watch (informer)
What is the informerfactory and what is the meaning of lister and informer?
Recall the component of kubernetes, the control plane includes the kube-apiserver, kube-controller, kube-scheduler, etcd etc. Now you can guess all the communication with the cluster is through kube-apiserver. We ask the kube-apiserver to get the things we want or tell others what we want(we will learn this in later chapter).
However, this does not answer the previous question. The centralized configuration would dismiss many inconsistency problems in a distribute system. But every time to query the configuration is a heavy burden for the database(api server and etcd). Store a local cache and only watch the increment change could greatly save the cost. This is the so-called list-and-watch mechanism.
The list and watch mechanism was already widely used by the kube-controller and kube-scheduler. And they had abstracted it out as tool for deverloper to extend the kubernetes management. Here we employ the client-go SDK to communicate with the cluster. This SDK hides the details of cache and authorization. For our purpose, this is enough to implement a scheduler.
Let have a look on the client-go SDK, we see most of the code is generated(What?).
```
//k8s.io/[email protected]/informers/core/v1/interface.go
...
// Code generated by informer-gen. DO NOT EDIT.
package v1
import (
internalinterfaces "k8s.io/client-go/informers/internalinterfaces"
)
// Interface provides access to all the informers in this group version.
type Interface interface {
// ComponentStatuses returns a ComponentStatusInformer.
ComponentStatuses() ComponentStatusInformer
// ConfigMaps returns a ConfigMapInformer.
ConfigMaps() ConfigMapInformer
// Endpoints returns a EndpointsInformer.
Endpoints() EndpointsInformer
// Events returns a EventInformer.
Events() EventInformer
// LimitRanges returns a LimitRangeInformer.
...
```
## Custom Resource definition(CRD)
Definition and updating API is a nuisance for manage plane. The kubenetes employ the CRD to solving this, once define the resouce we can easily generate the list and watch style api and SDKs. The more detail could find here [custom-resources](https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/) and [deep-dive-code-generation-customresources](https://www.openshift.com/blog/kubernetes-deep-dive-code-generation-customresources)<file_sep>/Chapter1/pull_images.sh
#!/bin/sh
# Copyright 2020 <NAME> (<EMAIL>)
#
# 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.
mirror="registry.aliyuncs.com/google_containers"
kubernetes_version=v1.20.2
pause_version=3.2
etcd_version=3.4.13-0
coredns_version=1.7.0
sudo docker pull $mirror/kube-apiserver:$kubernetes_version
sudo docker pull $mirror/kube-controller-manager:$kubernetes_version
sudo docker pull $mirror/kube-scheduler:$kubernetes_version
sudo docker pull $mirror/kube-proxy:$kubernetes_version
sudo docker pull $mirror/pause:$pause_version
sudo docker pull $mirror/etcd:$etcd_version
sudo docker pull $mirror/coredns:$coredns_version
sudo docker tag $mirror/kube-apiserver:$kubernetes_version k8s.gcr.io/kube-apiserver:$kubernetes_version
sudo docker tag $mirror/kube-controller-manager:$kubernetes_version k8s.gcr.io/kube-controller-manager:$kubernetes_version
sudo docker tag $mirror/kube-scheduler:$kubernetes_version k8s.gcr.io/kube-scheduler:$kubernetes_version
sudo docker tag $mirror/kube-proxy:$kubernetes_version k8s.gcr.io/kube-proxy:$kubernetes_version
sudo docker tag $mirror/pause:$pause_version k8s.gcr.io/pause:$pause_version
sudo docker tag $mirror/etcd:$etcd_version k8s.gcr.io/etcd:$etcd_version
sudo docker tag $mirror/coredns:$coredns_version k8s.gcr.io/coredns:$coredns_version
sudo docker rmi $mirror/kube-apiserver:$kubernetes_version
sudo docker rmi $mirror/kube-controller-manager:$kubernetes_version
sudo docker rmi $mirror/kube-scheduler:$kubernetes_version
sudo docker rmi $mirror/kube-proxy:$kubernetes_version
sudo docker rmi $mirror/pause:$pause_version
sudo docker rmi $mirror/etcd:$etcd_version
sudo docker rmi $mirror/coredns:$coredns_version<file_sep>/Chapter1/scheduler.go
/*
Copyright 2021 <NAME> (<EMAIL>)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"context"
"fmt"
"os"
v1 "k8s.io/api/core/v1"
"k8s.io/client-go/informers"
clientset "k8s.io/client-go/kubernetes"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/clientcmd"
)
func addPod(obj interface{}) {
pod := obj.(*v1.Pod)
fmt.Printf("add event for pod %s/%s\n", pod.Namespace, pod.Name)
}
func main() {
// Prepare for informerfactory
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if len(os.Args) <= 1 || len(os.Args[1]) == 0 {
panic("No --kubeconfig was specified. Using default API client. This might not work")
}
// This creates a client, load kubeconfig
kubeConfig, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
&clientcmd.ClientConfigLoadingRules{ExplicitPath: os.Args[1]}, nil).ClientConfig()
if err != nil {
os.Exit(-1)
}
client, err := clientset.NewForConfig(restclient.AddUserAgent(kubeConfig, "scheduler"))
if err != nil {
os.Exit(-1)
}
informerfactory := informers.NewSharedInformerFactory(client, 0)
// Here we only care about pods.
informerfactory.Core().V1().Pods().Lister()
// Start all informers.
informerfactory.Start(ctx.Done())
// Wait for all caches to sync before scheduling.
informerfactory.WaitForCacheSync(ctx.Done())
// Add event handle for add pod
informerfactory.Core().V1().Pods().Informer().AddEventHandler(
cache.ResourceEventHandlerFuncs{
AddFunc: addPod,
},
)
for {
}
}
<file_sep>/go.mod
module github.com/lwmqwer/easy-learn-kubescheduler
go 1.16
require (
k8s.io/api v0.20.0
k8s.io/client-go v0.20.0
)
<file_sep>/Chapter2/README.md
# Schedule a pod and notice the cluster
## List and filter resource we are interesting in
Now we can communicate with the cluster by the help of client SDK. Let us move on, to complete our scheduler. For the simplest case, the pod and node are the minimum information we need to schedule. Let us add some code to query them from the cluster. However, other than the node, not all the pod we are interested in, right? We can use a filter to filter out these that need to schedule and these need schedule by our scheduler. Thanks to client SDK again, they had already provided such interface.
```
...
// interestedPod selects pods that are assigned (scheduled and running).
func interestedPod(pod *v1.Pod) bool {
return pod.Spec.SchedulerName == SchedulerName && len(pod.Spec.NodeName) == 0
}
...
informerfactory.Core().V1().Pods().Informer().AddEventHandler(
cache.FilteringResourceEventHandler{
FilterFunc: func(obj interface{}) bool {
switch t := obj.(type) {
case *v1.Pod:
return !interestedPod(t)
case cache.DeletedFinalStateUnknown:
if pod, ok := t.Obj.(*v1.Pod); ok {
return !interestedPod(pod)
}
fmt.Errorf("unable to convert object %T to *v1.Pod", obj)
return false
default:
fmt.Errorf("unable to handle object in %T", obj)
return false
}
},
Handler: cache.ResourceEventHandlerFuncs{
AddFunc: addPod,
},
},
)
informerfactory.Core().V1().Nodes().Informer().AddEventHandler(
cache.ResourceEventHandlerFuncs{
AddFunc: addNode,
},
)
```
Question:
Could you list resource as possible as you can that a scheduler may interest in?
Extending reading: addAllEventHandlers is the function that kube-scheduler adds events to watch on resouces. The source code is here: [The resource that kube scheduler list and watch](https://github.com/kubernetes/kubernetes/blob/master/pkg/scheduler/eventhandlers.go)
```
...
// addAllEventHandlers is a helper function used in tests and in Scheduler
// to add event handlers for various informers.
func addAllEventHandlers(
sched *Scheduler,
informerFactory informers.SharedInformerFactory,
) {
// scheduled pod cache
informerFactory.Core().V1().Pods().Informer().AddEventHandler(
cache.FilteringResourceEventHandler{
...
```
Questions:
1. For a great number of pod and nodes, how should we store them, and which form of data struct to use?
[Scheduler cache](https://github.com/kubernetes/kubernetes/blob/master/pkg/scheduler/internal/cache/interface.go)
2. Should we schedule the pod based on first in first out? Could you suggest a more reasonable way?
[Priority queue](https://github.com/kubernetes/kubernetes/blob/master/pkg/scheduler/internal/queue/scheduling_queue.go)
## Bind node and notice the cluster
Now we have enough information to schedule a pod. We should choose the node that the pod run on. This is the so-called filter and score procedure in the kube-scheduler. [filter and score](https://kubernetes.io/docs/concepts/scheduling-eviction/kube-scheduler/#kube-scheduler-implementation)
For our test environment there is only one node and we just want to see the schedule result so let us skip the filter and score. Move on to the next phase. We should tell the cluster our schedule result. This phase called binding and of course there is an api in client SDK to help you.
```
binding := &v1.Binding{
ObjectMeta: metav1.ObjectMeta{Namespace: pod.Namespace, Name: pod.Name, UID: pod.UID},
Target: v1.ObjectReference{Kind: "Node", Name: pod.Spec.NodeName},
}
err := client.CoreV1().Pods(binding.Namespace).Bind(ctx, binding, metav1.CreateOptions{})
```
Let us test our scheduler. Deploy a nginx which specify the schedule name to our scheduler.
```
apiVersion: v1
kind: Pod
metadata:
name: webserver
spec:
containers:
- name: webserver # The name that this container will have.
image: nginx:1.14.0 # The image on which it is based.
hostNetwork: true
schedulerName: "StupidScheduler"
```
Deploy before start our scheduler.
```
$ kubectl apply -f nginx_deployment.yaml
pod/webserver created
$ kubectl get pods
NAME READY STATUS RESTARTS AGE
webserver 0/1 Pending 0 4s
```
We can see the pod is in pending status.
Now start our scheduler
```
# go run scheduler.go ~/scheduler.conf
add event for pod default/webserver
add event for node "test"
Success bind pod default/webserver
```
We can see our pod is running now.
```
$ kubectl get pods
NAME READY STATUS RESTARTS AGE
webserver 1/1 Running 0 2m3s
```
Test wherthe it works
```
$ curl localhost:80
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>
```
If you see this. Congratulation! You just finish a your own kubernetes scheduler.
This basic tutorial just help you understand the kubernetes scheduler. Here we skip many problems occurs in the production environment. You can continue to read the advance topic or find the answer in the kube-scheduler.
More questions:
1. Can you split the schedule procedure to different phases? And point out each phase main task?
[Kube scheduler framework](https://kubernetes.io/docs/concepts/scheduling-eviction/scheduling-framework/)
2. Can a single scheduler to schedule pod with different policy according to its configuration?
[Kube scheduler profile]()
<file_sep>/Chapter2/scheduler.go
/*
Copyright 2021 <NAME> (<EMAIL>)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"context"
"fmt"
"os"
"sync"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/informers"
clientset "k8s.io/client-go/kubernetes"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/clientcmd"
)
const (
schedulerName = "StupidScheduler"
)
var (
podslock sync.Mutex
nodeslock sync.Mutex
pods map[string]*v1.Pod
nodes map[string]*v1.Node
)
func addPod(obj interface{}) {
pod := obj.(*v1.Pod)
fmt.Printf("add event for pod %s/%s\n", pod.Namespace, pod.Name)
podslock.Lock()
defer podslock.Unlock()
pods[pod.Namespace+pod.Name] = pod
}
func addNode(obj interface{}) {
node := obj.(*v1.Node)
fmt.Printf("add event for node %q\n", node.Name)
nodeslock.Lock()
defer nodeslock.Unlock()
nodes[node.Name] = node
}
// interestedPod selects pods that are assigned (scheduled and running).
func interestedPod(pod *v1.Pod) bool {
return pod.Spec.SchedulerName == schedulerName && len(pod.Spec.NodeName) == 0
}
func scheduleOne(ctx context.Context, client clientset.Interface) {
var pod *v1.Pod
podslock.Lock()
for k, v := range pods {
pod = v
delete(pods, k)
break
}
podslock.Unlock()
if pod == nil {
return
}
nodeslock.Lock()
for _, v := range nodes {
pod.Spec.NodeName = v.Name
break
}
nodeslock.Unlock()
binding := &v1.Binding{
ObjectMeta: metav1.ObjectMeta{Namespace: pod.Namespace, Name: pod.Name, UID: pod.UID},
Target: v1.ObjectReference{Kind: "Node", Name: pod.Spec.NodeName},
}
err := client.CoreV1().Pods(binding.Namespace).Bind(ctx, binding, metav1.CreateOptions{})
if err != nil {
fmt.Printf("failed bind pod %s/%s\n", pod.Namespace, pod.Name)
pod.Spec.NodeName = ""
podslock.Lock()
defer podslock.Unlock()
pods[pod.Namespace+pod.Name] = pod
}
fmt.Printf("Success bind pod %s/%s\n", pod.Namespace, pod.Name)
}
func main() {
pods = make(map[string]*v1.Pod)
nodes = make(map[string]*v1.Node)
// Prepare for informerfactory
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if len(os.Args) <= 1 || len(os.Args[1]) == 0 {
panic("No --kubeconfig was specified. Using default API client. This might not work")
}
// This creates a client, load kubeconfig
kubeConfig, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
&clientcmd.ClientConfigLoadingRules{ExplicitPath: os.Args[1]}, nil).ClientConfig()
if err != nil {
os.Exit(-1)
}
client, err := clientset.NewForConfig(restclient.AddUserAgent(kubeConfig, "scheduler"))
if err != nil {
os.Exit(-1)
}
informerfactory := informers.NewSharedInformerFactory(client, 0)
// Here we only care about pods and nodes.
informerfactory.Core().V1().Pods().Lister()
informerfactory.Core().V1().Nodes().Lister()
// Start all informers.
informerfactory.Start(ctx.Done())
// Wait for all caches to sync before scheduling.
informerfactory.WaitForCacheSync(ctx.Done())
informerfactory.Core().V1().Pods().Informer().AddEventHandler(
cache.FilteringResourceEventHandler{
FilterFunc: func(obj interface{}) bool {
switch t := obj.(type) {
case *v1.Pod:
return interestedPod(t)
case cache.DeletedFinalStateUnknown:
if pod, ok := t.Obj.(*v1.Pod); ok {
return interestedPod(pod)
}
fmt.Errorf("unable to convert object %T to *v1.Pod", obj)
return false
default:
fmt.Errorf("unable to handle object in %T", obj)
return false
}
},
Handler: cache.ResourceEventHandlerFuncs{
AddFunc: addPod,
},
},
)
informerfactory.Core().V1().Nodes().Informer().AddEventHandler(
cache.ResourceEventHandlerFuncs{
AddFunc: addNode,
},
)
for {
scheduleOne(ctx, client)
}
}
<file_sep>/README.md
# A tutorial to crack kubenetes scheduler
This is a tutorial to help you understand the kubernetes scheduler and the philosophy behind it.
This tutorial will guide you to write your own scheduler step by step. Besides that, there are also some questions to help you understand the difficulties in the production environment and the practice way to solve them by kube-scheduler.
I would try my best to make the tutorial as simple as possible and focus on the scheduler trunk. So that we would be hindered by robust, performance, error-handling etc. This does not mean these are not important, on the contrary, they cost the engineer enoumous time to tune it. After this tutorial, I believe you can find out these answers in kube-scheduler source code.
Before starting this tutorial, you still need some prerequisites for it:
- You need some basic knowledge about kubernetes and what the role is the scheduler. Here two links to help you understand it.
[What-is-kubernetes](https://kubernetes.io/docs/concepts/overview/what-is-kubernetes/) and [Kubernetes Components](https://kubernetes.io/docs/concepts/overview/components/)
- The Golang programming language, the tutorial chooses golang as the programming language so you need some knowledge to read the code and how to compile and run it. The kubernetes provides many programming language SDKs, you could choose one as you like to write a C++ , python, or Jave scheduler for kubernetes. You can download and install the golang SDK from [here](https://golang.org/dl/) and I highly recommend this [book](https://www.gopl.io/) for the beginner.
- You also need a computer to setup the development environment and setup a kubernetes cluster to test it.
- The other prerequisites I would point out in the following chapters.
## 1. [Communicate with the kubernetes cluster](Chapter1/README.md)
## 2. [Schedule a pod and notice the cluster](Chapter2/README.md)
# Advance topics
## 1. [Metrics and logs]()
## 2. [Scheduler Cache and priority queue]()
## 3. [Framework and profile]()
|
47621272827df6746e412fa31397b17efb611684
|
[
"Markdown",
"Go Module",
"Go",
"Shell"
] | 7 |
Markdown
|
lwmqwer/easy-learn-kubescheduler
|
8223133409bb2e79c326485cebb9ceebf95b8b56
|
52a04839af1146c81cedc2a2c75bfe2197f14b01
|
refs/heads/master
|
<file_sep>import React, { useState } from 'react';
// Components
import Form from './Form';
import ToDoList from './ToDoList';
// Meteor Data
import { withTracker } from 'meteor/react-meteor-data';
import { Tasks } from '../api/tasks';
const App = ({ tasks, incompleteCount }) => {
const [hideCompleted, setHideCompleted] = useState(false);
const toggleHideCompleted = () => setHideCompleted((prev) => !prev);
return (
<div className='container'>
<h1>To-Do List: {incompleteCount}</h1>
<label className='hide-completed'>
<input
type='checkbox'
checked={hideCompleted}
onClick={toggleHideCompleted}
/>
Hide Completed Tasks
</label>
<Form />
<ToDoList tasks={tasks} hideCompleted={hideCompleted} />
</div>
);
};
export default withTracker(() => {
return {
tasks: Tasks.find({}, { sort: { createdAt: -1 } }).fetch(),
incompleteCount: Tasks.find({ checked: { $ne: true } }).count(),
};
})(App);
<file_sep>Example function in Elm:
```elm
pluralize singular plural quantity =
if quantity == 1 then
singular
else
plural
main = -- this snippet works like JS console.log
text (pluralize "leaf" "leaves" 1)
```
Note that `if...else...` is an expression in Elm (very much like a JS ternary operator). This means that you _always_ need an `else`.
It's JS equivalent:
```js
function pluralize(singular, plural, quantity) {
if (quantity === 1) {
return singular;
} else {
return plural;
}
}
console.log(pluralize("leaf", "leaves", 1));
```
### DOM Representation
```html
<ul class="languages">
<li>Elm</li>
<li>JS</li>
</ul>
```
And the Elm equivalent:
```elm
ul [ class "languages" ] [
li [] [ text "Elm" ],
li [] [ text "JS" ]
]
```
In Elm, there's no syntactical dressing; you describe the DOM with function calls.
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
// Test Data
import data from "../testData/Chats";
const Chats = () => {
return (
<>
{data.map(chat => (
<div className="chat">
<img src={chat.picture} alt="User" />
<h2>{chat.name}</h2>
<p>{chat.lastMessage.text}</p>
<span className="last-message-timestamp">
{chat.lastMessage.timestamp}
</span>
</div>
))}
</>
);
};
Chats.propTypes = {
picture: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
lastMessage: PropTypes.shape({
text: PropTypes.string.isRequired,
timestamp: PropTypes.instanceOf(Date)
}).isRequired
};
Chats.defaultProps = {
picture: "",
name: "",
lastMessage: {
text: "",
timestamp: new Date()
}
};
export default Chats;
<file_sep>import React from "react";
// Components
import { Link, Router } from "@reach/router";
import Favorites from "./Favorites";
import Recents from "./Recents";
import Contacts from "./Contacts";
import Chats from "./Chats";
import Settings from "./Settings";
const App = () => (
<div>
<h1>WhatsApp Clone</h1>
<div className="links">
<Link to="/favorites">Favorites</Link>
<Link to="/recents">Recents</Link>
<Link to="/contacts">Contacts</Link>
<Link to="/chats">Chats</Link>
<Link to="/settings">Settings</Link>
</div>
<Router>
<Favorites path="/favorites" />
<Recents path="/recents" />
<Contacts path="/contacts" />
<Chats path="/chats" />
<Settings path="/settings" />
</Router>
</div>
);
export default App;
|
644733e19966b59fbf2c0f010cbc30997a8c4604
|
[
"JavaScript",
"Markdown"
] | 4 |
JavaScript
|
Mister-Corn/random-journeys
|
9d4e203faac555f220b228deb7f518ba7d7a4ec0
|
d541f059a674d734e03438669cac70a589410d79
|
refs/heads/master
|
<file_sep>#!/bin/bash
set -e
SAMSUNG=$(! xrandr --query | grep "DP-1-2 connected" > /dev/null; echo $?)
LG=$(! xrandr --query | grep "DP-1-1 connected" > /dev/null; echo $?)
#LG=$(</sys/class/drm/card0/card0-DP-3/status)
#notify-send -t 1000 "Monitor" "Samsung: $SAMSUNG\nLG: $LG"
if [ $SAMSUNG == 1 ] && [ $LG == 1 ]; then
echo "both connected"
/home/daniel/.screenlayout/dock-no-laptop.sh
notify-send -t 1000 "Dual-Monitor" "Both displays connected"
elif [ $SAMSUNG == 0 ] && [ $LG == 0 ]; then
echo "none connected"
/home/daniel/.screenlayout/laptop-only.sh
notify-send -t 1000 "Monitor" "No displays connected"
fi
exit 0
if xrandr --query | grep "DP-1-2 connected"; then
echo "LG connected"
fi
if xrandr --query | grep "DP-1-1 connected"; then
echo "Samsung connected"
fi
<file_sep>Daniel's Dotfiles
==
`bin/`: Some scripts written by me (+ friends) to help manage i3
`.config/`: This repo is in my home folder (~/), so .config/ is ~/.config/ which contains configuration files for many programs
Color Scheme: https://colorhunt.co/palette/17117
<file_sep>#!/bin/bash
set -e
# --------- TODO ----------
#
# - auto lock on close lid (/etc/systemd/system/i3lock.service)
# - install Overpass font
# - install wmctrl for Jan's shutdown script
# - change permission of backlight on @reboot in /etc/crontab
# - add red color to root's bash prompt
# - install browserpass native client, chromium and browserpass extension
# - install dropbox integration
# -------------------------
#su root
# setup sudo
#apt install sudo
usermod -aG sudo,video,audio,dialout daniel
# log out and back in and sudo will work
# disable the root account
#passwd -d root
#passwd -l root
# add non-free sources, e.g. for wifi drivers
cp /etc/apt/sources.list /etc/apt/sources.list.bak
if ! grep "deb http://httpredir.debian.org/debian/ stretch main contrib non-free" /etc/apt/sources.list
then
echo "deb http://httpredir.debian.org/debian/ stretch main contrib non-free" >> /etc/apt/sources.list
fi
apt update
apt upgrade -y
apt update
# drivers
apt install -y firmware-iwlwifi
modprobe -r iwlwifi
modprobe iwlwifi
# basic tools
apt install -y vim git curl rsync qemu make nmap gparted testdisk whois htop nasm hibernatie pass locate scdaemon gdb
# window manager ++
apt install -y i3 openconnect nm-applet openvpn xbacklight i3blocks fonts-font-awesome acpi feh moka-icon-theme faba-icon-theme faba-mono-icons xserver-xorg-input-synaptics terminator arandr albert compton ffmpeg pavucontrol arc-theme feh lxappearance scrot libnotify-bin numlockx
# needed software
apt install -y thunderbird texlive python3 python3-pip thunar chromium-browser texlive-latex-extra texlive-lang-german pdfgrep pass arbtt terminator telegram-desktop
# Lehrstuhl 1 software
apt install-y ansible mysql-workbench
# current semester uni stuff
apt install -y opam m4
opam install ocaml utop merlin ocp-indent
opam user-setup install
# maybe needed, maybe not?
# -> _
# install fzf
git clone --depth 1 https://github.com/junegunn/fzf.git ~/.fzf
echo -e "y\ny\ny" | ~/.fzf/install
# install and enable albert
# BROKEN!!!
# install + enable arbtt
# done in i3config
# autostarts (done by i3?)
# set i3 as standard wm
# install + setup vs code (+ merlin)
wget "https://go.microsoft.com/fwlink/?LinkID=760868" -O vscode.deb
apt install -y ./vscode.deb
# install teamviewer
wget "https://download.teamviewer.com/download/linux/teamviewer_amd64.deb" -O teamviewer.deb
apt install -y ./teamviewer.deb
# install skype
# install spotify
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 931FF8E79F0876134EDDBDCCA87FF9DF48BF1C90
echo deb http://repository.spotify.com stable non-free | sudo tee /etc/apt/sources.list.d/spotify.list
apt update
apt install -y spotify-client
# install Telegram Desktop
wget "https://telegram.org/dl/desktop/linux" > telegram.tar
tar -xf telegram.tar
mv Telegram /opt/
ln -s /opt/Telegram/Telegram /usr/local/bin/telegram
# prepare for easy backlight management
chmod a+w /sys/class/backlight/intel_backlight/brightness
# install nice font from github https://github.com/supermarin/YosemiteSanFranciscoFont
wget "https://github.com/supermarin/YosemiteSanFranciscoFont/archive/master.zip" -O font.zip
unzip font.zip
mv YosemiteSanFranciscoFont-master/*.ttf ~/.fonts/
# install moka icon theme for gtk
wget "https://snwh.org/moka/download.php?owner=snwh&ppa=ppa&pkg=moka-icon-theme,18.04" -O moka.deb
apt install ./moka.deb
source ~/.bashrc
echo "\e[32m\e[1mE------------------------------------------------------\e[0m"
echo -e "\e[32m\e[1mEverything complete.\e[0m Some things still need to be done:"
echo "1. install and setup Slack and VS Code"
echo "2. copy over the WiFi configurations from /etc/NetworkManager/..."
echo "3. install light: https://github.com/haikarainen/light/releases"
echo "4. open lxappearence and select the arc theme and moka icon theme"
|
d288dd18348d2c17f73a05ab3c6e8a0c7ed206f7
|
[
"Markdown",
"Shell"
] | 3 |
Shell
|
dabch/dotfiles
|
ae187fc96db4f193ce3198a72799bd68def91cec
|
b3f474cdd7d7b0fcbe09c47b16bf99157966298d
|
refs/heads/master
|
<file_sep>window.MovieModel = Backbone.Model.extend({
defaults:{
movie:"",
director:"",
language:"",
runtime:0
}
});
window.MovieCollection = Backbone.Collection.extend({
model: MovieModel,
initialize: function () {
console.log('collection initialised!')
},
comparator: function (item) {
return -item.get(this.key);
},
sortByField: function (fieldName) {
this.key = fieldName;
this.sort();
},
url: "movies.json"
});
window.MovieListView = Backbone.View.extend({
tagName: 'tr',
render: function(){
this.$el.html("<td>"+this.model.get('movie')+"</td>");
this.$el.append("<td>"+this.model.get('director')+"</td>");
this.$el.append("<td>"+this.model.get('language')+"</td>");
this.$el.append("<td>"+this.model.get('runtime')+"</td>");
// this.$el.append("<td>"+this.model.get('thumb')+"</td>");
return this;
}
});
window.StartView = Backbone.View.extend( {
el:'body',
collection: new MovieCollection(),
searchCollection: new MovieCollection(),
sortDescending: true,
initialize: function(){
var that = this;
this.collection.fetch({
success: function(){
that.render(that.collection);
},
error: function(){
console.log(that)
}
});
return this;
},
render: function(collection){
$('#movie-table tbody').empty();
collection.each(function(model) {
var movieListView = new MovieListView({model:model});
$('#movie-table tbody').append(movieListView.render().el);
});
},
events: {
'keyup #search': 'search',
'click #runtime': 'sort'
},
sort: function () {
this.collection.sortByField('runtime');
this.render(this.collection);
},
search : function(){
var searchString = $('#search').val().toLowerCase();
var that=this;
this.searchCollection.reset();
if(searchString.length>0){
that.collection.each(function(model){
if((model.get('movie').toLowerCase().indexOf(searchString)>-1)
|| (model.get('director').toLowerCase().indexOf(searchString)>-1)){
that.searchCollection.add(model);
}
});
that.render(that.searchCollection);
}
else if(searchString.length==0){
that.render(that.collection);
}
}
});
window.App = new StartView();
|
c9679f373d393fe9104a286799acc9b8bb068755
|
[
"JavaScript"
] | 1 |
JavaScript
|
ambarbs/BackboneMovieDB
|
ceb589adbd24cb6a4bcc282e6170445f26bdd710
|
e4e04684daab3045259b984714caddd7c34f2ff7
|
refs/heads/gh-pages
|
<file_sep>/* global math */
// Variables
var buttons = ['7', '8', '9', '+',
'4', '5', '6', '-',
'1', '2', '3', '*',
'0', '.', '=', '/',
'sin', 'cos', '^', 'sqrt',
'tan', 'cot', '(', ')',
'e^','ln','clr', '<-','pi'
];
// e^x
// ln()
// Closing paraenthesis bug
var lastNum = 'new';
var answer;
var autoclear = false;
function renderContent() {
// Create base elements for the page
var container = createElement('div', '', {
id: 'container'
});
var header = createElement('div', '', {
id: 'header'
});
var nav = createElement('div', '', {
id: 'nav'
});
var main = createElement('div', '', {
id: 'main'
});
var aside = createElement('div', '', {
id: 'aside'
});
var footer = createElement('div', '', {
id: 'footer'
});
// Append main elements to container
container.appendChild(header);
container.appendChild(nav);
container.appendChild(main);
container.appendChild(aside);
container.appendChild(footer);
// Insert content
header.appendChild(createElement('h1', '<NAME>', {
className: 'title'
}));
main.appendChild(calculator());
footer.appendChild(footerButtons());
footer.appendChild(about());
// Add container to page
document.body.appendChild(container);
//document.getElementById('cal-box').focus();
}
function createElement(type, textContent, options) {
var elem = document.createElement(type);
elem.textContent = textContent;
if (options) {
for (var option in options) {
elem[option] = options[option];
}
}
return elem;
}
function calculator() {
var calculatorWrap = createElement('div', '', {
id: 'calculator'
}); // Add calculator wrapper div
calculatorWrap.appendChild(createElement('input', '', {
className: 'cal-box',
id: 'cal-box'
})); // Add input box
buttons.forEach(function(buttonContent) {
var button = createElement('button', buttonContent, {
className: 'cal-button',
id: buttonContent
});
button.addEventListener('click', handleButton, false);
calculatorWrap.appendChild(button);
}); // Add calculator buttons
return calculatorWrap;
}
function footerButtons() {
var btnWrapper = createElement('div', '');
var span = createElement('span', 'OFF', { id: 'spantxt' });
var autoclr = createElement('button', 'Auto Clear: ', { className: 'auto-false', id: 'autoclr' });
autoclr.addEventListener('click', function(event){
if(autoclr.className == 'auto-false'){
autoclr.className = 'auto-true';
span.textContent = 'ON';
autoclear = true;
} else {
autoclr.className = 'auto-false';
span.textContent = 'OFF';
autoclear = false;
}
}, false);
autoclr.appendChild(span);
var toggle = createElement('button', 'Toggle Theme', { className: 'toggle', id: 'toggle' });
toggle.addEventListener('click', function(event){
theme = document.body.className;
if (theme == 'theme-light') {
document.body.className = 'theme-dark';
} else {
document.body.className = 'theme-light';
}
}, false);
btnWrapper.appendChild(autoclr);
btnWrapper.appendChild(toggle);
return btnWrapper;
}
function about() {
var about = createElement('div','');
var math = createElement('p', 'Solutions calculated using ');
math.appendChild(createElement('a', 'math.js', { href: 'http://mathjs.org/'} ));
about.appendChild(math);
var creator = createElement('p', 'Created by ');
creator.appendChild(createElement('a', '@keawade', { href: 'https://github.com/keawade' }));
about.appendChild(creator);
return about;
}
// Need to rewrite keypress to be more efficient
// If Enter/Return is pressed, click '=' to evaluate
document.addEventListener('keypress', function(key) {
var keyString = String.fromCharCode(key.charCode);
if (key.keyCode == 13) {
document.getElementById('=').click();
} else if (/[0-9]|[-/*+=.^()]/.test(keyString)) {
document.getElementById(keyString).click();
} else if (key.keyCode == 8) {
var box = document.getElementById('cal-box')
if (box === document.activeElement) {
//
} else {
if (box.value == '') {
// Do nothing
} else {
document.getElementById('<-').click();
}
}
} // keyCode 46 is Delete
}, false);
function handleButton(event) {
var box = document.getElementById('cal-box');
if (!(box === document.activeElement)) {
// Solve
if(autoclear){
if(lastNum == '=') {
box.value = '';
}
}
if (event.target.id == '=') {
var temp = box.value.replace(/ln\(/g, 'log(');
answer = math.eval(temp);
if (!isNaN(answer)) {
box.value = answer;
if(autoclear){
lastNum = '=';
} else {
lastNum = answer;
}
}
// Clear
} else if (event.target.id == 'clr') {
box.value = '';
lastNum = 'new';
// Backspace
} else if (event.target.id == '<-') {
box.value = box.value.substring(0, box.value.length - 1);
lastNum = box.value.charAt(box.value.length - 1);
// Numbers
} else if (/[0-9]/.test(event.target.id)) {
box.value = box.value + event.target.id;
lastNum = event.target.id;
// Symbols
} else if (/[-/*+.]/.test(event.target.id)) {
if(!(/new|[-/*+.]/.test(lastNum))){
box.value = box.value + event.target.id;
lastNum = event.target.id;
}
} else if (event.target.id == '^'){
if (/[0-9]|\)/.test(lastNum)) {
box.value = box.value + '^(';
}
} else if (/[\(\)]/.test(event.target.id)) {
box.value = box.value + event.target.id;
lastNum = event.target.id;
// Trig Functions
} else if (/sin|cos|tan|cot|sqrt|e\^|ln/.test(event.target.id)) {
box.value = box.value + event.target.id + '('
lastNum = '(';
} else if (/pi/.test(event.target.id)){
box.value = box.value + '(pi)';
lastNum = ')';
}
this.blur();
}
}
/*
if(!isNaN(event.target.id)) {
// If last operation was math.eval then start new string
if(lastNum == 'new') {
box.value = '';
}
// Append new value
box.value = box.value + event.target.id;
lastNum = event.target.id;
// If clicked button is not a number
} else {
// If clicked button is '='
if(event.target.id == '=') {
// Evaluate current string
answer = math.eval(box.value)
if(isNaN(answer)){
//
} else {
box.value = answer;
}
// Note that the last operation was an eval
lastNum = 'new';
// If clicked button is an operation
} else {
// If the last button clicked was a number, allow the operator to be appended
if(!isNaN(lastNum)) {
box.value = box.value + event.target.id;
lastNum = event.target.id;
}
}
}
// Remove keyboard focus on button
this.blur();
} if(event.target.id == '=') {
// Evaluate current string
answer = math.eval(box.value)
if(isNaN(answer)){
//
} else {
box.value = answer;
}
// Note that the last operation was an eval
lastNum = 'new';
*/
renderContent();
<file_sep>Calculator
==========
Description
-----------
This was an exercise to get experience using DOM manipulation to build web pages. It ended up also being a fun exercise in user interface/experience design.
The original exercise can be found at https://github.com/unioncollege-webtech/calculator
|
d88dc9b83b48942221d4a9f77c8e46a87c2cf613
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
keawade/cuddly-weasel
|
43731c74eda72a2a35e2463d14a36a6ceebe6931
|
97e267c826e872d7e877b7925b8ca07d1d91e87a
|
refs/heads/master
|
<file_sep>class View {
constructor(game, $el) {
this.game = game;
this.$el = $el;
this.setupBoard();
this.bindEvents();
}
bindEvents() {
const $square = $("li");
$square.on("click", (e) => {
const $tile = $(e.currentTarget);
this.makeMove($tile);
});
}
makeMove($square) {
const $pos = $square.data("pos");
const mark = this.game.currentPlayer;
try {
this.game.playMove($pos);
} catch (e) {
alert("This " + e.msg.toUpperCase());
return;
}
if (mark === 'x') {
$($square).addClass("x:after");
$($square).css('background-color', 'yellowgreen');
} else {
$($square).addClass("o:after");
$($square).css('background-color', 'skyblue');
}
}
setupBoard() {
const $row = $("<ul>").addClass("row");
for (let rowIdx = 0; rowIdx < 3; rowIdx++) {
for (let colIdx = 0; colIdx < 3; colIdx++) {
const $tile = $("<li>").addClass("tile").data("pos", [rowIdx, colIdx]);
$row.append($tile);
}
}
this.$el.append($row);
}
}
module.exports = View;
<file_sep>const View = require ('./ttt-view.js');
const Game = require ('../../TicTacToe_solution/game.js');
$( () => {
const $game = new Game();
const $el = $("figure");
new View($game, $el);
});
|
84af9da8bf06d8751861175771a45a785514f0cf
|
[
"JavaScript"
] | 2 |
JavaScript
|
as6730/W6D2
|
cb612314bb575faf69f1b2951a99ee75d2f0336c
|
9446782c4d4c95ed78433183d09d9a2502e78bcb
|
refs/heads/main
|
<repo_name>xvd112/nagari_lama<file_sep>/app/Views/galeri/view.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<!-- Main content -->
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-user-friends mr-1"></i>
View Gambar : <?= $galeri->jenis; ?>
</h3>
<div class="card-tools">
<ul class="nav nav-pills ml-auto">
<li class="nav-item">
<button type="button" style="margin-left: 10px;" class="btn btn-success">
<a href="<?php echo base_url('galeri/edit/' . $galeri->id_galeri); ?>" style="color: white;">
<i class="far fa-plus-square"> Edit Data</i>
</a>
</button>
</li>
</ul>
</div>
</div><!-- /.card-header -->
<div class="row card-body" align="center">
<h1><b><u><?= $galeri->jenis; ?></u></b></h1>
<img src="<?= base_url(); ?>/aset/img/<?= $galeri->foto; ?>">
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</div>
<!-- /.container-fluid -->
</section>
<!-- /.content -->
<!-- /.content -->
<?= $this->endSection(); ?><file_sep>/app/Models/AuthModel.php
<?php
namespace App\Models;
use CodeIgniter\Model;
class AuthModel extends Model
{
protected $table = 'users';
public function getUser($id = false, $level = false)
{
if ($id == false and $level != false) {
return $this->where('level', $level)->orderBy('id', 'DESC')->findAll();
} elseif ($id != false and $level != false) {
return $this->where('level', $level)->getWhere(['id' => $id])->getRow();
} else {
return $this->getWhere(['id' => $id])->getRow();
}
}
public function saveUser($data)
{
$builder = $this->db->table($this->table);
return $builder->insert($data);
}
public function editUser($data, $id)
{
$builder = $this->db->table($this->table);
$builder->where('id', $id);
return $builder->update($data);
}
public function hapusUser($id)
{
$builder = $this->db->table($this->table);
return $builder->delete(['id' => $id]);
}
public function login($x, $log)
{
return $this->where($x, $log)->get()->getRowArray();
}
}
<file_sep>/app/Views/user/input.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<!-- Main content -->
<section class="content">
<?php if (session()->getFlashdata('error')) { ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('error'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php } ?>
<form method="post" action="<?= base_url('user/add'); ?>">
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-user mr-1"></i>
Data User
</h3>
</div>
<div class="container-fluid card-body">
<?= csrf_field(); ?>
<?php if ($level == 1 or $level == 2) { ?>
<div class="row mb-3">
<label for="id_datauser" class="col-sm-2 col-form-label">Data Perangkat</label>
<div class="col-sm-10">
<select class="form-control select2bs4" name="id_datauser" id="id_datauser" required required>
<option value="">Pilih Data Perangkat</option>
<?php
foreach ($data as $data) {
?>
<option value="<?= $data['id_pemerintahan']; ?>"><?= $data['nama'] ?> - <?= $data['jabatan']; ?></option>
<?php } ?>
</select>
</div>
</div>
<?php } elseif ($level == 3) { ?>
<div class="row mb-3">
<label for="id_keluarga" class="col-sm-2 col-form-label">No KK</label>
<div class="col-md-10">
<select onchange="nik()" class="form-control select2bs4" name="id_keluarga" id="id_keluarga" required>
<option value="">Pilih No KK</option>
<?php
foreach ($data as $k) {
?>
<option value="<?php echo $k['id_keluarga'] ?>"><?php echo $k['no_kk'] ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row mb-3">
<label for="id_penduduk" class="col-sm-2 col-form-label">NIK</label>
<div class="col-md-10">
<select onchange="ambilnik()" class="form-control select2bs4" name="id_penduduk" id="id_penduduk" required>
<option value="">Pilih NIK</option>
</select>
</div>
</div>
<?php } ?>
<div class="row mb-3">
<label for="username" class="col-sm-2 col-form-label">Username</label>
<div class="col-sm-10">
<input autocomplete="off" type="text" placeholder="Masukkan Username" class="form-control" id="username" name="username" required>
</div>
</div>
<div class="row mb-3">
<label for="email" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input autocomplete="off" type="email" placeholder="Masukkan Email" class="form-control" id="email" name="email">
</div>
</div>
<div class="row mb-3">
<label for="pass" class="col-sm-2 col-form-label">Password</label>
<div class="col-sm-10">
<input autocomplete="off" minlength="8" type="password" placeholder="Masukkan Password" class="form-control" id="pass" name="pass" required>
</div>
</div>
<div class="row mb-3">
<label for="telp" class="col-sm-2 col-form-label">Nomor Telepon</label>
<div class="col-sm-10">
<input autocomplete="off" type="text" placeholder="Masukkan Nomor Telepon" class="form-control" id="telp" name="telp">
</div>
</div>
<input type="hidden" name="level" id="level" value="<?= $level; ?>">
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-danger">Clear</button>
</form>
</section>
<!-- /.content -->
<!-- /.content -->
<?= $this->endSection(); ?><file_sep>/app/Views/template/form.php
<script>
$(function() {
$("#example1").DataTable({
"responsive": true,
"lengthChange": true,
"autoWidth": false,
"buttons": ["copy", "csv", "excel", "pdf", "print", "colvis"]
}).buttons().container().appendTo('#example1_wrapper .col-md-6:eq(0)');
$('#example2').DataTable({
"paging": true,
"lengthChange": true,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": false,
"responsive": true,
});
$('#example2-2').DataTable({
"paging": true,
"lengthChange": true,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": false,
"responsive": true,
});
$('#example2-3').DataTable({
"paging": true,
"lengthChange": true,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": false,
"responsive": true,
});
$("#centangsemua").click(function(e) {
if ($(this).is(':checked')) {
$('.centang').prop('checked', true);
} else {
$('.centang').prop('checked', false);
}
});
$("#centangsemua2").click(function(e) {
if ($(this).is(':checked')) {
$('.centang').prop('checked', true);
} else {
$('.centang').prop('checked', false);
}
});
$("#centangsemua3").click(function(e) {
if ($(this).is(':checked')) {
$('.centang').prop('checked', true);
} else {
$('.centang').prop('checked', false);
}
});
$(document).on('shown.lte.pushmenu', handleExpandedEvent)
$('[data-widget="pushmenu"]').PushMenu('toggle')
});
$.widget.bridge('uibutton', $.ui.button)
</script><file_sep>/app/Views/info/index.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<!-- Main content -->
<section class="content">
<?php if (session()->getFlashdata('error')) { ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('error'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php } ?>
<?php if (session()->getFlashdata('pesan_data')) : ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('pesan_data'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>
<?php if (session()->getFlashdata('warning_data')) : ?>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('warning_data'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>
<div>
<button type="button" class="btn btn-success">
<a href="<?php echo base_url('data/editinfo'); ?>" style="color: white;">
<i class="fas fa-edit"> Edit Data</i>
</a>
</button>
</div>
<br>
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-phone mr-1"></i>
Kontak
</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse">
<i class="fas fa-minus"></i>
</button>
</div>
</div>
<div class="container-fluid card-body">
<table class="table">
<tr>
<td style="width: 200px;">Nomor Telepon</td>
<td style="width: 1px;"> : </td>
<td><a href="tel:<?= $tambah->telp; ?>"> <i class="fas fa-phone"></i></a> <?= $tambah->telp; ?></td>
</tr>
<tr>
<td>Email</td>
<td> : </td>
<td><a href="mailto:<?= $tambah->email; ?>"> <i class="fas fa-envelope"></i></a> <?= $tambah->email; ?></td>
</tr>
</table>
</div>
</div>
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-info mr-1"></i>
Info
</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse">
<i class="fas fa-minus"></i>
</button>
</div>
</div>
<div class="container-fluid card-body">
<table class="table">
<?php if (session()->get('level') == 1) { ?>
<tr>
<td style="width: 1px;">Kata Sambutan</td>
<td style="width: 1px;"> : </td>
<td><?= $data->kata_sambutan; ?></td>
</tr>
<?php } ?>
<tr>
<td style="width: 1px;">Visi</td>
<td style="width: 1px;"> : </td>
<td><?= $data->visi; ?></td>
</tr>
<tr>
<td>Misi</td>
<td> : </td>
<td><?= $data->misi; ?></td>
</tr>
<tr>
<td>Sejarah</td>
<td> : </td>
<td><?= $data->sejarah; ?></td>
</tr>
<tr>
<td>Wilayah</td>
<td> : </td>
<td><?= $data->wilayah; ?></td>
</tr>
<tr>
<td>Persyaratan Surat</td>
<td> : </td>
<td><?= $data->syarat_surat; ?></td>
</tr>
</table>
</div>
</div>
</section>
<!-- /.content -->
<!-- /.content -->
<?= $this->endSection(); ?><file_sep>/app/Views/web/kontak.php
<?= $this->extend('web/template'); ?>
<?= $this->section('content'); ?>
<main id="main">
<section style="padding: 40px; background: #f8fcfd;">
<div class="card">
<div class="card-body">
<table class="table">
<tr>
<td>Alamat</td>
<td> : </td>
<td><a href="<?= $data->map_kantor; ?>" target="_blank"><?= $data->alm; ?>, Nagari <?= $data->nagari; ?>, Kec. <?= $data->kec; ?>, Kab. <?= $data->kab; ?>, <?= $data->prov; ?>, Indonesia, <?= $data->kd_pos; ?></a></td>
</tr>
<tr>
<td>No. Telepon</td>
<td> : </td>
<td><a href="tel:<?= $data->telp; ?>"><?= $data->telp; ?></a></td>
</tr>
<tr>
<td>Email</td>
<td> : </td>
<td><a href="mailto:<?= $data->email; ?>"><?= $data->email; ?></a></td>
</tr>
</table>
</div>
</div>
<h1 align="center" style="padding: 20px;"><b>PETA</b></h1>
<div class="card" align="center">
<?= $data->map_wilayah; ?>
</div>
</section>
</main>
<?= $this->endSection(); ?><file_sep>/app/Views/penduduk/index.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<?php if (session()->getFlashdata('pesan_penduduk')) : ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('pesan_penduduk'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php elseif (session()->getFlashdata('danger_penduduk')) : ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('danger_penduduk'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php elseif (session()->getFlashdata('warning_penduduk')) : ?>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('warning_penduduk'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-user-friends mr-1"></i>
Data penduduk
</h3>
<div class="card-tools">
<ul class="nav nav-pills ml-auto">
<li>
<button type="button" style="margin-left: 10px;" class="btn btn-success">
<a href="<?php echo base_url('/penduduk/input'); ?>" style="color: white;">
<i class="far fa-plus-square"> Tambah Data</i>
</a>
</button>
</li>
<li class="nav-item">
<button type="button" class="btn" style="background:purple; margin-left:10px">
<a href="<?php echo base_url('/penduduk/import'); ?>" style="color: white;">
<i class="fas fa-file-import"> Import Data</i>
</a>
</button>
</li>
<li class="nav-item">
<button type="button" class="btn" style="background:grey; margin-left:10px">
<a href="<?php echo base_url('/penduduk/laporan'); ?>" style="color: white;">
<i class="fas fa-download"></i>
</a>
</button>
</li>
</ul>
</div>
</div>
<div class="card-body">
<b>Total Penduduk : </b><?= $jml; ?> orang
<div style="float: right;">
<form method="post" action="">
<div class="input-group mb-3">
<input type="text" class="form-control" aria-describedby="basic-addon2" name="key">
<div class="input-group-append">
<button class="btn btn-outline-secondary" name="submit" type="submit">Cari</button>
</div>
</div>
</form>
</div>
<?= form_open('penduduk/hapusbanyak', ['class' => 'formhapus']) ?>
<div style="padding-bottom: 10px;">
<button type="submit" style="margin-left: 10px;" class="btn btn-danger tombolHapusBanyak" onclick="javascript:return confirm('Apakah ingin menghapus data ini ?')">
<i class="far fa-trash-alt"> Hapus</i>
</button>
</div>
<table class="table table-bordered table-hover">
<thead class="thead-dark" style="text-align: center;">
<tr>
<th>
<input type="checkbox" id="centangsemua">
</th>
<th style="text-align:center">No</th>
<th style="text-align:center">Nomor KK</th>
<th style="text-align:center">NIK</th>
<th style="text-align:center">Nama</th>
<th>Aksi</th>
</tr>
</thead>
<?php
$no = 1 + (10 * ($currentPage - 1));
foreach ($penduduk as $data) {
?>
<tr>
<td style="text-align: center;">
<input type="checkbox" id="check" name="id_penduduk[]" class="centang" value="<?= $data['id_penduduk']; ?>">
</td>
<td><?= $no; ?></td>
<td id="no_kk"><a href="<?= base_url(); ?>/keluarga/view/<?= $data['id_keluarga']; ?>"><?= $data['no_kk']; ?></a></td>
<td id="nik"><?= $data['nik']; ?></td>
<td id="nama"><?= $data['nama']; ?></td>
<td style="text-align: center;">
<a href="<?php echo base_url('/penduduk/view/' . $data['id_penduduk']); ?>" style="color: black;">
<li class="far fa-eye"></li>
</a>
<a href="<?php echo base_url('penduduk/edit/' . $data['id_penduduk']); ?>" style="color: black;">
<li class="far fa-edit"></li>
</a>
<a href="<?php echo base_url('penduduk/delete/' . $data['id_penduduk']); ?>" onclick="javascript:return confirm('Apakah Anda Yakin Ingin Menghapus Data Ini?')" style="color: black;">
<li class="far fa-trash-alt"></li>
</a>
</td>
</tr>
<?php $no++;
}
?>
</table>
<?= form_close(); ?>
<?= $pager->links('data', 'bootstrap_pagination') ?>
</div>
</div>
</div>
</div>
</div>
</section>
<?= $this->endSection(); ?><file_sep>/app/Views/alamat/index.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<!-- Main content -->
<section class="content">
<?php if (session()->getFlashdata('error')) { ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('error'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php } ?>
<?php if (session()->getFlashdata('pesan_data')) : ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('pesan_data'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>
<?php if (session()->getFlashdata('warning_data')) : ?>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('warning_data'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-info mr-1"></i>
<?= $ket[0]; ?>
</h3>
<div class="card-tools">
<ul class="nav nav-pills ml-auto">
<li class="nav-item">
<button type="button" class="btn btn-success">
<a href="<?php echo base_url('/data/edit'); ?>" style="color: white;">
<i class="fas fa-edit"> Edit Data</i>
</a>
</button>
</li>
</ul>
</div>
</div>
<div class="container-fluid card-body">
<table class="table">
<tr>
<td>Alamat Kantor</td>
<td> : </td>
<td><?= $data->alm; ?>, Nagari <?= $data->nagari; ?>, Kecamatan <?= $data->kec; ?>, Kabupaten <?= $data->kab; ?>, <?= $data->prov; ?>, <?= $data->kd_pos; ?></td>
<td><a href="<?= $data->map_kantor; ?>" target="_blank"><i class="fas fa-map-signs"></i></a></td>
</tr>
<tr>
<td>Area Nagari</td>
<td> : </td>
<td><?= $data->map_wilayah; ?></td>
<td></td>
</tr>
</table>
</div>
</div>
</section>
<!-- /.content -->
<!-- /.content -->
<?= $this->endSection(); ?><file_sep>/app/Models/IsiModel.php
<?php
namespace App\Models;
use CodeIgniter\Model;
class IsiModel extends Model
{
public function getIsi($id = false, $tabel)
{
if ($id === false) {
$builder = $this->db->table($tabel);
return $builder->select('nama')->get()->getResultArray();
} else {
$builder = $this->db->table($tabel);
return $builder->where('id', $id)->get()->getRow();
}
}
}
<file_sep>/app/Views/surat/print.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="SHORTCUT ICON" href="<?php echo base_url() ?>/aset/img/logo.png">
</head>
<body>
<?= $this->include('template/tgl'); ?>
<div align="center">
<b><u>SURAT KETERANGAN USAHA</u></b><br>
NO.<?= $surat->no_surat; ?>/PEREK/<?= date('Y', strtotime($surat->tgl_surat)); ?>
</div>
<div style="text-align: justify;">
Yang bertanda tangan dibawah ini adalah Wali Nagari <?= $data->nagari; ?> Kecamatan <?= $data->kec; ?> Kabupaten <?= $data->kab; ?>, dengan ini :
<br>
<table>
<tr>
<td>Nama</td>
<td style="width: 10px;"> : </td>
<td style="width: 60%;"><b><?= $surat->nama; ?></b></td>
</tr>
<tr>
<td>Jenis Kelamin</td>
<td> : </td>
<td><?= $surat->jekel; ?></td>
</tr>
<tr>
<td>Tempat/Tanggal Lahir</td>
<td> : </td>
<td><?= $surat->tpt_lahir; ?> / <?= tgl_indo($surat->tgl_lahir); ?></td>
</tr>
<tr>
<td>NIK</td>
<td> : </td>
<td><?= $surat->nik; ?></td>
</tr>
<tr>
<td>Agama</td>
<td> : </td>
<td><?= $surat->agama; ?></td>
</tr>
<tr>
<td>Pekerjaan</td>
<td> : </td>
<td><?= $surat->kerja; ?></td>
</tr>
<tr>
<td>Alamat</td>
<td> : </td>
<td><?= $kk->alamat; ?> Nagari <?= $data->nagari; ?> Kecamatan <?= $data->kec; ?> Kabupaten <?= $data->kab; ?></td>
</tr>
</table>
<br>
Nama yang tersebut diatas memang benar Penduduk Nagari <?= $data->nagari; ?> Kecamatan <?= $data->kec; ?> Kabupaten <?= $data->kab; ?> dan benar usaha sehari-hari adalah <b><?= $surat->tambahan; ?></b>. <br>
Surat Keterangan Usaha ini dipergunakan sebagai syarat untuk <?= $surat->tujuan; ?>. <br>
Demikianlah Surat Keterangan usaha ini kami berikan untuk dapat dipergunakan oleh yang bersangkutan.
<div style="text-align: right;">
<?= $data->nagari; ?>, <?= tgl_indo($surat->tgl_surat); ?><br>
Wali Nagari <?= $data->nagari; ?>
<?php if ($ttd->jabatan == 'Sekretaris Nagari')
echo '<br> a/n Sekretaris Nagari'
?>
<br><br><br><br>
<?= $ttd->nama; ?>
</div>
</div>
</body>
</html><file_sep>/app/Controllers/Aduan.php
<?php
namespace App\Controllers;
use App\Models\PendudukModel;
use App\Models\AuthModel;
use App\Models\PerangkatModel;
use App\Models\AduanModel;
class Aduan extends BaseController
{
public function __construct()
{
helper('form');
$this->model = new AduanModel();
$this->penduduk = new PendudukModel();
$this->user = new AuthModel();
$this->perangkat = new PerangkatModel();
}
public function index()
{
if (session()->get('level') == 1 or session()->get('level') == 2) {
$ket = [
'List Aduan', '<li class="breadcrumb-item active"><a href="' . base_url() . '/aduan/index">List Aduan</a></li>'
];
$data = [
'title' => 'List Aduan',
'ket' => $ket,
'link' => 'home',
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id),
'aduan_blm' => $this->model->getAduan(false, false, 'Belum Diproses'),
'aduan_sdh' => $this->model->getAduan(false, false, 'Selesai')
];
return view('aduan/indexadmin', $data);
} elseif (session()->get('level') == 3) {
$ket = [
'List Aduan', '<li class="breadcrumb-item active"><a href="' . base_url() . '/aduan/index">List Aduan</a></li>'
];
$data = [
'title' => 'List Aduan',
'ket' => $ket,
'link' => 'home',
'user' => $this->penduduk->getPenduduk(session()->get('id_datauser')),
'isi' => $this->user->getUser(session()->id),
'aduan' => $this->model->getAduan(session()->id)
];
return view('aduan/index', $data);
}
}
public function view($id_aduan, $hasil = false)
{
if (session()->get('level') == 1 or session()->get('level') == 2) {
if ($hasil == 'belum') {
$view = 'viewadmin';
} elseif ($hasil == 'sudah') {
$view = 'view';
}
$getAduan = $this->model->getAduan(false, $id_aduan, false);
$x = $this->user->getUser($getAduan->id_user);
if (isset($getAduan)) {
$ket = [
'Periksa Data : ' . $getAduan->id_aduan,
'<li class="breadcrumb-item active"><a href="/aduan/index">List Aduan</a></li>',
'<li class="breadcrumb-item active">Periksa Data</li>'
];
$data = [
'title' => 'Periksa Data : ' . $getAduan->id_aduan,
'ket' => $ket,
'aduan' => $getAduan,
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id),
'penduduk' => $this->penduduk->getPenduduk($x->id_datauser)
];
return view('aduan/' . $view, $data);
} else {
session()->setFlashdata('warning_aduan', 'aduan Tidak Ditemukan.');
return redirect()->to(base_url() . 'aduan/index');
}
} elseif (session()->get('level') == 3) {
$ket = [
'View Aduan', '<li class="breadcrumb-item active"><a href="' . base_url() . '/aduan/index">List Aduan</a></li>',
'<li class="breadcrumb-item active">View Data</li>'
];
$data = [
'title' => 'View Aduan',
'ket' => $ket,
'link' => 'home',
'user' => $this->penduduk->getPenduduk(session()->get('id_datauser')),
'isi' => $this->user->getUser(session()->id),
'aduan' => $this->model->getAduan(false, $id_aduan)
];
return view('aduan/view', $data);
}
}
public function input()
{
$ket = [
'Tambah Aduan', '<li class="breadcrumb-item active"><a href="' . base_url() . '/aduan/index">List Aduan</a></li>',
'<li class="breadcrumb-item active">Tambah Data</li>'
];
$data = [
'title' => 'Tambah Aduan',
'ket' => $ket,
'link' => 'home',
'user' => $this->penduduk->getPenduduk(session()->get('id_datauser')),
'isi' => $this->user->getUser(session()->id),
];
return view('aduan/input', $data);
}
public function add()
{
$request = \Config\Services::request();
$file = $request->getFile('foto');
if ($file->getError() == 4) {
$nm = "no_image.png";
} else {
$nm = $file->getRandomName();
$file->move('aduan', $nm);
}
$data = array(
'aduan' => $request->getPost('aduan'),
'gambar' => $nm,
'tgl_aduan' => date('Y-m-d'),
'id_user' => session()->id,
'respon' => 'Belum ada respon'
);
$this->model->saveAduan($data);
session()->setFlashdata('pesan_aduan', 'Aduan berhasi ditambah.');
return redirect()->to(base_url() . '/aduan/index');
}
public function edit($id_aduan)
{
$getAduan = $this->model->getAduan(false, $id_aduan);
if (isset($getAduan)) {
$ket = [
'Edit Aduan', '<li class="breadcrumb-item active"><a href="' . base_url() . '/aduan/index">List Aduan</a></li>',
'<li class="breadcrumb-item active">Edit Data</li>'
];
$data = [
'title' => 'Edit Aduan',
'ket' => $ket,
'link' => 'home',
'aduan' => $getAduan,
'isi' => $this->user->getUser(session()->id),
'user' => $this->penduduk->getPenduduk(session()->get('id_datauser')),
];
return view('aduan/edit', $data);
} else {
session()->setFlashdata('warning_aduan', 'Data Aduan tidak ditemukan.');
return redirect()->to(base_url() . '/aduan/index');
}
}
public function update()
{
if (session()->get('level') == 1 or session()->get('level') == 2) {
$request = \Config\Services::request();
$id = $request->getPost('id_aduan');
$data = array(
'respon' => $request->getPost('respon'),
'tgl_respon' => date('Y-m-d'),
'ket' => 'Selesai'
);
$this->model->editAduan($data, $id);
session()->setFlashdata('pesan_aduan', 'Data Aduan berhasi diedit.');
return redirect()->to(base_url() . '/aduan/index');
} elseif (session()->get('level') == 3) {
$request = \Config\Services::request();
$id = $request->getPost('id_aduan');
$file = $request->getFile('foto');
if ($file->getError() == 4) {
$nm = $request->getPost('lama');
} else {
$nm = $file->getRandomName();
$file->move('aduan', $nm);
if ($request->getPost('lama') != 'no_image.png') {
unlink('aduan/' . $request->getPost('lama'));
}
}
$data = array(
'aduan' => $request->getPost('aduan'),
'gambar' => $nm,
'tgl_aduan' => date('Y-m-d'),
'id_user' => session()->id,
'respon' => 'Belum ada respon'
);
$this->model->editAduan($data, $id);
session()->setFlashdata('pesan_aduan', 'Data Aduan berhasi diedit.');
return redirect()->to(base_url() . '/aduan/index');
}
}
public function delete($id_aduan)
{
$getAduan = $this->model->getAduan($id_aduan);
if (isset($getAduan)) {
$this->model->hapusAduan($id_aduan);
session()->setFlashdata('danger_aduan', 'Data aduan Berhasi Dihapus.');
return redirect()->to(base_url() . '/aduan/index');
} else {
session()->setFlashdata('warning_aduan', 'Data aduan Tidak Ditemukan.');
return redirect()->to(base_url() . '/aduan/index');
}
}
public function hapusbanyak()
{
$request = \Config\Services::request();
$id_aduan = $request->getPost('id_aduan');
if ($id_aduan == null) {
session()->setFlashdata('warning_aduan', 'Data aduan Belum Dipilih, Silahkan Pilih Data Terlebih Dahulu.');
return redirect()->to(base_url() . '/aduan/index');
}
$jmldata = count($id_aduan);
for ($i = 0; $i < $jmldata; $i++) {
$this->model->hapusAduan($id_aduan[$i]);
}
session()->setFlashdata('pesan_aduan', 'Data aduan Berhasi Dihapus Sebanyak ' . $jmldata . ' Data.');
return redirect()->to(base_url() . '/aduan/index');
}
}
<file_sep>/app/Models/KeluargaModel.php
<?php
namespace App\Models;
use CodeIgniter\Model;
class KeluargaModel extends Model
{
protected $table = 'keluarga';
public function getKeluarga($id_keluarga = false)
{
if ($id_keluarga == false) {
return $this->orderBy('id_keluarga', 'DESC')->findAll();
} else {
return $this->getWhere(['id_keluarga' => $id_keluarga])->getRow();
}
}
public function saveKeluarga($data)
{
$builder = $this->db->table($this->table);
return $builder->insert($data);
}
public function editKeluarga($data, $id_keluarga)
{
$builder = $this->db->table($this->table);
$builder->where('id_keluarga', $id_keluarga);
return $builder->update($data);
}
public function hapusKeluarga($id_keluarga)
{
$builder = $this->db->table($this->table);
return $builder->delete(['id_keluarga' => $id_keluarga]);
}
public function id($input, $field)
{
return $this->getWhere([$field => $input])->getRow();
}
public function cek($no_kk, $nik_kepala)
{
return $this->where(['no_kk' => $no_kk])->where('nik_kepala', $nik_kepala)->get()->getRowArray();
}
}
<file_sep>/app/Views/web/berita.php
<?= $this->extend('web/template'); ?>
<?= $this->section('content'); ?>
<main id="main">
<div class="row">
<div class="col-md-9">
<section style="padding: 40px; background: #f8fcfd;">
<?php
foreach ($data as $data) {
?>
<div class="row h" style="word-wrap: break-word; padding: 10px;">
<?php if ($data['gambar'] != NULL and $data['gambar'] != 'no_image.png') { ?>
<div class="col-md-3 col-lg-3">
<img src="<?= base_url(); ?>/berita/<?= $data['gambar']; ?>" style="max-height: 100px; max-width: 200px;">
</div>
<?php } ?>
<div class="col-md-9 col-lg-6">
<a href="<?= base_url('/web/isi/' . $data['id_berita']) ?>" style="color: black;">
<p><b><?= $data['judul']; ?></b></p>
<?= substr($data['isi'], 0, 500); ?>
<p style="color: #061F2D;"> Baca Selengkapnya...</p>
</a>
</p>
</div>
</div>
<hr>
<?php } ?>
<?= $pager->links('data', 'bootstrap_pagination') ?>
</section>
</div>
<div class="col-md-3" style="margin-top: 40px; padding-right: 35px;">
<h5 align=" center"><b>Berita Terbaru</b></h5>
<hr>
<?php if ($berita == NULL) { ?>
<div class="row h" style="word-wrap: break-word; padding: 10px;">
Berita belum ada
</div>
<?php } ?>
<?php
foreach ($berita as $data) {
?>
<div class="row h" style="word-wrap: break-word; padding: 10px;">
<a href="<?= base_url('/web/isi/' . $data['id_berita']) ?>" style="color: black;">
<p><b><?= $data['judul']; ?></b></p>
<?= substr($data['isi'], 0, 50); ?>
<p style="color: #061F2D;"> Baca Selengkapnya...</p>
</a>
</div>
<hr>
<?php } ?>
</div>
</div>
</main>
<?= $this->endSection(); ?><file_sep>/app/Models/GaleriModel.php
<?php
namespace App\Models;
use CodeIgniter\Model;
class GaleriModel extends Model
{
protected $table = 'galeri';
public function getGaleri($id_galeri = false)
{
if ($id_galeri === false) {
return $this->orderBy('id_galeri', 'DESC')->findAll();
} else {
return $this->getWhere(['id_galeri' => $id_galeri])->getRow();
}
}
public function saveGaleri($data)
{
$builder = $this->db->table($this->table);
return $builder->insert($data);
}
public function editGaleri($data, $id_galeri)
{
$builder = $this->db->table($this->table);
$builder->where('id_galeri', $id_galeri);
return $builder->update($data);
}
public function hapusGaleri($id_galeri)
{
$builder = $this->db->table($this->table);
return $builder->delete(['id_galeri' => $id_galeri]);
}
public function gambar($jenis)
{
return $this->select('foto as x')->where('jenis', $jenis)->get()->getRow();
}
}
<file_sep>/app/Views/penduduk/rekap.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laporan Rekap Penduduk</title>
<link rel="SHORTCUT ICON" href="<?php echo base_url() ?>/aset/img/logo.png">
</head>
<body>
<h1>Jumlah Penduduk : <b><?= $p; ?></b></h1>
<table border="1" style="padding:10;">
<tr>
<td><b>Jumlah Laki - Laki</b></td>
<td><?= $lk; ?></td>
</tr>
<tr>
<td><b>Jumlah Perempuan</b></td>
<td><?= $pr; ?></td>
</tr>
</table>
<h1>Jumlah Penduduk Jorong Gantiang : <b><?= $p_g; ?></b></h1>
<table border="1" style="padding:10;">
<tr>
<td><b>Jumlah Laki - Laki</b></td>
<td><?= $lk_g; ?></td>
</tr>
<tr>
<td><b>Jumlah Perempuan</b></td>
<td><?= $pr_g; ?></td>
</tr>
</table>
<h1>Jumlah Penduduk Jorong Gunuang Rajo Utara : <b><?= $p_gru; ?></b></h1>
<table border="1" style="padding:10;">
<tr>
<td><b>Jumlah Laki - Laki</b></td>
<td><?= $lk_gru; ?></td>
</tr>
<tr>
<td><b>Jumlah Perempuan</b></td>
<td><?= $pr_gru; ?></td>
</tr>
</table>
</body>
</html><file_sep>/app/Controllers/Auth.php
<?php
namespace App\Controllers;
use App\Models\AuthModel;
use App\Models\PendudukModel;
use App\Models\KeluargaModel;
class Auth extends BaseController
{
public function __construct()
{
helper('form');
$this->model = new AuthModel();
$this->penduduk = new PendudukModel();
$this->keluarga = new KeluargaModel();
}
public function login()
{
$data = [
'title' => 'Login',
];
return view('auth/login', $data);
}
public function cek_login()
{
$request = \Config\Services::request();
$log = $request->getPost('login');
$pass = $request->getPost('password');
$cek_email = $this->model->login('email', $log);
$cek_telp = $this->model->login('telp', $log);
$cek_nik = $this->model->login('username', $log);
if ($cek_email != NULL and password_verify($pass, $cek_email['password'])) {
session()->set('log', true);
session()->set('level', $cek_email['level']);
session()->set('id_datauser', $cek_email['id_datauser']);
session()->set('foto', $cek_email['foto']);
session()->set('username', $cek_email['username']);
session()->set('email', $cek_email['email']);
session()->set('telp', $cek_email['telp']);
session()->set('id', $cek_email['id']);
return redirect()->to(base_url() . '/home/index');
} elseif ($cek_telp != NULL and password_verify($pass, $cek_telp['password'])) {
session()->set('log', true);
session()->set('level', $cek_telp['level']);
session()->set('id_datauser', $cek_telp['id_datauser']);
session()->set('foto', $cek_telp['foto']);
session()->set('username', $cek_telp['username']);
session()->set('email', $cek_telp['email']);
session()->set('telp', $cek_telp['telp']);
session()->set('id', $cek_telp['id']);
return redirect()->to(base_url() . '/home/index');
} elseif ($cek_nik != NULL and password_verify($pass, $cek_nik['password'])) {
session()->set('log', true);
session()->set('level', $cek_nik['level']);
session()->set('id_datauser', $cek_nik['id_datauser']);
session()->set('foto', $cek_nik['foto']);
session()->set('username', $cek_nik['username']);
session()->set('email', $cek_nik['email']);
session()->set('telp', $cek_nik['telp']);
session()->set('id', $cek_nik['id']);
return redirect()->to(base_url() . '/home/index');
} else {
session()->setFlashdata('error', 'Login gagal');
if ($request->getPost('log') == 'surat') {
return redirect()->to(base_url() . '/web/surat');
} else {
return redirect()->to(base_url() . '/auth/login');
}
}
}
public function logout()
{
session()->remove('log');
session()->remove('level');
session()->remove('id_datauser');
session()->remove('foto');
session()->remove('username');
session()->remove('email');
session()->remove('telp');
session()->setFlashdata('pesan_log', 'Logout sukses');
return redirect()->to(base_url() . '/auth/login');
}
}
<file_sep>/app/Views/user/edit.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<!-- Main content -->
<section class="content">
<?php if (session()->getFlashdata('error')) { ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('error'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php } ?>
<form method="post" action="<?= base_url('user/update'); ?>" enctype="multipart/form-data">
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-user mr-1"></i>
Data User
</h3>
</div>
<div class="container-fluid card-body">
<?= csrf_field(); ?>
<?php if ($level == 1 or $level == 2) { ?>
<div class="row mb-3">
<label for="id_datauser" class="col-sm-2 col-form-label">Data Perangkat</label>
<div class="col-sm-10">
<select class="form-control select2bs4" name="id_datauser" id="id_datauser" required required>
<option value="">Pilih Data Perangkat</option>
<?php
foreach ($data as $data) {
?>
<option <?php if ($datauser->id_datauser == $data['id_pemerintahan']) {
echo 'selected';
} ?> value="<?= $data['id_pemerintahan']; ?>"><?= $data['nama'] ?> - <?= $data['jabatan']; ?></option>
<?php } ?>
</select>
</div>
</div>
<?php } elseif ($level == 3) { ?>
<div class="row mb-3">
<label for="id_keluarga" class="col-sm-2 col-form-label">No KK</label>
<div class="col-sm-10">
<select onchange="nik()" class="form-control select2bs4" name="id_keluarga" id="id_keluarga" required>
<option value="">Pilih No KK</option>
<?php
foreach ($keluarga as $k) {
?>
<option <?php if ($kel->id_keluarga == $k['id_keluarga']) {
echo 'selected';
} ?> value="<?= $k['id_keluarga'] ?>"><?php echo $k['no_kk'] ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row mb-3">
<label for="id_penduduk" class="col-sm-2 col-form-label">NIK</label>
<div class="col-sm-10">
<select onchange="ambilNama()" class="form-control select2bs4" name="id_penduduk" id="id_penduduk" required>
<option value="">Pilih NIK</option>
<?php
foreach ($data as $p) {
?>
<option <?php if ($datauser->id_datauser == $p['id_penduduk']) {
echo 'selected';
} ?> value="<?= $p['id_penduduk'] ?>"><?php echo $p['nik'] ?> - <?= $p['nama']; ?></option>
<?php } ?>
</select>
</div>
</div>
<?php } ?>
<div class="row mb-3">
<label for="level" class="col-sm-2 col-form-label">Data Role</label>
<div class="col-sm-10">
<select class="form-control select2bs4" name="level" id="level" required required>
<option value="">Pilih Data Role</option>
<?php
$level = [
'Super Admin', 'Admin', 'Warga'
];
for ($i = 0; $i < count($level); $i++) {
?>
<option <?php if ($datauser->level == ($i + 1)) {
echo 'selected';
} ?> value="<?= ($i + 1); ?>"><?= $level[$i] ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row mb-3">
<label for="username" class="col-sm-2 col-form-label">Username</label>
<div class="col-sm-10">
<input value="<?= $datauser->username; ?>" autocomplete="off" type="text" placeholder="Masukkan Username" class="form-control" id="username" name="username" required>
</div>
</div>
<div class="row mb-3">
<label for="email" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input value="<?= $datauser->email; ?>" autocomplete="off" type="email" placeholder="Masukkan Email" class="form-control" id="email" name="email">
</div>
</div>
<div class="row mb-3">
<label for="pass" class="col-sm-2 col-form-label">Reset Password</label>
<div class="col-sm-10">
<input autocomplete="off" type="password" minlength="8" placeholder="<PASSWORD> Baru" class="form-control" id="pass" name="pass">
</div>
</div>
<div class="row mb-3">
<label for="telp" class="col-sm-2 col-form-label">Nomor Telepon</label>
<div class="col-sm-10">
<input value="<?= $datauser->telp; ?>" autocomplete="off" type="text" placeholder="Masukkan Nomor Telepon" class="form-control" id="telp" name="telp">
</div>
</div>
<div class="row mb-3">
<label for="foto" class="col-sm-2 col-form-label label">Foto</label>
<div class="col-sm-1">
<img class="img-thumbnail img-preview" src="<?= base_url(); ?>/user/<?= $datauser->foto; ?>" alt="">
</div>
<div class="col-sm-9">
<div class="custom-file">
<input type="file" class="custom-file-input" id="fotoo" name="foto" onchange="previewImg()">
<input type="hidden" name="lama" value="<?= $datauser->foto; ?>">
<p style="color: red">Ekstensi yang diperbolehkan .png | .jpg | .jpeg (Ukuran Max 10 MB dan Nama File Sesuai Nama)</p>
<label for="foto" class="custom-file-label"><?= $datauser->foto; ?></label>
</div>
</div>
</div>
<input type="hidden" name="id" id="id" value="<?= $datauser->id; ?>">
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</section>
<!-- /.content -->
<!-- /.content -->
<?= $this->endSection(); ?><file_sep>/app/Controllers/Keluarga.php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\KeluargaModel;
use App\Models\IsiModel;
use App\Models\PendudukModel;
use App\Models\DataModel;
use App\Models\AuthModel;
use App\Models\AlamatModel;
use App\Models\PerangkatModel;
class Keluarga extends Controller
{
public function __construct()
{
helper('form');
$this->model = new KeluargaModel();
$this->isi = new IsiModel();
$this->penduduk = new PendudukModel();
$this->data = new DataModel();
$this->user = new AuthModel();
$this->alm = new AlamatModel();
$this->perangkat = new PerangkatModel();
}
public function index()
{
$kel = $this->model->getKeluarga();
$x = $kel;
for ($i = 0; $i < count($kel); $i++) {
$x[$i]['id_keluarga'] = $kel[$i]['id_keluarga'];
$x[$i]['no_kk'] = $kel[$i]['no_kk'];
$x[$i]['nik_kepala'] = $kel[$i]['nik_kepala'];
$p = $this->penduduk->id($kel[$i]['nik_kepala'], 'nik');
if ($p != NULL) {
$x[$i]['nama'] = $p->nama;
} else {
$x[$i]['nama'] = NULL;
}
}
$ket = [
'Data Keluarga', '<li class="breadcrumb-item active"><a href="/keluarga/index">Data Keluarga</a></li>'
];
$data = [
'title' => 'Data Keluarga',
'ket' => $ket,
'keluarga' => $x,
'link' => 'home',
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('keluarga/index', $data);
}
public function input()
{
$ket = [
'Tambah Data Keluarga',
'<li class="breadcrumb-item active"><a href="/keluarga/index">Data Keluarga</a></li>',
'<li class="breadcrumb-item active">Tambah Data</li>'
];
$data = [
'title' => 'Tambah Data Keluarga',
'ket' => $ket,
'agama' => $this->isi->getIsi(false, 'agama'),
'pendidikan' => $this->isi->getIsi(false, 'pendidikan'),
'pekerjaan' => $this->isi->getIsi(false, 'pekerjaan'),
'status_kawin' => $this->isi->getIsi(false, 'status_kawin'),
'link' => 'home',
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('keluarga/input', $data);
}
public function view($id_keluarga)
{
$getKeluarga = $this->model->getKeluarga($id_keluarga);
$ket = [
'View Data Keluaga : ' . $getKeluarga->no_kk, '<li class="breadcrumb-item active"><a href="/keluarga/index">Data Keluarga</a></li>',
'<li class="breadcrumb-item active">View Data</li>'
];
$isi = $this->isi->getIsi(false, 'status_hub');
$x = 0;
for ($i = 0; $i < count($isi); $i++) {
if ($this->penduduk->id_array($isi[$i]['nama'], 'status_hub') != NULL) {
$p = $this->penduduk->id_array($getKeluarga->id_keluarga, 'id_keluarga');
$anggota = $p;
$x++;
} else {
continue;
}
}
$data = [
'title' => 'View Data Keluaga : ' . $getKeluarga->no_kk,
'ket' => $ket,
'jml' => $this->penduduk->jml($getKeluarga->id_keluarga, 'id_keluarga'),
'keluarga' => $getKeluarga,
'penduduk' => $this->penduduk->id($getKeluarga->nik_kepala, 'nik'),
'data' => $this->data->getData(),
'anggota' => $anggota,
'link' => 'home',
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id),
'alm' => $this->alm->getAlamat(),
];
return view('keluarga/view', $data);
}
public function add()
{
$request = \Config\Services::request();
$validation = \Config\Services::validation();
$validation->setRules([
'no_kk' => [
'label' => 'no_kk',
'rules' => 'is_unique[keluarga.no_kk]|required|numeric',
'errors' => [
'is_unique' => 'No Kartu Keluarga sudah terdaftar',
'required' => 'No Kartu Keluarga harus diisi',
'numeric' => 'No Kartu Keluarga harus angka'
]
],
'nik' => [
'label' => 'nik_kepala',
'rules' => 'is_unique[keluarga.nik_kepala]|required|numeric',
'errors' => [
'is_unique' => 'NIK sudah terdaftar',
'required' => 'NIK harus diisi',
'numeric' => 'NIK harus angka'
]
],
]);
if (!$validation->withRequest($request)->run()) {
session()->setFlashdata('error', $validation->listErrors());
return redirect()->to('/keluarga/input');
}
$data = array(
'no_kk' => $request->getPost('no_kk'),
'nik_kepala' => $request->getPost('nik'),
'alamat' => $request->getPost('alamat'),
'tgl_update' => date('Y-m-d')
);
$this->model->saveKeluarga($data);
$id = $this->model->id($request->getPost('no_kk'), 'no_kk');
$datakepala = array(
'id_keluarga' => $id->id_keluarga,
'nik' => $request->getPost('nik'),
'nama' => $request->getPost('nama'),
'tpt_lahir' => $request->getPost('tpt_lahir'),
'tgl_lahir' => $request->getPost('tgl_lahir'),
'jekel' => $request->getPost('jekel'),
'agama' => $request->getPost('agama'),
'kerja' => $request->getPost('kerja'),
'kwn' => $request->getPost('kwn'),
'goldar' => $request->getPost('goldar'),
'ket_tinggal' => 'Permanen',
'status_kawin' => $request->getPost('status_kawin'),
'status_kk' => $request->getPost('status_kk'),
'pendidikan' => $request->getPost('pendidikan'),
'nm_ayah' => $request->getPost('nm_ayah'),
'nik_ayah' => $request->getPost('nik_ayah'),
'nm_ibu' => $request->getPost('nm_ibu'),
'nik_ibu' => $request->getPost('nik_ibu'),
'paspor' => $request->getPost('paspor'),
'kitap' => $request->getPost('kitap'),
'ket' => 'Hidup',
'tgl_update' => date('Y-m-d')
);
$this->penduduk->savePenduduk($datakepala);
return redirect()->to(base_url() . '/keluarga/index');
}
public function edit($id_keluarga)
{
$getKeluarga = $this->model->getKeluarga($id_keluarga);
if (isset($getKeluarga)) {
$ket = [
'Edit Data : ' . $getKeluarga->no_kk,
'<li class="breadcrumb-item active"><a href="/keluarga/index">Data Keluarga</a></li>',
'<li class="breadcrumb-item active">Edit Data</li>'
];
$data = [
'title' => 'Edit Data : ' . $getKeluarga->no_kk,
'ket' => $ket,
'keluarga' => $getKeluarga,
'penduduk' => $this->penduduk->id($getKeluarga->nik_kepala, 'nik'),
'agama' => $this->isi->getIsi(false, 'agama'),
'pendidikan' => $this->isi->getIsi(false, 'pendidikan'),
'pekerjaan' => $this->isi->getIsi(false, 'pekerjaan'),
'status_kawin' => $this->isi->getIsi(false, 'status_kawin'),
'link' => 'home',
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('keluarga/edit', $data);
} else {
session()->setFlashdata('warning_keluarga', 'No KK ' . $getKeluarga->no_kk . ' Tidak Ditemukan.');
return redirect()->to(base_url() . '/keluarga/index');
}
}
public function update()
{
$request = \Config\Services::request();
$validation = \Config\Services::validation();
$id_keluarga = $request->getPost('id_keluarga');
$m = $this->model->getKeluarga($id_keluarga);
if ($request->getPost('no_kk') != $m->no_kk) {
$validation = \Config\Services::validation();
$validation->setRules([
'no_kk' => [
'label' => 'no_kk',
'rules' => 'is_unique[keluarga.no_kk]|required|numeric',
'errors' => [
'is_unique' => 'No Kartu Keluarga sudah terdaftar',
'required' => 'No Kartu Keluarga harus diisi',
'numeric' => 'No Kartu Keluarga harus angka'
]
],
]);
if (!$validation->withRequest($request)->run()) {
session()->setFlashdata('error', $validation->listErrors());
return redirect()->to('/keluarga/edit/' . $id_keluarga);
}
}
if ($request->getPost('nik') != $m->nik_kepala) {
$validation = \Config\Services::validation();
$validation->setRules([
'nik' => [
'label' => 'nik_kepala',
'rules' => 'is_unique[keluarga.nik_kepala]|required|numeric',
'errors' => [
'is_unique' => 'NIK sudah terdaftar',
'required' => 'NIK harus diisi',
'numeric' => 'NIK harus angka'
]
],
]);
if (!$validation->withRequest($request)->run()) {
session()->setFlashdata('error', $validation->listErrors());
return redirect()->to('/keluarga/edit/' . $id_keluarga);
}
}
$data = array(
'no_kk' => $request->getPost('no_kk'),
'nik_kepala' => $request->getPost('nik'),
'alamat' => $request->getPost('alamat')
);
$this->model->editKeluarga($data, $id_keluarga);
$id = $this->penduduk->id($request->getPost('nik'), 'nik');
$datakepala = array(
'id_keluarga' => $id_keluarga,
'nik' => $request->getPost('nik'),
'nama' => $request->getPost('nama'),
'tpt_lahir' => $request->getPost('tpt_lahir'),
'tgl_lahir' => $request->getPost('tgl_lahir'),
'jekel' => $request->getPost('jekel'),
'agama' => $request->getPost('agama'),
'kerja' => $request->getPost('kerja'),
'kwn' => $request->getPost('kwn'),
'goldar' => $request->getPost('goldar'),
'status_kawin' => $request->getPost('status_kawin'),
'status_hub' => $request->getPost('status_hub'),
'pendidikan' => $request->getPost('pendidikan'),
'nm_ayah' => $request->getPost('nm_ayah'),
'nik_ayah' => $request->getPost('nik_ayah'),
'nm_ibu' => $request->getPost('nm_ibu'),
'nik_ibu' => $request->getPost('nik_ibu'),
'paspor' => $request->getPost('paspor'),
'kitap' => $request->getPost('kitap'),
'ket' => 'Hidup',
'tgl_update' => date('Y-m-d')
);
$this->penduduk->editPenduduk($datakepala, $id->id_penduduk);
session()->setFlashdata('pesan_keluarga', 'Data Keluarga Berhasi Diedit.');
return redirect()->to(base_url() . '/keluarga/index');
}
public function delete($id_keluarga)
{
$getKeluarga = $this->model->getKeluarga($id_keluarga);
if (isset($getKeluarga)) {
$m = $this->penduduk->id($id_keluarga, 'id_keluarga');
$n = $this->penduduk->jml($id_keluarga, 'id_keluarga');
if ($m == NULL or $n->x == 1) {
$id = $this->penduduk->id($getKeluarga->nik_kepala, 'nik');
$data = $this->penduduk->getPenduduk($id->id_penduduk);
$this->penduduk->hapusPenduduk($data->id_penduduk);
$this->model->hapusKeluarga($id_keluarga);
session()->setFlashdata('danger_keluarga', 'Data keluarga ' . $id_keluarga . ' berhasi dihapus.');
return redirect()->to(base_url() . '/keluarga/index');
} else {
session()->setFlashdata('warning_keluarga', 'Data keluarga tidak bisa dihapus karena data dipakai pada tabel penduduk.');
return redirect()->to(base_url() . '/keluarga/index');
}
} else {
session()->setFlashdata('warning_keluarga', 'Data Keluarga ' . $id_keluarga . ' Tidak Ditemukan.');
return redirect()->to(base_url() . '/keluarga/index');
}
}
public function hapusbanyak()
{
$request = \Config\Services::request();
$nokk = $request->getPost('id_keluarga');
if ($nokk == null) {
session()->setFlashdata('warning_keluarga', 'Data Keluarga Belum Dipilih, Silahkan Pilih Data Terlebih Dahulu.');
return redirect()->to('index');
}
$jmldata = count($nokk);
$x = 0;
$y = 0;
for ($i = 0; $i < $jmldata; $i++) {
$getKeluarga = $this->model->getKeluarga($nokk[$i]);
$m = $this->penduduk->id($nokk[$i], 'id_keluarga');
$n = $this->penduduk->jml($nokk[$i], 'id_keluarga');
if ($m == NULL or $n->x == 1) {
$id = $this->penduduk->id($getKeluarga->nik_kepala, 'nik');
$data = $this->penduduk->getPenduduk($id->id_penduduk);
$this->penduduk->hapusPenduduk($data->id_penduduk);
$this->model->hapusKeluarga($nokk[$i]);;
$x++;
} else {
$y++;
}
}
if ($x != 0 and $y == 0) {
session()->setFlashdata('pesan_keluarga', $x . ' Data berhasi dihapus.');
return redirect()->to(base_url() . '/keluarga/index');
} elseif ($x == 0 and $y != 0) {
session()->setFlashdata('warning_keluarga', $y . ' Data tidak bisa dihapus karena ada keluarga.');
return redirect()->to(base_url() . '/keluarga/index');
} elseif ($x != 0 and $y != 0) {
session()->setFlashdata('warning_keluarga', $x . ' Data berhasi dihapus dan ' . $y . ' data tidak bisa dihapus karena ada kepala keluarga.');
return redirect()->to(base_url() . '/keluarga/index');
} else {
session()->setFlashdata('warning_keluarga', 'Data tidak bisa dihapus karena ada keluarga.');
return redirect()->to(base_url() . '/keluarga/index');
}
}
public function import()
{
$ket = [
'Import Data Keluarga', '<li class="breadcrumb-item active"><a href="/keluarga/index">Data Keluarga</a></li>',
'<li class="breadcrumb-item active">Import Data</li>'
];
$data = [
'title' => 'Import Data Penduduk',
'ket' => $ket,
'link' => 'home',
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('keluarga/import', $data);
}
public function proses()
{
$request = \Config\Services::request();
$file = $request->getFile('file_excel');
$ext = $file->getClientExtension();
if ($ext == 'xls') {
$render = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
} elseif ($ext == 'xlsx') {
$render = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
} else {
session()->setFlashdata('warning_keluarga', 'Ekstensi File Salah, Silahkan Pilih File Ber-ekstensi Excel.');
return redirect()->to('bprn/import');
}
$spreadsheet = $render->load($file);
$sheet = $spreadsheet->getActiveSheet()->toArray();
foreach ($sheet as $x => $excel) {
if ($x == 0) {
continue;
}
$nokk = $this->model->cek($excel[1], $excel[2]);
if ($nokk != NULL) {
if ($excel[1] == $nokk['no_kk'] or $excel[2] == $nokk['nik_kepala']) {
continue;
}
}
if ($excel[6] == 'L' or $excel[6] == 'LAKI-LAKI') {
$excel[6] = 'Laki - Laki';
} elseif ($excel[6] == 'P' or $excel[6] == 'PEREMPUAN') {
$excel[6] = 'Perempuan';
}
if ($excel[2] == '-' or $excel[2] == '0000000000000000') {
$nik = '';
} else {
$nik = $excel[2];
}
$data = array(
'no_kk' => $excel[1],
'nik_kepala' => $nik,
'alamat' => $excel[8],
'tgl_update' => date('Y-m-d')
);
$this->model->saveKeluarga($data);
$id = $this->model->id($excel[1], 'no_kk');
$datakepala = array(
'id_keluarga' => $id->id_keluarga,
'nik' => $nik,
'nama' => $excel[3],
'tpt_lahir' => $excel[4],
'tgl_lahir' => $excel[5],
'jekel' => $excel[6],
'agama' => $excel[7],
'kerja' => $excel[9],
'kwn' => $excel[10],
'goldar' => $excel[11],
'status_kawin' => $excel[12],
'status_hub' => 'Kepala Keluarga',
'pendidikan' => $excel[13],
'nm_ayah' => $excel[14],
'nik_ayah' => $excel[15],
'nm_ibu' => $excel[16],
'nik_ibu' => $excel[17],
'paspor' => $excel[18],
'kitap' => $excel[19],
'ket' => 'Hidup',
'tgl_update' => date('Y-m-d')
);
$this->penduduk->savePenduduk($datakepala);
}
session()->setFlashdata('pesan_keluarga', 'Data Badan Permusyawaratan Rakyat Nagari (BPRN) Berhasi Diimport.');
return redirect()->to('/keluarga');
}
}
<file_sep>/app/Views/berita/view.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<!-- Main content -->
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-user-friends mr-1"></i>
View Data : <?= $berita->judul; ?>
</h3>
<div class="card-tools">
<ul class="nav nav-pills ml-auto">
<li class="nav-item">
<button type="button" style="margin-left: 10px;" class="btn btn-success">
<a href="<?php echo base_url('berita/edit/' . $berita->id_berita); ?>" style="color: white;">
<i class="far fa-plus-square"> Edit Data</i>
</a>
</button>
</li>
</ul>
</div>
</div><!-- /.card-header -->
<div class="row card-body" align="center">
<h3><b><?= $berita->judul; ?></b></h3>
<?php if ($berita->gambar != NULL and $berita->gambar != 'no_image.png') { ?>
<div>
<img width="30%" src="<?= base_url(); ?>/berita/<?= $berita->gambar; ?>" alt=" Gambar <?= $berita->judul; ?>">
</div>
<?php } ?>
<div class="dropdown-divider"></div>
<div class="col" align="left">
Penulis : <b><i><?= $berita->penulis; ?></i></b>
</div>
<div class="col" align="right">
Tanggal Update : <b><?= date('d M Y', strtotime($berita->tgl_update)); ?></b>
</div>
<div class="dropdown-divider"></div>
<div style="text-align: justify;">
<?= $berita->isi; ?>
</div>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</div>
<!-- /.container-fluid -->
</section>
<!-- /.content -->
<!-- /.content -->
<?= $this->endSection(); ?><file_sep>/app/Views/template/index.php
<?= $this->include('template/link_css'); ?>
<?= $this->include('template/header'); ?>
<aside class="main-sidebar sidebar-dark-primary elevation-4">
<a href="<?= base_url(); ?>/home" class="brand-link">
<img src="<?= base_url(); ?>/aset/img/logo.png" alt="<NAME>" class="brand-image img-circle elevation-3" style="opacity: .8">
<span class="brand-text font-weight-light"><b><NAME></b></span>
</a>
<div class="sidebar">
<nav class="mt-2">
<ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false">
<?= $this->include('template/sidebar_pemerintah'); ?>
<?= $this->include('template/sidebar_admin'); ?>
<?= $this->include('template/sidebar_warga'); ?>
<li class="nav-item">
<a href="<?= base_url(); ?>/auth/logout" class="nav-link">
<i class="nav-icon fas fas fa-sign-out-alt"></i>
<p>
Logout
</p>
</a>
</li>
</ul>
</nav>
</div>
</aside>
<script>
window.setTimeout(function() {
$(".alert").fadeTo(500, 0).slideUp(500, function() {
$(this).remove();
});
}, 3000);
</script>
<div class="content-wrapper">
<div class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1 class="m-0"><?= $ket[0]; ?></h1>
</div>
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item"><a href="<?= base_url(); ?>/home/index">
<?php
if (session()->get('level') == 1 or session()->get('level') == 2) {
echo 'Beranda';
} else {
echo ' My Profile';
} ?>
</a></li>
<?php
for ($i = 1; $i < count($ket); $i++) {
?>
<?= $ket[$i]; ?>
<?php } ?>
</ol>
</div>
</div>
</div>
</div>
<?= $this->renderSection('content'); ?>
</div>
<?= $this->include('template/footer'); ?>
<?= $this->include('template/link_js'); ?>
<?php if (isset($link) and $link == 'chart') { ?>
<?= $this->include('template/chart'); ?>
<?php } ?>
<?= $this->include('template/form'); ?>
<?= $this->include('template/ambil_data'); ?><file_sep>/app/Controllers/Lahir.php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\KeluargaModel;
use App\Models\IsiModel;
use App\Models\PendudukModel;
use App\Models\PerangkatModel;
use App\Models\AuthModel;
class Lahir extends Controller
{
protected $model, $isi, $keluarga, $data;
public function __construct()
{
helper('form');
$this->keluarga = new KeluargaModel();
$this->isi = new IsiModel();
$this->model = new PendudukModel();
$this->perangkat = new PerangkatModel();
$this->user = new AuthModel();
}
public function index()
{
$ket = [
'Data Kelahiran', '<li class="breadcrumb-item active"><a href="/lahir/index">Data Kelahiran</a></li>'
];
$data = [
'title' => 'Data Kelahiran',
'ket' => $ket,
'penduduk' => $this->model->lahir(),
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('lahir/index', $data);
}
public function input()
{
$ket = [
'Tambah Data Kelahiran',
'<li class="breadcrumb-item active"><a href="/lahir/index">Data Kelahiran</a></li>',
'<li class="breadcrumb-item active">Tambah Data</li>'
];
$data = [
'title' => 'Tambah Data Kelahiran',
'ket' => $ket,
'no_kk' => $this->keluarga->getKeluarga(),
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('lahir/input', $data);
}
public function view($id_penduduk)
{
$lahir = $this->model->lahir($id_penduduk);
$ket = [
'View Data Kelahiran : ' . $lahir->nik, '<li class="breadcrumb-item active"><a href="/lahir/index">Data Kelahiran</a></li>',
'<li class="breadcrumb-item active">View Data</li>'
];
$data = [
'title' => 'View Data Kelahiran : ' . $lahir->nik,
'ket' => $ket,
'penduduk' => $lahir,
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('lahir/view', $data);
}
public function add()
{
$request = \Config\Services::request();
$data = array(
'id_keluarga' => $request->getPost('id_keluarga'),
'nama' => $request->getPost('nama'),
'tpt_lahir' => $request->getPost('tpt_lahir'),
'tgl_lahir' => $request->getPost('tgl_lahir'),
'jekel' => $request->getPost('jekel'),
'kerja' => 'Belum/Tidak Bekerja',
'kwn' => 'WNI',
'status_kawin' => 'Belum Kawin',
'status_hub' => 'Anak',
'pendidikan' => 'Tidak/Belum Sekolah',
'nm_ayah' => $request->getPost('nm_ayah'),
'nik_ayah' => $request->getPost('nik_ayah'),
'nm_ibu' => $request->getPost('nm_ibu'),
'nik_ibu' => $request->getPost('nik_ibu'),
'ket' => 'Hidup',
'tgl_update' => date('Y-m-d')
);
$this->model->savePenduduk($data);
session()->setFlashdata('pesan_lahir', 'Data kelahiran berhasil ditambahkan.');
return redirect()->to('/lahir/index');
}
public function ortu($id_keluarga)
{
$data = $this->model->id_array($id_keluarga, 'id_keluarga');
$json = array();
foreach ($data as $kk) {
if ($kk['status_hub'] == 'Kepala Keluarga' or $kk['status_hub'] == 'Suami') {
$json['nm_ayah'] = $kk['nama'];
$json['nik_ayah'] = $kk['nik'];
} elseif ($kk['status_hub'] == 'Istri') {
$json['nm_ibu'] = $kk['nama'];
$json['nik_ibu'] = $kk['nik'];
}
}
return $this->response->setJson($json);
}
public function edit($id_penduduk)
{
$lahir = $this->model->lahir($id_penduduk);
if (isset($lahir)) {
$ket = [
'Edit Data : ' . $lahir->no_kk,
'<li class="breadcrumb-item active"><a href="/lahir/index">Data Kelahiran</a></li>',
'<li class="breadcrumb-item active">Edit Data</li>'
];
$data = [
'title' => 'Edit Data : ' . $lahir->no_kk,
'ket' => $ket,
'penduduk' => $lahir,
'no_kk' => $this->keluarga->getKeluarga(),
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('lahir/edit', $data);
} else {
session()->setFlashdata('warning_lahir', 'No KK ' . $lahir->no_kk . ' Tidak Ditemukan.');
return redirect()->to('/lahir/index');
}
}
public function update()
{
$request = \Config\Services::request();
$id_penduduk = $request->getPost('id_penduduk');
$data = array(
'id_keluarga' => $request->getPost('id_keluarga'),
'nama' => $request->getPost('nama'),
'tpt_lahir' => $request->getPost('tpt_lahir'),
'tgl_lahir' => $request->getPost('tgl_lahir'),
'jekel' => $request->getPost('jekel'),
'kerja' => 'Belum/Tidak Bekerja',
'kwn' => 'WNI',
'status_kawin' => 'Belum Kawin',
'status_hub' => 'Anak',
'pendidikan' => 'Tidak/Belum Sekolah',
'nm_ayah' => $request->getPost('nm_ayah'),
'nik_ayah' => $request->getPost('nik_ayah'),
'nm_ibu' => $request->getPost('nm_ibu'),
'nik_ibu' => $request->getPost('nik_ibu'),
'ket' => 'Hidup',
'tgl_update' => date('Y-m-d')
);
$this->model->editPenduduk($data, $id_penduduk);
session()->setFlashdata('pesan_lahir', 'Data Kelahiran Berhasi Diedit.');
return redirect()->to('lahir/index');
}
public function delete($id_penduduk)
{
$lahir = $this->model->lahir($id_penduduk);
if (isset($lahir)) {
if ($lahir->status_hub != 'Kepala Keluarga') {
$this->model->hapusPenduduk($id_penduduk);
session()->setFlashdata('danger_lahir', 'Data Kelahiran ' . $id_penduduk . ' berhasi dihapus.');
return redirect()->to('/lahir/index');
} else {
session()->setFlashdata('warning_lahir', 'Data Kelahiran tidak bisa dihapus karena kepala keluarga.');
return redirect()->to('/lahir/index');
}
} else {
session()->setFlashdata('warning_lahir', 'Data Kelahiran ' . $id_penduduk . ' Tidak Ditemukan.');
return redirect()->to('/lahir/index');
}
}
}
<file_sep>/app/Views/auth/login.php
<?= $this->extend('auth/template'); ?>
<?= $this->section('content'); ?>
<div class="container">
<!-- Outer Row -->
<div class="row justify-content-center">
<div class="col-md-10 col-lg-6">
<div class="card o-hidden border-0 shadow-lg my-5">
<div class="card-body p-0">
<!-- Nested Row within Card Body -->
<div class="row">
<div class="col-lg">
<div class="p-5">
<div class="text-center">
<h1 class="h4 text-gray-900 mb-4"><?= $title; ?></h1>
</div>
<?php if (session()->getFlashdata('error')) { ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
<?= session()->getFlashdata('error'); ?>
</div>
<?php } ?>
<form class="user" action="<?= base_url() ?>/auth/cek_login" method="post">
<?= csrf_field() ?>
<div class="form-group">
<input required type="text" class="form-control form-control-user" name="login" placeholder="Masukkan NIK / No Telepon / Email">
</div>
<div class="form-group">
<input required type="<PASSWORD>" class="form-control form-control-user" name="password" placeholder="<PASSWORD>">
</div>
<button type="submit" class="btn btn-primary btn-user btn-block">
<?= $title; ?>
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<?= $this->endSection(); ?><file_sep>/app/Views/beranda/index.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-lg-3 col-6">
<div class="small-box bg-info">
<div class="inner">
<h3><?= $penduduk; ?></h3>
<p>Penduduk</p>
</div>
<div class="icon">
<i class="fas fa-users"></i>
</div>
<a href="<?= base_url(); ?>/penduduk/index" class="small-box-footer">More info <i class="fas fa-arrow-circle-right"></i></a>
</div>
</div>
<div class="col-lg-3 col-6">
<div class="small-box bg-success">
<div class="inner">
<h3><?= $keluarga; ?></h3>
<p>Kepala Keluarga</p>
</div>
<div class="icon">
<i class="fas fa-user-friends"></i>
</div>
<a href="<?= base_url(); ?>/keluarga/index" class="small-box-footer">More info <i class="fas fa-arrow-circle-right"></i></a>
</div>
</div>
<div class="col-lg-3 col-6">
<div class="small-box bg-warning" style="height: 141px;">
<div class="inner">
<h3><?= $lk; ?></h3>
<p>Laki - Laki</p>
</div>
<div class="icon">
<i class="fas fa-user"></i>
</div>
</div>
</div>
<div class="col-lg-3 col-6">
<div class="small-box bg-danger" style="height: 141px;">
<div class="inner">
<h3><?= $pr; ?></h3>
<p>Perempuan</p>
</div>
<div class="icon">
<i class="fas fa-user"></i>
</div>
</div>
</div>
<div class="col-md-6">
<div class="card card-danger">
<div class="card-header">
<h3 class="card-title" style="padding:5px">
Penduduk
</h3>
<div class="card-tools" style="padding:5px">
<ul class="nav nav-pills ml-auto">
<li class="nav-item">
<a class="nav-link active" href="#jorong" data-toggle="tab">Jorong</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#jekel_g" data-toggle="tab">Jekel Gantiang</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#jekel_gru" data-toggle="tab">Jekel Gunuang Rajo Utara</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#umur" data-toggle="tab">Umur</a>
</li>
</ul>
</div>
</div>
<div class="card-body">
<div class="tab-content p-0">
<div class="chart tab-pane active" id="jorong" style="position: relative; height: 300px;">
<canvas id="pc_jorong" height="300" style="height: 300px;"></canvas>
</div>
<div class="chart tab-pane " id="jekel_g" style="position: relative; height: 300px;">
<canvas id="pc_jekel_g" height="300" style="height: 300px;"></canvas>
</div>
<div class="chart tab-pane " id="jekel_gru" style="position: relative; height: 300px;">
<canvas id="pc_jekel_gru" height="300" style="height: 300px;"></canvas>
</div>
<div class="chart tab-pane" id="umur" style="position: relative; height: 300px;">
<canvas id="bc_umur" height="300" style="height: 300px;"></canvas>
</div>
</div>
</div>
</div>
<div class="card card-warning">
<div class="card-header">
<h3 class="card-title" style="padding:5px">Aduan</h3>
</div>
<div class="card-body">
<canvas id="bc_aduan" style="min-height: 305px; height: 305px; max-height: 305px; max-width: 100%;"></canvas>
</div>
</div>
</div>
<div class="col-md-6">
<div class="card card-success">
<div class="card-header">
<h3 class="card-title" style="padding:5px">
Grafik Penduduk
</h3>
<div class="card-tools" style="padding:5px">
<ul class="nav nav-pills ml-auto">
<li class="nav-item">
<a class="nav-link active" href="#rubah" data-toggle="tab">Perubahan Penduduk</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#banding" data-toggle="tab">Kelahiran & Kematian</a>
</li>
</ul>
</div>
</div>
<div class="card-body">
<div class="tab-content p-0">
<div class="chart tab-pane active" id="rubah" style="position: relative; height: 300px;">
<canvas id="bc_rubah" height="300" style="height: 300px;"></canvas>
</div>
<div class="chart tab-pane" id="banding" style="position: relative; height: 300px;">
<canvas id="bc_banding" height="300" style="height: 300px;"></canvas>
</div>
</div>
</div>
</div>
<div class="card card-info">
<div class="card-header">
<h3 class="card-title" style="padding:5px">Permohonan Surat</h3>
</div>
<div class="card-body">
<canvas id="bc_mohon" style="min-height: 305px; height: 305px; max-height: 305px; max-width: 100%;"></canvas>
</div>
</div>
</div>
</div>
</div>
</section>
<?= $this->endSection(); ?><file_sep>/app/Views/template/header.php
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
<!-- Preloader -->
<div class="preloader flex-column justify-content-center align-items-center">
<img class="animation__shake" src="<?= base_url(); ?>/aset/img/logo.png" alt="AdminLTELogo" height="200" width="200">
</div>
<!-- Navbar -->
<nav class="main-header navbar navbar-expand navbar-white navbar-light">
<!-- Left navbar links -->
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" data-widget="pushmenu" href="#" role="button"><i class="fas fa-bars"></i></a>
</li>
<li class="nav-item d-none d-sm-inline-block">
<a href="<?= base_url(); ?>/home" class="nav-link">Sistem Informasi Nagari</a>
</li>
</ul>
<!-- Right navbar links -->
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<div class="user-panel d-flex">
<div class="image">
<?php if (session()->get('id_datauser') != 0) { ?>
<img src="<?= base_url(); ?>/<?php if (session()->level == 3) {
echo 'penduduk';
} else {
echo 'perangkat';
} ?>/<?= $isi->foto; ?>" class="img-circle elevation-1" alt="User Image">
<?php } else { ?>
<img src="<?= base_url(); ?>/aset/img/default.svg" class="img-circle elevation-1" alt="User Image">
<?php } ?>
</div>
</div>
</li>
<li class="nav-item dropdown">
<a style="margin-right: 10px;" id="dropdownSubMenu1" href="#" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" class="nav-link dropdown-toggle">
<?php if (session()->get('id_datauser') != 0) {
echo $user->nama;
} else {
echo 'Super Admin';
} ?>
</a>
<ul aria-labelledby="dropdownSubMenu1" class="dropdown-menu border-0 shadow">
<li><a href="<?= base_url(); ?>/<?php if (session()->level == 3) {
echo 'home';
} else {
echo 'profile/index';
} ?>" class="dropdown-item">View Profile </a></li>
<li class="dropdown-divider"></li>
<li><a href="<?= base_url(); ?>/auth/logout" class="dropdown-item">Logout</a></li>
</li>
</ul>
</nav>
<!-- /.navbar --><file_sep>/app/Models/LainnyaModel.php
<?php
namespace App\Models;
use CodeIgniter\Model;
class LainnyaModel extends Model
{
protected $table = 'lainnya';
public function getLainnya()
{
return $this->getWhere(['id_lainnya' => 1])->getRow();
}
public function editLainnya($lainnya)
{
$builder = $this->db->table($this->table);
$builder->where('id_lainnya', 1);
return $builder->update($lainnya);
}
}
<file_sep>/app/Controllers/User.php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\PendudukModel;
use App\Models\PerangkatModel;
use App\Models\AuthModel;
use App\Models\KeluargaModel;
class User extends Controller
{
protected $model, $isi, $keluarga, $data;
public function __construct()
{
helper('form');
$this->model = new AuthModel();
$this->penduduk = new PendudukModel();
$this->perangkat = new PerangkatModel();
$this->keluarga = new KeluargaModel();
}
public function index()
{
$ket = [
'Data User', '<li class="breadcrumb-item active"><a href="' . base_url() . '/user/index">Data User</a></li>'
];
$x = $this->model->getUser(false, 1);
$admin = [];
for ($i = 0; $i < count($x); $i++) {
$admin[$i]['id'] = $x[$i]['id'];
$admin[$i]['username'] = $x[$i]['username'];
$admin[$i]['email'] = $x[$i]['email'];
if ($this->perangkat->getPerangkat($x[$i]['id_datauser'], 'Perangkat Nagari') != NULL) {
$admin[$i]['nama'] = $this->perangkat->getPerangkat($x[$i]['id_datauser'], 'Perangkat Nagari')->nama;
} else {
$admin[$i]['nama'] = 'Super Admin';
}
}
$y = $this->model->getUser(false, 2);
$perangkat = [];
for ($i = 0; $i < count($y); $i++) {
$perangkat[$i]['id'] = $y[$i]['id'];
$perangkat[$i]['username'] = $y[$i]['username'];
$perangkat[$i]['email'] = $y[$i]['email'];
if ($this->perangkat->getPerangkat($x[$i]['id_datauser'], 'Perangkat Nagari') != NULL) {
$perangkat[$i]['nama'] = $this->perangkat->getPerangkat($x[$i]['id_datauser'], 'Perangkat Nagari')->nama;
} else {
$perangkat[$i]['nama'] = 'Admin';
}
}
$z = $this->model->getUser(false, 3);
$warga = [];
for ($i = 0; $i < count($z); $i++) {
$warga[$i]['id'] = $z[$i]['id'];
$warga[$i]['username'] = $z[$i]['username'];
$warga[$i]['email'] = $z[$i]['email'];
if ($this->penduduk->getPenduduk($z[$i]['id_datauser']) != NULL) {
$warga[$i]['nama'] = $this->penduduk->getPenduduk($z[$i]['id_datauser'])->nama;
} else {
$warga[$i]['nama'] = 'Warga';
}
}
$data = [
'title' => 'Data User',
'ket' => $ket,
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->model->getUser(session()->id),
'data_admin' => $admin,
'data_perangkat' => $perangkat,
'data_warga' => $warga
];
return view('user/index', $data);
}
public function getnik($id_keluarga)
{
$data = $this->penduduk->id_array($id_keluarga, 'id_keluarga');
for ($i = 0; $i < count($data); $i++) {
$json[$i]['nik'] = $data[$i]['nik'];
$json[$i]['id_penduduk'] = $data[$i]['id_penduduk'];
$json[$i]['nama'] = $data[$i]['nama'];
}
return $this->response->setJson($json);
}
public function input($l)
{
$ket = [
'Tambah Data User',
'<li class="breadcrumb-item active"><a href="' . base_url() . '/user/index">Data User</a></li>',
'<li class="breadcrumb-item active">Tambah Data</li>'
];
$data = [
'title' => 'Tambah Data User',
'ket' => $ket,
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->model->getUser(session()->id)
];
if ($l == 1 or $l == 2) {
$data['data'] = $this->perangkat->data('Perangkat Nagari');
} elseif ($l == 3) {
$data['data'] = $this->keluarga->getKeluarga();
}
$data['level'] = $l;
return view('user/input', $data);
}
public function view($id)
{
$user = $this->model->getUser($id);
$ket = [
'View Data User : ' . $user->username, '<li class="breadcrumb-item active"><a href="' . base_url() . '/user/index">Data User</a></li>',
'<li class="breadcrumb-item active">View Data</li>'
];
$data = [
'title' => 'View Data User : ' . $user->username,
'ket' => $ket,
'datauser' => $user,
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->model->getUser(session()->id)
];
return view('user/view', $data);
}
public function add()
{
$request = \Config\Services::request();
if ($request->getPost('level') == 1 or $request->getPost('level') == 2) {
$id = $request->getPost('id_datauser');
} elseif ($request->getPost('level') == 3) {
$id = $request->getPost('id_penduduk');
}
$data = array(
'id_datauser' => $id,
'email' => $request->getPost('email'),
'username' => $request->getPost('username'),
'password' => password_hash($request->getPost('pass'), PASSWORD_BCRYPT),
'telp' => $request->getPost('telp'),
'level' => $request->getPost('level'),
'foto' => 'default.svg',
);
$this->model->saveUser($data);
session()->setFlashdata('pesan_user', 'Data user berhasi ditambahkan.');
return redirect()->to('/user/index');
}
public function edit($id)
{
$user = $this->model->getUser($id);
if (isset($user)) {
$ket = [
'Edit Data : ' . $user->username,
'<li class="breadcrumb-item active"><a href="' . base_url() . '/user/index">Data User</a></li>',
'<li class="breadcrumb-item active">Edit Data</li>'
];
$data = [
'level' => $user->level,
'title' => 'Edit Data : ' . $user->username,
'ket' => $ket,
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->model->getUser(session()->id),
'datauser' => $user
];
$x = $this->model->getUser($id);
if ($user->level == 1 or $user->level == 2) {
$data['data'] = $this->perangkat->getPerangkat(false, 'Perangkat Nagari');
} elseif ($user->level == 3) {
$data['data'] = $this->penduduk->id_array($x->id_datauser, 'id_penduduk');
$data['keluarga'] = $this->keluarga->getKeluarga();
$data['kel'] = $this->penduduk->getPenduduk($x->id_datauser);
}
return view('user/edit', $data);
} else {
session()->setFlashdata('warning_user', 'User tidak ditemukan.');
return redirect()->to('/user/index');
}
}
public function update()
{
$request = \Config\Services::request();
$id = $request->getPost('id');
$file = $request->getFile('foto');
if ($file->getError() == 4) {
$nm = $request->getPost('lama');
} else {
$nm = $file->getRandomName();
$file->move('user', $nm);
if ($request->getPost('lama') != 'default.svg') {
unlink('user/' . $request->getPost('lama'));
}
}
if ($request->getPost('username') != NULL) {
$data = array(
'password' => password_hash($request->getPost('pass'), PASSWORD_BCRYPT),
);
$this->model->editUser($data, $id);
}
$data = array(
'id_datauser' => $request->getPost('id_datauser'),
'foto' => $nm,
'email' => $request->getPost('email'),
'username' => $request->getPost('username'),
'telp' => $request->getPost('telp'),
'level' => $request->getPost('level'),
);
$this->model->editUser($data, $id);
session()->setFlashdata('pesan_user', 'Data User Berhasi Diedit.');
return redirect()->to('user/index');
}
public function reset($id)
{
$data = array(
'password' => password_hash('<PASSWORD>', PASSWORD_<PASSWORD>),
);
$this->model->editUser($data, $id);
session()->setFlashdata('pesan_user', 'Password berhasil di reset');
return redirect()->to('user/index');
}
public function delete($id)
{
$user = $this->model->getUser($id);
if (isset($user) and $id != 1) {
$this->model->hapusUser($id);
session()->setFlashdata('danger_user', 'Data User ' . $user->username . ' berhasi dihapus.');
return redirect()->to('/user/index');
} elseif (isset($user) and $id == 1) {
session()->setFlashdata('warning_user', 'User : ' . $user->username . ' tidak dapat dihapus.');
return redirect()->to('/user/index');
} else {
session()->setFlashdata('warning_user', 'Data User ' . $user->username . ' Tidak Ditemukan.');
return redirect()->to('/user/index');
}
}
public function hapusbanyak()
{
$request = \Config\Services::request();
$id = $request->getPost('id');
if ($id == null) {
session()->setFlashdata('warning_user', 'Data user tidak dapat dihapus.');
return redirect()->to('user/index');
}
$jmldata = count($id);
$x = 0;
$y = 0;
for ($i = 0; $i < $jmldata; $i++) {
if ($id[$i] != 1) {
$this->model->hapusUser($id[$i]);
$x++;
} else {
$y++;
}
}
if ($y == 0 and $x != 0) {
session()->setFlashdata('pesan_user', 'Data user Berhasi Dihapus Sebanyak ' . $x . ' Data.');
} elseif ($y != 0 and $x != 0) {
session()->setFlashdata('pesan_user', 'Data user Berhasi Dihapus Sebanyak ' . $x . ' Data dan ' . $y . ' data tidak dapat dihapus.');
} else {
session()->setFlashdata('warning_user', 'Data user tidak dapat dihapus sebanyak ' . $y . ' data.');
}
return redirect()->to('user/index');
}
}
<file_sep>/app/Database/Migrations/2021-08-07-135514_Nagari.php
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class Nagari extends Migration
{
public function up()
{
$this->forge->addField([
'id_keluarga' => [
'type' => 'INT',
'auto_increment' => true,
],
'no_kk' => [
'type' => 'VARCHAR',
'constraint' => '16'
],
'nik_kepala' => [
'type' => 'VARCHAR',
'constraint' => '16'
],
'alamat' => [
'type' => 'VARCHAR',
'constraint' => '50'
],
'tgl_update' => [
'type' => 'DATE',
],
]);
$this->forge->addKey('id_keluarga', TRUE);
$this->forge->addUniqueKey('no_kk');
$this->forge->addUniqueKey('nik_kepala');
$this->forge->createTable('keluarga', TRUE);
$this->forge->addField([
'id_penduduk' => [
'type' => 'INT',
'auto_increment' => true
],
'id_keluarga' => [
'type' => 'INT'
],
'nik' => [
'type' => 'VARCHAR',
'constraint' => '16',
'null' => true
],
'nama' => [
'type' => 'VARCHAR',
'constraint' => '255'
],
'tpt_lahir' => [
'type' => 'VARCHAR',
'constraint' => '25'
],
'tgl_lahir' => [
'type' => 'DATE',
],
'jekel' => [
'type' => 'ENUM',
'constraint' => ['Laki - Laki', 'Perempuan']
],
'agama' => [
'type' => 'VARCHAR',
'constraint' => '25'
],
'kerja' => [
'type' => 'VARCHAR',
'constraint' => '50'
],
'kwn' => [
'type' => 'ENUM',
'constraint' => ['WNI', 'WNA']
],
'goldar' => [
'type' => 'VARCHAR',
'constraint' => '3',
'default' => '-'
],
'foto' => [
'type' => 'VARCHAR',
'constraint' => '255',
'default' => 'default.jpg'
],
'status_kawin' => [
'type' => 'VARCHAR',
'constraint' => '20',
'default' => 'Belum Kawin'
],
'status_hub' => [
'type' => 'VARCHAR',
'constraint' => '20',
'default' => 'Anak'
],
'pendidikan' => [
'type' => 'VARCHAR',
'constraint' => '50',
'default' => 'Tidak/Belum Sekolah'
],
'nm_ayah' => [
'type' => 'VARCHAR',
'constraint' => '255'
],
'nik_ayah' => [
'type' => 'VARCHAR',
'constraint' => '16',
'null' => true
],
'nm_ibu' => [
'type' => 'VARCHAR',
'constraint' => '255'
],
'nik_ibu' => [
'type' => 'VARCHAR',
'constraint' => '16',
'null' => true
],
'paspor' => [
'type' => 'VARCHAR',
'constraint' => '50',
'null' => true
],
'kitap' => [
'type' => 'VARCHAR',
'constraint' => '50',
'null' => true
],
'ket' => [
'type' => 'ENUM',
'constraint' => ['Hidup', 'Wafat'],
'default' => 'Hidup'
],
'tgl_update' => [
'type' => 'DATE',
],
]);
$this->forge->addKey('id_penduduk', TRUE);
$this->forge->addUniqueKey('nik');
$this->forge->addForeignKey('id_keluarga', 'keluarga', 'id_keluarga', 'CASCADE', 'CASCADE');
$this->forge->createTable('penduduk', TRUE);
$this->forge->addField([
'id_kematian' => [
'type' => 'INT',
'auto_increment' => true,
],
'id_penduduk' => [
'type' => 'INT'
],
'sebab' => [
'type' => 'VARCHAR',
'constraint' => '255'
],
'tpt_kematian' => [
'type' => 'VARCHAR',
'constraint' => '25'
],
'tgl_kematian' => [
'type' => 'DATE',
],
'tgl_update' => [
'type' => 'DATE'
],
]);
$this->forge->addKey('id_kematian', TRUE);
$this->forge->addForeignKey('id_penduduk', 'penduduk', 'id_penduduk', 'CASCADE', 'CASCADE');
$this->forge->createTable('kematian', TRUE);
$this->forge->addField([
'id_permohonan' => [
'type' => 'INT',
'auto_increment' => true,
],
'id_penduduk' => [
'type' => 'INT'
],
'id_user' => [
'type' => 'INT'
],
'jenis' => [
'type' => 'VARCHAR',
'constraint' => '5'
],
'tujuan' => [
'type' => 'TEXT'
],
'tambahan' => [
'type' => 'TEXT'
],
'scan_ktp' => [
'type' => 'VARCHAR',
'constraint' => '255'
],
'scan_kk' => [
'type' => 'VARCHAR',
'constraint' => '255'
],
'scan_jamkes' => [
'type' => 'VARCHAR',
'constraint' => '255',
'null' => true
],
'tgl_masuk' => [
'type' => 'DATE'
],
'tgl_periksa' => [
'type' => 'DATE',
'null' => true
],
'hasil' => [
'type' => 'TEXT',
'null' => true
],
'ket' => [
'type' => 'ENUM',
'constraint' => ['Belum Diperiksa', 'Disetujui', 'Ditolak'],
'default' => 'Belum Diperiksa'
],
]);
$this->forge->addKey('id_permohonan', TRUE);
$this->forge->addForeignKey('id_penduduk', 'penduduk', 'id_penduduk', 'CASCADE', 'CASCADE');
$this->forge->addForeignKey('id_user', 'users', 'id', 'CASCADE', 'CASCADE');
$this->forge->createTable('permohonan', TRUE);
$this->forge->addField([
'id_surat' => [
'type' => 'INT',
'auto_increment' => true,
],
'no_surat' => [
'type' => 'VARCHAR',
'constraint' => '50'
],
'id_penduduk' => [
'type' => 'INT'
],
'id_pemerintahan' => [
'type' => 'INT'
],
'tgl_surat' => [
'type' => 'DATE'
],
'jenis' => [
'type' => 'VARCHAR',
'constraint' => '5'
],
'tujuan' => [
'type' => 'TEXT'
],
'tambahan' => [
'type' => 'TEXT'
],
]);
$this->forge->addKey('id_surat', TRUE);
$this->forge->addForeignKey('id_penduduk', 'penduduk', 'id_penduduk', 'CASCADE', 'CASCADE');
$this->forge->addForeignKey('id_pemerintahan', 'pemerintahan', 'id_pemerintahan', 'CASCADE', 'CASCADE');
$this->forge->createTable('surat', TRUE);
$this->forge->addField([
'id_pemerintahan' => [
'type' => 'INT',
'auto_increment' => true,
],
'no' => [
'type' => 'VARCHAR',
'constraint' => '50',
],
'nik' => [
'type' => 'VARCHAR',
'constraint' => '16',
'null' => true
],
'nama' => [
'type' => 'VARCHAR',
'constraint' => '255'
],
'jabatan' => [
'type' => 'VARCHAR',
'constraint' => '50'
],
'status' => [
'type' => 'VARCHAR',
'constraint' => '25'
],
'telp' => [
'type' => 'VARCHAR',
'constraint' => '20',
'null' => true
],
'jekel' => [
'type' => 'ENUM',
'constraint' => ['Laki - Laki', 'Perempuan']
],
'foto' => [
'type' => 'VARCHAR',
'constraint' => '255',
'default' => 'default.jpg'
],
'tgl_lantik' => [
'type' => 'DATE',
],
'tgl_berhenti' => [
'type' => 'DATE',
'null' => true
],
'ket' => [
'type' => 'ENUM',
'constraint' => ['Menjabat', 'Berhenti'],
'default' => 'Menjabat'
],
'tgl_update' => [
'type' => 'DATE'
],
]);
$this->forge->addKey('id_pemerintahan', TRUE);
$this->forge->createTable('pemerintahan', TRUE);
$this->forge->addField([
'id_berita' => [
'type' => 'INT',
'auto_increment' => true,
],
'judul' => [
'type' => 'VARCHAR',
'constraint' => '255'
],
'penulis' => [
'type' => 'VARCHAR',
'constraint' => '255'
],
'gambar' => [
'type' => 'VARCHAR',
'constraint' => '255',
'null' => true
],
'isi' => [
'type' => 'TEXT',
],
'tgl_update' => [
'type' => 'DATE'
],
]);
$this->forge->addKey('id_berita', TRUE);
$this->forge->createTable('berita', TRUE);
$this->forge->addField([
'id_potensi' => [
'type' => 'INT',
'auto_increment' => true,
],
'nama' => [
'type' => 'VARCHAR',
'constraint' => '255'
],
'foto' => [
'type' => 'VARCHAR',
'constraint' => '255',
'null' => true
],
'ket' => [
'type' => 'TEXT',
],
'tgl_update' => [
'type' => 'DATE'
],
]);
$this->forge->addKey('id_potensi', TRUE);
$this->forge->createTable('potensi', TRUE);
$this->forge->addField([
'id_data' => [
'type' => 'INT',
'auto_increment' => true,
],
'nama_wali' => [
'type' => 'VARCHAR',
'constraint' => '255'
],
'visi' => [
'type' => 'TEXT',
'null' => true
],
'misi' => [
'type' => 'TEXT',
'null' => true
],
'sejarah' => [
'type' => 'TEXT',
'null' => true
],
'wilayah' => [
'type' => 'TEXT',
'null' => true
],
'logo' => [
'type' => 'VARCHAR',
'constraint' => '255'
],
'kata_sambutan' => [
'type' => 'TEXT',
'null' => true
],
'tgl_update' => [
'type' => 'DATE'
],
]);
$this->forge->addKey('id_data', TRUE);
$this->forge->createTable('data', TRUE);
$this->forge->addField([
'id_alamat' => [
'type' => 'INT',
'auto_increment' => true,
],
'alm' => [
'type' => 'TEXT'
],
'nagari' => [
'type' => 'VARCHAR',
'constraint' => '50'
],
'kec' => [
'type' => 'VARCHAR',
'constraint' => '50'
],
'kab' => [
'type' => 'VARCHAR',
'constraint' => '50'
],
'prov' => [
'type' => 'VARCHAR',
'constraint' => '50'
],
'kd_pos' => [
'type' => 'VARCHAR',
'constraint' => '10',
'null' => true
],
'map_wilayah' => [
'type' => 'TEXT',
'null' => true
],
'map_kantor' => [
'type' => 'TEXT',
'null' => true
],
'telp' => [
'type' => 'VARCHAR',
'constraint' => '20',
'null' => true
],
'email' => [
'type' => 'VARCHAR',
'constraint' => '255',
'null' => true
],
'tgl_update' => [
'type' => 'DATE'
],
]);
$this->forge->addKey('id_alamat', TRUE);
$this->forge->createTable('alamat', TRUE);
$this->forge->addField([
'id_agama' => [
'type' => 'INT',
'auto_increment' => true,
],
'nama' => [
'type' => 'VARCHAR',
'constraint' => '25'
],
]);
$this->forge->addKey('id_agama', TRUE);
$this->forge->createTable('agama', TRUE);
$this->forge->addField([
'id_pendidikan' => [
'type' => 'INT',
'auto_increment' => true,
],
'nama' => [
'type' => 'VARCHAR',
'constraint' => '50'
],
]);
$this->forge->addKey('id_pendidikan', TRUE);
$this->forge->createTable('pendidikan', TRUE);
$this->forge->addField([
'id_pekerjaan' => [
'type' => 'INT',
'auto_increment' => true,
],
'nama' => [
'type' => 'VARCHAR',
'constraint' => '50'
],
]);
$this->forge->addKey('id_pekerjaan', TRUE);
$this->forge->createTable('pekerjaan', TRUE);
$this->forge->addField([
'id_kawin' => [
'type' => 'INT',
'auto_increment' => true,
],
'nama' => [
'type' => 'VARCHAR',
'constraint' => '20'
],
]);
$this->forge->addKey('id_kawin', TRUE);
$this->forge->createTable('status_kawin', TRUE);
$this->forge->addField([
'id_hub' => [
'type' => 'INT',
'auto_increment' => true,
],
'nama' => [
'type' => 'VARCHAR',
'constraint' => '20'
],
]);
$this->forge->addKey('id_hub', TRUE);
$this->forge->createTable('status_hub', TRUE);
$this->forge->addField([
'id_galeri' => [
'type' => 'INT',
'auto_increment' => true,
],
'jenis' => [
'type' => 'VARCHAR',
'constraint' => '255'
],
'foto' => [
'type' => 'VARCHAR',
'constraint' => '255'
],
]);
$this->forge->addKey('id_galeri', TRUE);
$this->forge->createTable('galeri', TRUE);
$this->forge->addField([
'id_aduan' => [
'type' => 'INT',
'auto_increment' => true
],
'id_user' => [
'type' => 'INT'
],
'tgl_aduan' => [
'type' => 'DATE'
],
'tgl_respon' => [
'type' => 'DATE',
'null' => true
],
'aduan' => [
'type' => 'TEXT'
],
'respon' => [
'type' => 'DATE',
'null' => true
],
'ket' => [
'type' => 'ENUM',
'constraint' => ['Belum Diproses', 'Selesai'],
'default' => 'Belum Diproses'
],
]);
$this->forge->addKey('id_aduan', TRUE);
$this->forge->addForeignKey('id_user', 'users', 'id', 'CASCADE', 'CASCADE');
$this->forge->createTable('aduan', TRUE);
$this->forge->addField([
'id' => [
'type' => 'INT',
'auto_increment' => true
],
'id_datauser' => [
'type' => 'INT',
'null' => true
],
'foto' => [
'type' => 'VARCHAR',
'constraint' => '255',
'default' => 'default.svg'
],
'email' => [
'type' => 'VARCHAR',
'constraint' => '255',
'null' => true
],
'username' => [
'type' => 'VARCHAR',
'constraint' => '255'
],
'password' => [
'type' => 'VARCHAR',
'constraint' => '255'
],
'telp' => [
'type' => 'VARCHAR',
'constraint' => '20',
'null' => true
],
'level' => [
'type' => 'INT'
],
]);
$this->forge->addKey('id', TRUE);
$this->forge->createTable('users', TRUE);
}
public function down()
{
$this->forge->dropTable('keluarga');
$this->forge->dropTable('penduduk');
$this->forge->dropTable('kematian');
$this->forge->dropTable('permohonan'); //
$this->forge->dropTable('surat'); //
$this->forge->dropTable('pemerintahan');
$this->forge->dropTable('berita');
$this->forge->dropTable('potensi');
$this->forge->dropTable('data');
$this->forge->dropTable('alamat');
$this->forge->dropTable('agama');
$this->forge->dropTable('pendidikan');
$this->forge->dropTable('pekerjaan');
$this->forge->dropTable('status_kawin');
$this->forge->dropTable('status_hub');
$this->forge->dropTable('galeri');
$this->forge->dropTable('aduan');
$this->forge->dropTable('users');
}
}
<file_sep>/app/Controllers/Data.php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\DataModel;
use App\Models\AlamatModel;
use App\Models\PendudukModel;
use App\Models\AuthModel;
use App\Models\PerangkatModel;
class Data extends Controller
{
protected $model;
public function __construct()
{
helper('form');
// Deklarasi model
$this->model = new DataModel();
$this->alm = new AlamatModel();
$this->penduduk = new PendudukModel();
$this->user = new AuthModel();
$this->perangkat = new PerangkatModel();
}
// Menampilkan Alamat
public function index()
{
$ket = [
'Alamat', '<li class="breadcrumb-item active"><a href="/data/index">Alamat</a></li>'
];
$data = [
'title' => 'Alamat',
'ket' => $ket,
'data' => $this->alm->getAlamat(),
'link' => 'home',
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('alamat/index', $data);
}
// Menampilkan form edit data
public function edit()
{
$data = $this->alm->getAlamat();
if (isset($data)) {
$ket = [
'Edit Alamat', '<li class="breadcrumb-item active"><a href="/data/index">Alamat</a></li>',
'<li class="breadcrumb-item active">Edit Data</li>'
];
$data = [
'title' => 'Edit Alamat',
'ket' => $ket,
'link' => 'home',
'data' => $data,
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('alamat/edit', $data);
} else {
session()->setFlashdata('warning_data', 'data Tidak Ditemukan.');
return redirect()->to(base_url() . '/data/index');
}
}
// Edit Data
public function update()
{
$request = \Config\Services::request();
$data = array(
'kec' => $request->getPost('kec'),
'nagari' => $request->getPost('nagari'),
'kab' => $request->getPost('kab'),
'prov' => $request->getPost('prov'),
'alm' => $request->getPost('alm'),
'map_wilayah' => $request->getPost('map_wilayah'),
'map_kantor' => $request->getPost('map_kantor'),
'kd_pos' => $request->getPost('kd_pos')
);
$this->alm->editAlamat($data);
session()->setFlashData('pesan_data', 'Alamat Berhasi Diedit.');
return redirect()->to(base_url() . '/data/index');
}
public function info()
{
$ket = [
'Info', '<li class="breadcrumb-item active"><a href="/data/info">Info</a></li>'
];
$data = [
'title' => 'Info',
'ket' => $ket,
'link' => 'home',
'data' => $this->model->getData(),
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id),
'tambah' => $this->alm->getAlamat(),
];
return view('info/index', $data);
}
public function editinfo()
{
$data = $this->model->getData();
if (isset($data)) {
$ket = [
'Edit Info', '<li class="breadcrumb-item active"><a href="/data/info">Info</a></li>',
'<li class="breadcrumb-item active">Edit Data</li>'
];
$data = [
'title' => 'Edit Info',
'ket' => $ket,
'link' => 'home',
'data' => $data,
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id),
'tambah' => $this->alm->getAlamat(),
];
return view('info/edit', $data);
} else {
session()->setFlashdata('warning_data', 'data Tidak Ditemukan.');
return redirect()->to(base_url() . '/data/info');
}
}
// Edit Data
public function updateinfo()
{
$request = \Config\Services::request();
$data = array(
'visi' => $request->getPost('visi'),
'misi' => $request->getPost('misi'),
'sejarah' => $request->getPost('sejarah'),
'wilayah' => $request->getPost('wilayah'),
'kata_sambutan' => $request->getPost('kata_sambutan'),
'syarat_surat' => $request->getPost('surat'),
);
$this->model->editData($data);
$data2 = array(
'telp' => $request->getPost('telp'),
'email' => $request->getPost('email')
);
$this->alm->editAlamat($data2);
session()->setFlashData('pesan_data', 'Info Berhasi Diedit.');
return redirect()->to(base_url() . '/data/info');
}
}
<file_sep>/app/Models/PotensiModel.php
<?php
namespace App\Models;
use CodeIgniter\Model;
class PotensiModel extends Model
{
protected $table = 'potensi';
public function getPotensi($id_potensi = false)
{
if ($id_potensi === false) {
return $this->orderBy('id_potensi', 'DESC')->findAll();
} else {
return $this->getWhere(['id_potensi' => $id_potensi])->getRow();
}
}
public function savePotensi($data)
{
$builder = $this->db->table($this->table);
return $builder->insert($data);
}
public function editPotensi($data, $id_potensi)
{
$builder = $this->db->table($this->table);
$builder->where('id_potensi', $id_potensi);
return $builder->update($data);
}
public function hapusPotensi($id_potensi)
{
$builder = $this->db->table($this->table);
return $builder->delete(['id_potensi' => $id_potensi]);
}
}
<file_sep>/app/Views/mohon/hasil.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<?= $this->include('template/tgl'); ?>
<!-- Main content -->
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-eye mr-1"></i>
View Data : <?= $mohon->jenis; ?> ~ <?= tgl_indo($mohon->tgl_masuk); ?>
</h3>
</div><!-- /.card-header -->
<div class="card-body">
<table class="table">
<tr>
<th>Jenis Surat</th>
<td> : <?= $mohon->jenis; ?></td>
</tr>
<tr>
<th>Tanggal Permohoanan Surat</th>
<td> : <?= tgl_indo($mohon->tgl_masuk); ?></td>
</tr>
<tr>
<th>Status</th>
<td> : <?= $mohon->ket; ?></td>
</tr>
<tr>
<th>Tujuan Surat</th>
<td> : <?= $mohon->tujuan; ?></td>
</tr>
<tr>
<th>Keterangan Tambahan</th>
<td> : <?= $mohon->tambahan; ?></td>
</tr>
</table>
<table class="table">
<tr>
<th>Lampiran Scan KTP : </th>
<th>Lampiran Scan KK : </th>
</tr>
<tr>
<td><img src="<?= base_url(); ?>/permohonan/<?= $mohon->scan_ktp; ?>" alt="Scan KTP" width="100%"></td>
<td><img src="<?= base_url(); ?>/permohonan/<?= $mohon->scan_kk; ?>" alt="Scan KK" width="100%"></td>
</tr>
</table>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</div>
<!-- /.container-fluid -->
</section>
<!-- /.content -->
<!-- /.content -->
<?= $this->endSection(); ?><file_sep>/app/Views/aduan/viewadmin.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<?= $this->include('template/tgl'); ?>
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-eye mr-1"></i>
View Data : Aduan - <?= tgl_indo($aduan->tgl_aduan); ?>
</h3>
</div>
<div class="card-body">
<table class="table">
<tr>
<th>Nama</th>
<td> : <?= $penduduk->nama; ?></td>
</tr>
<tr>
<th>Tanggal Aduan</th>
<td> : <?= tgl_indo($aduan->tgl_aduan); ?></td>
</tr>
<tr>
<th>Gambar</th>
<td> : <img style="max-width: 50%;" src="<?= base_url(); ?>/aduan/<?= $aduan->gambar; ?>" alt=""></td>
</tr>
<tr>
<th>Isi Aduan</th>
<td> : <?= $aduan->aduan; ?></td>
</tr>
</table>
</div>
</div>
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-eye mr-1"></i>
Tanggapan
</h3>
</div>
<div class="card-body">
<form action="<?= base_url(); ?>/aduan/update" method="post">
<?= csrf_field(); ?>
<div class="row mb-3">
<label for="respon" class="col-form-label">Tanggapan</label>
<textarea name="respon" id="respon" style="height: 200px; background: lightgrey;"><?php if ($aduan->respon != NULL or $aduan->respon != 'Belum ada respon') {
echo $aduan->respon;
} ?></textarea>
</div>
<input type="hidden" name="id_aduan" value="<?= $aduan->id_aduan; ?>">
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
<?= $this->endSection(); ?><file_sep>/app/Controllers/Sku.php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\SuratModel;
use App\Models\PendudukModel;
use App\Models\AlamatModel;
use App\Models\KeluargaModel;
use App\Models\PerangkatModel;
use App\Models\AuthModel;
use App\Models\GaleriModel;
use TCPDF;
class pdf extends TCPDF
{
public function Header()
{
$this->data = new AlamatModel();
$x = $this->data->getAlamat();
$kab = strtoupper($x->kab);
$kec = strtoupper($x->kec);
$nag = strtoupper($x->nagari);
$image_file = @FCPATH . 'aset\img\logo.png';
$this->SetY(10);
$this->SetFont('times', 'B', 12);
$isi_header = "
<table>
<tr>
<td width=\"70\"><img src=\"" . $image_file . "\" width=\"80\" height=\"80\"></td>
<td align=\"center\" style=\"font-size:17px\" width=\"90%\">
PEMERINTAHAN KABUPATEN " . $kab . "<br>
KECAMATAN " . $kec . "<br>
WALI NAGARI " . $nag . "
</td>
</tr>
<tr>
<td width=\"50%\">" . $x->alm . "</td>
<td width=\"50%\" align=\"right\">Kode Pos : " . $x->kd_pos . "</td>
</tr>
</table>
<hr>
";
$this->writeHTML($isi_header, true, false, false, false, '');
}
}
class Sku extends Controller
{
protected $model, $penduduk, $data, $keluarga, $perangkat;
public function __construct()
{
helper('form');
$this->model = new SuratModel();
$this->penduduk = new PendudukModel();
$this->data = new AlamatModel();
$this->keluarga = new KeluargaModel();
$this->perangkat = new PerangkatModel();
$this->user = new AuthModel();
$this->gal = new GaleriModel();
}
public function index()
{
$ket = [
'Data Surat Keterangan Usaha', '<li class="breadcrumb-item active"><a href="/sku/index">Data Surat Keterangan Usaha</a></li>'
];
$data = [
'title' => 'Data Surat Keterangan Usaha',
'ket' => $ket,
'link' => 'sku',
'surat' => $this->model->getSurat(false, 'SKU'),
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('surat/index', $data);
}
public function view($id_surat)
{
$x = $this->model->getSurat($id_surat, 'SKU');
$ket = [
'View Data Surat Keterangan Usaha', '<li class="breadcrumb-item active"><a href="/sku/index">Data Surat Keterangan Usaha</a></li>',
'<li class="breadcrumb-item active">View Data</li>'
];
$data = [
'title' => 'View Data Surat Keterangan Usaha',
'ket' => $ket,
'link' => 'sku',
'surat' => $x,
'data' => $this->data->getAlamat(),
'gal' => $this->gal->getGaleri(2),
'kk' => $this->keluarga->getKeluarga($x->id_keluarga),
'ttd' => $this->perangkat->getPerangkat($x->id_pemerintahan, 'Perangkat Nagari'),
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id),
'jenis_s' => 'SURAT KETERANGAN USAHA',
'label_s' => '/PEREK/',
'label' => 'Jenis Usaha',
];
return view('surat/view', $data);
}
public function print($id_surat)
{
$x = $this->model->getSurat($id_surat, 'SKU');
$data = [
'title' => 'View Data Surat Keterangan Usaha',
'surat' => $x,
'data' => $this->data->getAlamat(),
'kk' => $this->keluarga->getKeluarga($x->id_keluarga),
'ttd' => $this->perangkat->getPerangkat($x->id_pemerintahan, 'Perangkat Nagari')
];
$html = view('surat/print', $data);
$pdf = new pdf(PDF_PAGE_ORIENTATION, PDF_UNIT, 'F4', true, 'UTF-8', false);
$pdf->SetFont('times', '', 12);
$pdf->setHeaderMargin(20);
$pdf->setPrintHeader(true);
$pdf->setPrintFooter(true);
$pdf->SetMargins(20, 45, 20, true);
$pdf->AddPage();
$pdf->writeHTML($html);
$this->response->setContentType('application/pdf');
$pdf->Output('sku.pdf', 'I');
}
public function input()
{
$ket = [
'Tambah Data Surat Keterangan Usaha',
'<li class="breadcrumb-item active"><a href="/sku/index">Data Surat Keterangan Usaha</a></li>',
'<li class="breadcrumb-item active">Tambah Data</li>'
];
$data = [
'title' => 'Tambah Data Surat Keterangan Usaha',
'ket' => $ket,
'link' => 'sku',
'label' => 'Jenis Usaha',
'keluarga' => $this->keluarga->getKeluarga(),
'ttd' => $this->perangkat->ttd(),
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('surat/input', $data);
}
public function nama($id_penduduk)
{
$data = $this->penduduk->id($id_penduduk, 'id_penduduk');
$json = array();
$json['nama'] = $data->tambahan;
return $this->response->setJson($json);
}
public function getnik($id_keluarga)
{
$data = $this->penduduk->id_array($id_keluarga, 'id_keluarga');
for ($i = 0; $i < count($data); $i++) {
$json[$i]['nik'] = $data[$i]['nik'];
$json[$i]['id_penduduk'] = $data[$i]['id_penduduk'];
$json[$i]['nama'] = $data[$i]['nama'];
}
return $this->response->setJson($json);
}
public function add()
{
$request = \Config\Services::request();
$max = $this->model->no('SKU');
$data = array(
'no_surat' => $max->x + 1,
'id_penduduk' => $request->getPost('id_penduduk'),
'id_pemerintahan' => $request->getPost('ttd'),
'tgl_surat' => date('Y-m-d'),
'jenis' => 'SKU',
'tujuan' => $request->getPost('tujuan'),
'tambahan' => $request->getPost('ket'),
);
$this->model->saveSurat($data);
return redirect()->to('sku/index');
}
public function edit($id_surat)
{
$surat = $this->model->getSurat($id_surat, 'SKU');
if (isset($surat)) {
$ket = [
'Edit ' . $surat->tambahan,
'<li class="breadcrumb-item active"><a href="/sku/index">Data Surat Keterangan Usaha</a></li>',
'<li class="breadcrumb-item active">Edit Data</li>'
];
$x = $this->penduduk->getPenduduk($surat->id_penduduk);
$data = [
'title' => 'Edit ' . $surat->tambahan,
'ket' => $ket,
'link' => 'sku',
'surat' => $surat,
'label' => 'Jenis Usaha',
'keluarga' => $this->keluarga->getKeluarga(),
'ttd' => $this->perangkat->ttd(),
'kel' => $x,
'penduduk' => $this->penduduk->id_array($surat->id_keluarga, 'id_keluarga'),
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('surat/edit', $data);
} else {
session()->setFlashdata('warning_surat', 'Surat tanggal : ' . $surat->tambahan . ' Tidak Ditemukan.');
return redirect()->to('sku/index');
}
}
public function update()
{
$request = \Config\Services::request();
$id_surat = $request->getPost('id_surat');
$max = $this->model->no('SKU');
$data = array(
'no_surat' => $max->x + 1,
'id_penduduk' => $request->getPost('id_penduduk'),
'id_pemerintahan' => $request->getPost('ttd'),
'tgl_surat' => date('Y-m-d'),
'jenis' => 'SKU',
'tujuan' => $request->getPost('tujuan'),
'tambahan' => $request->getPost('ket'),
);
$this->model->editSurat($data, $id_surat);
session()->setFlashdata('pesan_surat', 'Data Surat Keterangan Usaha Berhasi Diedit.');
return redirect()->to('sku/index');
}
public function delete($id_surat)
{
$surat = $this->model->getSurat($id_surat, 'SKU');
if (isset($surat)) {
$this->model->hapusSurat($id_surat);
session()->setFlashdata('pesan_surat', 'Data Surat Keterangan Usaha : ' . $surat->tambahan . ' Berhasi Dihapus.');
return redirect()->to('sku/index');
} else {
session()->setFlashdata('warning_surat', 'Data Surat Keterangan Usaha : ' . $surat->tambahan . ' Tidak Ditemukan.');
return redirect()->to('sku/index');
}
}
public function hapusbanyak()
{
$request = \Config\Services::request();
$id_surat = $request->getPost('id_surat');
if ($id_surat == null) {
session()->setFlashdata('warning', 'Data Pejabat dan berita Desa Belum Dipilih, Silahkan Pilih Data Terlebih Dahulu.');
$data['title'] = 'Data Surat Keterangan Usaha dan Pejabat Desa';
return redirect()->to('sku/index');
}
$jmldata = count($id_surat);
$x = 0;
for ($i = 0; $i < $jmldata; $i++) {
$this->model->hapusSurat($id_surat[$i]);
$x++;
}
session()->setFlashdata('pesan', 'Data Pejabat dan berita Desa Berhasi Dihapus Sebanyak ' . $x . ' Data.');
$data['title'] = 'Data Surat Keterangan Usaha dan Pejabat Desa';
return redirect()->to('sku/index');
}
}
<file_sep>/app/Views/template/sidebar_admin.php
<!-- Admin -->
<?php if (session()->get('level') == 1) : ?>
<li class="nav-item">
<a href="<?= base_url(); ?>/user/index" class="nav-link">
<i class="nav-icon fas fa-users"></i>
<p>
User
</p>
</a>
</li>
<div class="dropdown-divider"></div>
<?php endif; ?><file_sep>/app/Views/profile/index.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<section class="content">
<?= $this->include('template/tgl') ?>
<div class="container-fluid">
<div class="row">
<div class="col-12">
<?php if (session()->getFlashdata('pesan_profile')) : ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('pesan_profile'); ?>
</div>
<?php endif; ?>
<div class="card">
<div class="row">
<div class="col-lg-3 col-md-5" style="padding: 3vh;">
<img src="<?= base_url(); ?>/<?php if (session()->level == 3) {
echo 'penduduk';
} else {
echo 'perangkat';
} ?>/<?= $isi->foto; ?>">
</div>
<div class="col" style="padding: 3vh;">
<h3><b><?= $user->nama; ?></b></h3>
<table class="table">
<tr>
<td>NIK</td>
<td> : <?= $user->nik; ?></td>
</tr>
<tr>
<td>No KK</td>
<td> : <?= $user->no_kk; ?></td>
</tr>
<tr>
<td>Alamat</td>
<td> : <?= $user->alamat; ?></td>
</tr>
<tr>
<td>Tempat/Tanggal Lahir</td>
<td> : <?= $user->tpt_lahir; ?>/<?= tgl_indo($user->tgl_lahir); ?></td>
</tr>
<tr>
<td>Email</td>
<td> : <?= $isi->email; ?></td>
</tr>
<tr>
<td>No Telepon</td>
<td> : <a href="tel:<?= $isi->telp; ?>"><?= $isi->telp; ?></a></td>
</tr>
</table>
<button type="button" class="btn btn-success">
<a href="<?php echo base_url('/profile/edit'); ?>" style="color: white;">
<i class="far fa-edit"> Edit Profile</i>
</a>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<?= $this->endSection(); ?><file_sep>/app/Models/UangModel.php
<?php
namespace App\Models;
use CodeIgniter\Model;
class UangModel extends Model
{
protected $table = 'uang';
public function getUang($id_uang = false)
{
if ($id_uang === false) {
return $this->orderBy('id_uang', 'DESC')->findAll();
} else {
return $this->getWhere(['id_uang' => $id_uang])->getRow();
}
}
public function saveUang($data)
{
$builder = $this->db->table($this->table);
return $builder->insert($data);
}
public function editUang($data, $id_uang)
{
$builder = $this->db->table($this->table);
$builder->where('id_uang', $id_uang);
return $builder->update($data);
}
public function hapusUang($id_uang)
{
$builder = $this->db->table($this->table);
return $builder->delete(['id_uang' => $id_uang]);
}
// Mencari ID
public function id($input, $field)
{
return $this->getWhere([$field => $input])->getRow();
}
}
<file_sep>/app/Models/MohonModel.php
<?php
namespace App\Models;
use CodeIgniter\Model;
class MohonModel extends Model
{
protected $table = 'permohonan';
public function getMohon($id = false, $id_permohonan = false, $hasil = false)
{
if ($id != false and $id_permohonan == false and $hasil == false) { // Semua data
return $this->where('id_user', $id)->orderBy('id_permohonan', 'DESC')->findAll();
} elseif ($id == false and $id_permohonan == false and $hasil != false) { // Semua data berdasarkan hasil
return $this->where('ket', $hasil)->orderBy('id_permohonan', 'DESC')->findAll();
} elseif ($id == false and $id_permohonan != false and $hasil == false) { // Salah satu data
return $this->getWhere(['id_permohonan' => $id_permohonan])->getRow();
}
}
public function saveMohon($data)
{
$builder = $this->db->table($this->table);
return $builder->insert($data);
}
public function editMohon($data, $id_permohonan)
{
$builder = $this->db->table($this->table);
$builder->where('id_permohonan', $id_permohonan);
return $builder->update($data);
}
public function hapusMohon($id_permohonan)
{
$builder = $this->db->table($this->table);
return $builder->delete(['id_permohonan' => $id_permohonan]);
}
// Count Mohon
public function count($srt)
{
return $this->db->table('permohonan')->where('jenis', $srt)->countAllResults();
}
}
<file_sep>/app/Controllers/Permohonan.php
<?php
namespace App\Controllers;
use App\Models\PendudukModel;
use App\Models\AuthModel;
use App\Models\MohonModel;
use App\Models\PerangkatModel;
use App\Models\SuratModel;
class Permohonan extends BaseController
{
public function __construct()
{
helper('form');
// Deklarasi model
$this->model = new MohonModel();
$this->penduduk = new PendudukModel();
$this->user = new AuthModel();
$this->perangkat = new PerangkatModel();
$this->surat = new SuratModel();
}
public function index()
{
if (session()->get('level') == 1 or session()->get('level') == 2) {
$ket = [
'List Permohonan', '<li class="breadcrumb-item active"><a href="' . base_url() . '/permohonan/index">List Permohonan</a></li>'
];
$data = [
'title' => 'List Permohonan',
'ket' => $ket,
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id),
'mohon_blm' => $this->model->getMohon(false, false, 'Belum Diperiksa'),
'mohon_stj' => $this->model->getMohon(false, false, 'Diterima'),
'mohon_tlk' => $this->model->getMohon(false, false, 'Ditolak'),
];
return view('mohon/indexadmin', $data);
} elseif (session()->get('level') == 3) {
$ket = [
'Permohonan Surat', '<li class="breadcrumb-item active"><a href="' . base_url() . '/permohonan/index">Permohonan Surat</a></li>'
];
$data = [
'title' => 'Permohonan Surat',
'ket' => $ket,
'user' => $this->penduduk->getPenduduk(session()->get('id_datauser')),
'isi' => $this->user->getUser(session()->id),
'permohonan' => $this->model->getMohon(session()->id, false, false),
];
return view('mohon/index', $data);
}
}
public function view($id_permohonan, $hasil = false)
{
if (session()->get('level') == 1 or session()->get('level') == 2) {
if ($hasil == 'belum') {
$view = 'viewadmin';
} elseif ($hasil == 'terima') {
$view = 'view';
} elseif ($hasil == 'tolak') {
$view = 'view';
}
$getMohon = $this->model->getMohon(false, $id_permohonan, false);
if (isset($getMohon)) {
$ket = [
'Periksa Data : ' . $getMohon->id_permohonan,
'<li class="breadcrumb-item active"><a href="/permohonan/index">List Permohonan</a></li>',
'<li class="breadcrumb-item active">Periksa Data</li>'
];
$data = [
'title' => 'Periksa Data : ' . $getMohon->id_permohonan,
'ket' => $ket,
'mohon' => $getMohon,
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id),
'penduduk' => $this->penduduk->getPenduduk($getMohon->id_penduduk)
];
return view('mohon/' . $view, $data);
} else {
session()->setFlashdata('warning_permohonan', 'Permohonan Tidak Ditemukan.');
return redirect()->to(base_url() . 'permohonan/index');
}
} elseif (session()->get('level') == 3) {
$getMohon = $this->model->getMohon(false, $id_permohonan, false);
if (isset($getMohon)) {
$ket = [
'Periksa Data : ' . $getMohon->id_permohonan,
'<li class="breadcrumb-item active"><a href="/permohonan/index">Permohonan Surat</a></li>',
'<li class="breadcrumb-item active">Periksa Data</li>'
];
$data = [
'title' => 'Periksa Data : ' . $getMohon->id_permohonan,
'ket' => $ket,
'mohon' => $getMohon,
'user' => $this->penduduk->getPenduduk(session()->get('id_datauser')),
'isi' => $this->user->getUser(session()->id),
];
return view('mohon/view', $data);
} else {
session()->setFlashdata('warning_permohonan', 'Permohonan Tidak Ditemukan.');
return redirect()->to(base_url() . 'permohonan/index');
}
}
}
public function input()
{
$ket = [
'Tambah Permohonan', '<li class="breadcrumb-item active"><a href="' . base_url() . '/permohonan/index">Permohonan Surat</a></li>',
'<li class="breadcrumb-item active">Tambah Data</li>'
];
$surat = array(
'SKTM', 'SKM', 'SKPO', 'SKU'
);
$data = [
'title' => 'Tambah Permohonan',
'ket' => $ket,
'link' => 'home',
'user' => $this->penduduk->getPenduduk(session()->get('id_datauser')),
'isi' => $this->user->getUser(session()->id),
'surat' => $surat
];
return view('mohon/input', $data);
}
public function add()
{
$request = \Config\Services::request();
$ktp = $request->getFile('scan_ktp');
if ($ktp->getError() == 4) {
$nm_ktp = "no_image.png";
} else {
$nm_ktp = $ktp->getRandomName();
$ktp->move('permohonan', $nm_ktp);
}
$kk = $request->getFile('scan_kk');
if ($kk->getError() == 4) {
$nm_kk = "no_image.png";
} else {
$nm_kk = $kk->getRandomName();
$kk->move('permohonan', $nm_kk);
}
$jamkes = $request->getFile('scan_jamkes');
if ($jamkes->getError() == 4) {
$nm_jamkes = "no_image.png";
} else {
$nm_jamkes = $jamkes->getRandomName();
$jamkes->move('permohonan', $nm_jamkes);
}
$data = array(
'id_penduduk' => session()->id_datauser,
'id_user' => session()->id,
'jenis' => $request->getPost('jenis'),
'tujuan' => $request->getPost('tujuan'),
'tambahan' => $request->getPost('tambahan'),
'scan_ktp' => $nm_ktp,
'scan_kk' => $nm_kk,
'scan_jamkes' => $nm_jamkes,
'tgl_masuk' => date('Y-m-d'),
);
// dd($data);
$this->model->saveMohon($data);
session()->setFlashdata('pesan_mohon', 'Permohonan berhasi ditambah.');
return redirect()->to(base_url() . '/permohonan/index');
}
public function surat($id_permohonan)
{
$srt = $this->model->getMohon(false, $id_permohonan, false);
$max = $this->surat->no($srt->jenis);
$wali = $this->perangkat->wali();
$data = array(
'no_surat' => $max->x + 1,
'id_penduduk' => $srt->id_penduduk,
'id_pemerintahan' => $wali->id_pemerintahan,
'tgl_surat' => date('Y-m-d'),
'jenis' => $srt->jenis,
'tujuan' => $srt->tujuan,
'tambahan' => $srt->tambahan,
);
$this->surat->saveSurat($data);
return redirect()->to($srt->jenis . '/index');
}
public function edit($id_permohonan)
{
$getMohon = $this->model->getMohon(false, $id_permohonan);
if (isset($getMohon)) {
$surat = array(
'SKTM', 'SKM', 'SKPO', 'SKU'
);
$ket = [
'Edit Permohonan', '<li class="breadcrumb-item active"><a href="' . base_url() . '/permohonan/index">Permohonan Surat</a></li>',
'<li class="breadcrumb-item active">Edit Data</li>'
];
$data = [
'title' => 'Edit Permohonan : ' . $getMohon->jenis,
'ket' => $ket,
'link' => 'home',
'mohon' => $getMohon,
'surat' => $surat,
'user' => $this->penduduk->getPenduduk(session()->get('id_datauser')),
'isi' => $this->user->getUser(session()->id),
];
return view('mohon/edit', $data);
} else {
session()->setFlashdata('warning_mohon', 'Data permohonan tidak ditemukan.');
return redirect()->to(base_url() . '/permohonan/index');
}
}
public function update()
{
if (session()->get('level') == 1 or session()->get('level') == 2) {
$request = \Config\Services::request();
$id = $request->getPost('id_permohonan');
$jenis = $request->getPost('jenis');
if ($jenis != 'SKM') {
$hasil = 'Hasil Pemeriksaan KTP : ' . $request->getPost('ktp') . '<br>Hasil Pemeriksaan KK : ' . $request->getPost('kk');
if ($request->getPost('ktp') == 'KTP Sesuai' and $request->getPost('kk') == 'KK Sesuai') {
$ket = 'Diterima';
} else {
$ket = 'Ditolak';
}
} else {
$hasil = 'Hasil Pemeriksaan KTP : ' . $request->getPost('ktp') . '<br>Hasil Pemeriksaan KK : ' . $request->getPost('kk') . '<br>Hasil Pemeriksaan Jamkesmas : ' . $request->getPost('jamkes');
if ($request->getPost('ktp') == 'KTP Sesuai' and $request->getPost('kk') == 'KK Sesuai' and $request->getPost('jamkes') == 'Jamkesmas Sesuai') {
$ket = 'Diterima';
} else {
$ket = 'Ditolak';
}
}
$data = array(
'hasil' => $hasil,
'ket' => $ket
);
$this->model->editMohon($data, $id);
session()->setFlashdata('pesan_mohon', 'Data permohonan berhasi diedit.');
return redirect()->to(base_url() . '/permohonan/index');
} elseif (session()->get('level') == 3) {
$request = \Config\Services::request();
$id = $request->getPost('id_permohonan');
$ktp = $request->getFile('scan_ktp');
if ($ktp->getError() == 4) {
$nm_ktp = $request->getPost('lama');
} else {
$nm_ktp = $ktp->getRandomName();
$ktp->move('permohonan', $nm_ktp);
if ($request->getPost('lama') != 'no_img.png') {
unlink('permohonan/' . $request->getPost('lama'));
}
}
$kk = $request->getFile('scan_kk');
if ($kk->getError() == 4) {
$nm_kk = $request->getPost('lama');
} else {
$nm_kk = $kk->getRandomName();
$kk->move('permohonan', $nm_kk);
if ($request->getPost('lama') != 'no_img.png') {
unlink('permohonan/' . $request->getPost('lama'));
}
}
$jamkes = $request->getFile('scan_jamkes');
if ($jamkes->getError() == 4) {
$nm_jamkes = $request->getPost('lama');
} else {
$nm_jamkes = $jamkes->getRandomName();
$jamkes->move('permohonan', $nm_jamkes);
if ($request->getPost('lama') != 'no_img.png') {
unlink('permohonan/' . $request->getPost('lama'));
}
}
$data = array(
'jenis' => $request->getPost('jenis'),
'tujuan' => $request->getPost('tujuan'),
'tambahan' => $request->getPost('tambahan'),
'scan_ktp' => $nm_ktp,
'scan_kk' => $nm_kk,
'scan_jamkes' => $nm_jamkes,
'tgl_masuk' => date('Y-m-d'),
'id_penduduk' => session()->id_datauser,
'ket' => 'Belum Diperiksa'
);
$this->model->editMohon($data, $id);
session()->setFlashdata('pesan_mohon', 'Data permohonan berhasi diedit.');
return redirect()->to(base_url() . '/permohonan/index');
}
}
public function delete($id_permohonan)
{
$getMohon = $this->model->getMohon($id_permohonan);
if (isset($getMohon)) {
$this->model->hapusMohon($id_permohonan);
session()->setFlashdata('danger_mohon', 'Data Permohonan Berhasi Dihapus.');
return redirect()->to(base_url() . '/permohonan/index');
} else {
session()->setFlashdata('warning_mohon', 'Data Permohonan Tidak Ditemukan.');
return redirect()->to(base_url() . '/permohonan/index');
}
}
public function hapusbanyak()
{
$request = \Config\Services::request();
$id_permohonan = $request->getPost('id_permohonan');
if ($id_permohonan == null) {
session()->setFlashdata('warning_mohon', 'Data Permohonan Belum Dipilih, Silahkan Pilih Data Terlebih Dahulu.');
return redirect()->to(base_url() . '/permohonan/index');
}
$jmldata = count($id_permohonan);
for ($i = 0; $i < $jmldata; $i++) {
$this->model->hapusMohon($id_permohonan[$i]);
}
session()->setFlashdata('pesan_mohon', 'Data Permohonan Berhasi Dihapus Sebanyak ' . $jmldata . ' Data.');
return redirect()->to(base_url() . '/permohonan/index');
}
}
<file_sep>/app/Controllers/Skm.php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\SuratModel;
use App\Models\PendudukModel;
use App\Models\AlamatModel;
use App\Models\KeluargaModel;
use App\Models\PerangkatModel;
use App\Models\AuthModel;
use App\Models\GaleriModel;
use TCPDF;
class pdf extends TCPDF
{
public function Header()
{
$this->data = new AlamatModel();
$x = $this->data->getAlamat();
$kab = strtoupper($x->kab);
$kec = strtoupper($x->kec);
$nag = strtoupper($x->nagari);
$image_file = @FCPATH . 'aset\img\logo.png';
$this->SetY(10);
$this->SetFont('times', 'B', 12);
$isi_header = "
<table>
<tr>
<td width=\"70\"><img src=\"" . $image_file . "\" width=\"80\" height=\"80\"></td>
<td align=\"center\" style=\"font-size:17px\" width=\"90%\">
PEMERINTAHAN KABUPATEN " . $kab . "<br>
KECAMATAN " . $kec . "<br>
WALI NAGARI " . $nag . "
</td>
</tr>
<tr>
<td width=\"50%\">" . $x->alm . "</td>
<td width=\"50%\" align=\"right\">Kode Pos : " . $x->kd_pos . "</td>
</tr>
</table>
<hr>
";
$this->writeHTML($isi_header, true, false, false, false, '');
}
}
class Skm extends Controller
{
protected $model, $penduduk, $data, $keluarga, $perangkat;
public function __construct()
{
helper('form');
$this->model = new SuratModel();
$this->penduduk = new PendudukModel();
$this->data = new AlamatModel();
$this->keluarga = new KeluargaModel();
$this->perangkat = new PerangkatModel();
$this->user = new AuthModel();
$this->gal = new GaleriModel();
}
public function index()
{
$ket = [
'Data Surat Keterangan Miskin', '<li class="breadcrumb-item active"><a href="/skm/index">Data Surat Keterangan Miskin</a></li>'
];
$data = [
'title' => 'Data Surat Keterangan Miskin',
'ket' => $ket,
'link' => 'skm',
'surat' => $this->model->getSurat(false, 'SKM'),
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('surat/index', $data);
}
// View detail data
public function view($id_surat)
{
$x = $this->model->getSurat($id_surat, 'SKM');
$ket = [
'View Data Surat Keterangan Miskin', '<li class="breadcrumb-item active"><a href="/skm/index">Data Surat Keterangan Miskin</a></li>',
'<li class="breadcrumb-item active">View Data</li>'
];
$data = [
'title' => 'View Data Surat Keterangan Miskin',
'ket' => $ket,
'link' => 'skm',
'surat' => $x,
'data' => $this->data->getAlamat(),
'gal' => $this->gal->getGaleri(2),
'kk' => $this->keluarga->getKeluarga($x->id_keluarga),
'ttd' => $this->perangkat->getPerangkat($x->id_pemerintahan, 'Perangkat Nagari'),
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id),
'jenis_s' => 'SURAT KETERANGAN MISKIN',
'label_s' => '/SKM/KESRA',
'label' => 'Penghasilan Orang Tua'
];
return view('surat/view', $data);
}
public function nama($id_penduduk)
{
$data = $this->penduduk->id($id_penduduk, 'id_penduduk');
$json = array();
$json['nama'] = $data->tambahan;
return $this->response->setJson($json);
}
// Menampilkan form input
public function input()
{
$ket = [
'Tambah Data Surat Keterangan Miskin',
'<li class="breadcrumb-item active"><a href="/skm/index">Data Surat Keterangan Miskin</a></li>',
'<li class="breadcrumb-item active">Tambah Data</li>'
];
$data = [
'title' => 'Tambah Data Surat Keterangan Miskin',
'ket' => $ket,
'link' => 'skm',
'label' => 'Penghasilan Orang Tua',
'keluarga' => $this->keluarga->getKeluarga(),
'ttd' => $this->perangkat->ttd(),
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('surat/input', $data);
}
public function add()
{
$request = \Config\Services::request();
$max = $this->model->no('SKM');
$data = array(
'no_surat' => $max->x + 1,
'id_penduduk' => $request->getPost('id_penduduk'),
'id_pemerintahan' => $request->getPost('ttd'),
'tgl_surat' => date('Y-m-d'),
'jenis' => 'SKM',
'tujuan' => $request->getPost('tujuan'),
'tambahan' => $request->getPost('ket'),
);
$this->model->saveSurat($data);
return redirect()->to('skm/index');
}
public function print($id_surat)
{
$x = $this->model->getSurat($id_surat, 'SKM');
$c = $this->penduduk->id_array($x->id_keluarga, 'id_keluarga');
$z = 0;
for ($i = 0; $i < count($c); $i++) {
if ($c[$i]['status_hub'] != 'Kepala Keluarga') {
$kel[$z]['nama'] = $c[$i]['nama'];
$kel[$z]['jekel'] = $c[$i]['jekel'];
$kel[$z]['kerja'] = $c[$i]['kerja'];
$kel[$z]['status_hub'] = $c[$i]['status_hub'];
$kel[$z]['umur'] = date('Y') - date('Y', strtotime($c[$i]['tgl_lahir']));
$z++;
}
}
$data = [
'title' => 'View Data Surat Keterangan Miskin',
'surat' => $x,
'data' => $this->data->getAlamat(),
'kk' => $this->keluarga->getKeluarga($x->id_keluarga),
'ttd' => $this->perangkat->getPerangkat($x->id_pemerintahan, 'Perangkat Nagari'),
'ayah' => $this->penduduk->id($x->nik_ayah, 'nik'),
'ibu' => $this->penduduk->id($x->nik_ibu, 'nik'),
'kel' => $kel,
'jenis' => 'Miskin',
'link' => 'SKM'
];
$html = view('surat/printskm', $data);
$pdf = new pdf(PDF_PAGE_ORIENTATION, PDF_UNIT, 'F4', true, 'UTF-8', false);
$pdf->SetFont('times', '', 12);
$pdf->setHeaderMargin(20);
$pdf->setPrintHeader(true);
$pdf->setPrintFooter(true);
$pdf->SetMargins(20, 45, 20, true);
$pdf->AddPage();
$pdf->writeHTML($html);
$this->response->setContentType('application/pdf');
$pdf->Output('skm.pdf', 'I');
}
///edit data
public function edit($id_surat)
{
$surat = $this->model->getSurat($id_surat, 'SKM');
if (isset($surat)) {
$ket = [
'Edit ' . $surat->tambahan,
'<li class="breadcrumb-item active"><a href="/skm/index">Data Surat Keterangan Miskin</a></li>',
'<li class="breadcrumb-item active">Edit Data</li>'
];
$x = $this->penduduk->getPenduduk($surat->id_penduduk);
$data = [
'title' => 'Edit ' . $surat->tambahan,
'ket' => $ket,
'link' => 'skm',
'label' => 'Penghasilan Orang Tua',
'keluarga' => $this->keluarga->getKeluarga(),
'surat' => $surat,
'kel' => $x,
'penduduk' => $this->penduduk->id_array($surat->id_keluarga, 'id_keluarga'),
'ttd' => $this->perangkat->ttd(),
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('surat/edit', $data);
} else {
session()->setFlashdata('warning_surat', 'Surat tanggal : ' . $surat->tambahan . ' Tidak Ditemukan.');
return redirect()->to('skm/index');
}
}
public function update()
{
$request = \Config\Services::request();
$id_surat = $request->getPost('id_surat');
$max = $this->model->no('SKM');
$data = array(
'no_surat' => $max->x + 1,
'id_penduduk' => $request->getPost('id_penduduk'),
'id_pemerintahan' => $request->getPost('ttd'),
'tgl_surat' => date('Y-m-d'),
'jenis' => 'SKM',
'tujuan' => $request->getPost('tujuan'),
'tambahan' => $request->getPost('ket'),
);
$this->model->editSurat($data, $id_surat);
session()->setFlashdata('pesan_surat', 'Data Surat Keterangan Miskin Berhasi Diedit.');
return redirect()->to('skm/index');
}
// Menghapus data
public function delete($id_surat)
{
$surat = $this->model->getSurat($id_surat, 'SKM');
if (isset($surat)) {
$this->model->hapusSurat($id_surat);
session()->setFlashdata('danger_surat', 'Data Surat Keterangan Miskin : ' . $surat->tambahan . ' Berhasi Dihapus.');
return redirect()->to('skm/index');
} else {
session()->setFlashdata('warning_surat', 'Data Surat Keterangan Miskin : ' . $surat->tambahan . ' Tidak Ditemukan.');
return redirect()->to('skm/index');
}
}
// Menghapus data pilihan
public function hapusbanyak()
{
$request = \Config\Services::request();
$id_surat = $request->getPost('id_surat');
if ($id_surat == null) {
session()->setFlashdata('warning_surat', 'Data Pejabat dan berita Desa Belum Dipilih, Silahkan Pilih Data Terlebih Dahulu.');
$data['title'] = 'Data Surat Keterangan Miskin dan Pejabat Desa';
return redirect()->to('skm/index');
}
$jmldata = count($id_surat);
$x = 0;
for ($i = 0; $i < $jmldata; $i++) {
$this->model->hapusSurat($id_surat[$i]);
$x++;
}
session()->setFlashdata('pesan_surat', 'Data Pejabat dan berita Desa Berhasi Dihapus Sebanyak ' . $x . ' Data.');
$data['title'] = 'Data Surat Keterangan Miskin dan Pejabat Desa';
return redirect()->to('skm/index');
}
}
<file_sep>/app/Views/keluarga/edit.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<!-- Main content -->
<section class="content">
<?php
use PhpParser\Node\Stmt\Echo_;
if (session()->getFlashdata('error')) { ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('error'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php } ?>
<form method="post" action="<?= base_url('keluarga/update'); ?>">
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-id-card mr-1"></i>
Data Kartu Keluarga
</h3>
</div>
<div class="container-fluid card-body">
<?= csrf_field(); ?>
<div class="row mb-3">
<label for="no_kk" class="col-sm-2 col-form-label">No Kartu Keluarga</label>
<div class="col-sm-10">
<input value="<?= $keluarga->no_kk; ?>" required autocomplete="off" autofocus placeholder="0000000000000000" minlength="16" maxlength="16" type="text" class="form-control" name="no_kk" id="no_kk">
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-user mr-1"></i>
Data Pribadi Kepala Keluarga
</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse">
<i class="fas fa-minus"></i>
</button>
</div>
</div>
<div class="container-fluid card-body">
<?= csrf_field(); ?>
<div class="row mb-3">
<label for="nik" class="col-sm-2 col-form-label">NIK</label>
<div class="col-sm-10">
<input value="<?= $keluarga->nik_kepala; ?>" autocomplete="off" type="text" placeholder="0000000000000000" maxlength="16" minlength="16" class="form-control" id="nik" name="nik" required>
</div>
</div>
<div class="row mb-3">
<label for="nama" class="col-sm-2 col-form-label">Nama</label>
<div class="col-sm-10">
<input value="<?= $penduduk->nama; ?>" autocomplete="off" type="text" placeholder="Masukkan Nama" class="form-control" id="nama" name="nama" required>
</div>
</div>
<div class="row mb-3">
<label for="tpt_lahir" class="col-sm-2 col-form-label">Tempat Lahir</label>
<div class="col-sm-10">
<input value="<?= $penduduk->tpt_lahir; ?>" autocomplete="off" type="text" placeholder="Masukkan Tempat Lahir" class="form-control" id="tpt_lahir" name="tpt_lahir" required>
</div>
</div>
<div class="row mb-3">
<label for="tgl_lahir" class="col-sm-2 col-form-label">Tanggal Lahir</label>
<div class="col-sm-10">
<input value="<?= $penduduk->tgl_lahir; ?>" autocomplete="off" placeholder="yyyy-mm-dd" type="date" id="datepicker" class="form-control" name="tgl_lahir" required>
</div>
</div>
<div class="row mb-3">
<label for="jekel" class="col-sm-2 col-form-label">Jenis Kelamin</label>
<div class="col-sm-10">
<input <?php if ($penduduk->jekel == 'Laki - Laki') echo 'checked' ?> type="radio" name="jekel" value="Laki - Laki"> Laki - laki
<input <?php if ($penduduk->jekel == 'Perempuan') echo 'checked' ?> type="radio" name="jekel" value="Perempuan"> Perempuan
</div>
</div>
<div class="row mb-3">
<label for="alamat" class="col-sm-2 col-form-label">Alamat</label>
<div class="col-sm-10">
<select required class="form-control select2bs4" name="alamat" id="alamat" required autocomplete="off">
<option value="">Pilih Alamat </option>
<?php
$data = array(
"Jorong Gunuang Rajo Utara", "Jorong Gantiang"
);
for ($i = 0; $i < count($data); $i++) {
?>
<option <?php if ($keluarga->alamat == $data[$i]) echo 'selected' ?> value="<?php echo $data[$i] ?>"><?php echo $data[$i] ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row mb-3">
<label for="kwn" class="col-sm-2 col-form-label">Kewarganegaraan</label>
<div class="col-sm-10">
<div class="col-sm-10">
<input <?php if ($penduduk->kwn == 'WNI') echo 'checked' ?> type="radio" name="kwn" value="WNI" checked> WNI
<input <?php if ($penduduk->kwn == 'WNA') echo 'checked' ?> type="radio" name="kwn" value="WNA"> WNA
</div>
</div>
</div>
<div class="row mb-3">
<label for="agama" class="col-sm-2 col-form-label">Agama</label>
<div class="col-sm-10">
<select class="form-control select2bs4" name="agama" id="agama" required>
<option value="">Pilih Agama</option>
<?php
foreach ($agama as $agama) {
?>
<option <?php if ($agama['nama'] == $penduduk->agama) echo 'selected' ?> value="<?php echo $agama['nama'] ?>"><?php echo $agama['nama'] ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row mb-3">
<label for="status_kawin" class="col-sm-2 col-form-label">Status Perkawinan</label>
<div class="col-sm-10">
<select class="form-control select2bs4" name="status_kawin" id="status_kawin" required>
<option value="">Pilih Status </option>
<?php
foreach ($status_kawin as $status_kawin) {
?>
<option <?php if ($status_kawin['nama'] == $penduduk->status_kawin) echo 'selected' ?> value="<?php echo $status_kawin['nama'] ?>"><?php echo $status_kawin['nama'] ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row mb-3">
<label for="status_hub" class="col-sm-2 col-form-label">Status Hubungan</label>
<div class="col-sm-10">
<input autocomplete="off" type="text" readonly value="Kepala Keluarga" class="form-control" id="status_hub" name="status_hub" required>
</div>
</div>
<div class="row mb-3">
<label for="goldar" class="col-sm-2 col-form-label">Golongan Darah</label>
<div class="col-sm-10">
<select class="form-control select2bs4" name="goldar" id="goldar" required>
<option value="">Pilih Golongan Darah</option>
<?php
$goldar = [
'A', 'B', 'AB', 'O', '-'
];
foreach ($goldar as $goldar) {
?>
<option <?php if ($goldar == $penduduk->goldar) echo 'selected' ?> value="<?php echo $goldar ?>"><?php echo $goldar ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row mb-3">
<label for="pendidikan" class="col-sm-2 col-form-label">Pendidikan</label>
<div class="col-sm-10">
<select class="form-control select2bs4" name="pendidikan" id="pendidikan" required>
<option value="">Pilih Pendidikan</option>
<?php
foreach ($pendidikan as $pendidikan) {
?>
<option <?php if ($pendidikan['nama'] == $penduduk->pendidikan) echo 'selected' ?> value="<?php echo $pendidikan['nama'] ?>"><?php echo $pendidikan['nama'] ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row mb-3">
<label for="kerja" class="col-sm-2 col-form-label">Pekerjaan</label>
<div class="col-sm-10">
<select class="form-control select2bs4" name="kerja" id="kerja" required>
<option value="">Pilih Pekerjaan </option>
<?php
foreach ($pekerjaan as $pekerjaan) {
?>
<option <?php if ($pekerjaan['nama'] == $penduduk->kerja) echo 'selected' ?> value="<?php echo $pekerjaan['nama'] ?>"><?php echo $pekerjaan['nama'] ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row mb-3">
<label for="paspor" class="col-sm-2 col-form-label">No Paspor</label>
<div class="col-sm-10">
<input value="<?= $penduduk->paspor; ?>" autocomplete="off" type="text" placeholder="Masukkan No Paspor" class="form-control" id="paspor" name="paspor">
</div>
</div>
<div class="row mb-3">
<label for="kitap" class="col-sm-2 col-form-label">No Kitap</label>
<div class="col-sm-10">
<input value="<?= $penduduk->kitap; ?>" autocomplete="off" type="text" placeholder="Masukkan No Kitap" class="form-control" id="kitap" name="kitap">
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-user mr-1"></i>
Data Keluarga Kepala Keluarga
</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse">
<i class="fas fa-minus"></i>
</button>
</div>
</div>
<div class="container-fluid card-body">
<?= csrf_field(); ?>
<div class="row mb-3">
<label for="nm_ayah" class="col-sm-2 col-form-label">Nama Ayah</label>
<div class="col-sm-10">
<input value="<?= $penduduk->nm_ayah; ?>" autocomplete="off" type="text" placeholder="Masukkan Nama Ayah" class="form-control" id="nm_ayah" name="nm_ayah" required>
</div>
</div>
<div class="row mb-3">
<label for="nik_ayah" class="col-sm-2 col-form-label">NIK Ayah</label>
<div class="col-sm-10">
<input value="<?= $penduduk->nik_ayah; ?>" autocomplete="off" type="text" placeholder="Masukkan NIK Ayah" class="form-control" id="nik_ayah" name="nik_ayah">
</div>
</div>
<div class="row mb-3">
<label for="nm_ibu" class="col-sm-2 col-form-label">Nama Ibu</label>
<div class="col-sm-10">
<input value="<?= $penduduk->nm_ibu; ?>" autocomplete="off" type="text" placeholder="Masukkan Nama Ibu" class="form-control" id="nm_ibu" name="nm_ibu" required>
</div>
</div>
<div class="row mb-3">
<label for="nik_ibu" class="col-sm-2 col-form-label">NIK Ibu</label>
<div class="col-sm-10">
<input value="<?= $penduduk->nik_ibu; ?>" autocomplete="off" type="text" placeholder="Masukkan NIK Ibu" class="form-control" id="nik_ibu" name="nik_ibu">
</div>
</div>
<input type="hidden" name="id_keluarga" id="id_keluarga" value="<?= $keluarga->id_keluarga; ?>">
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</section>
<!-- /.content -->
<!-- /.content -->
<?= $this->endSection(); ?><file_sep>/app/Views/mohon/edit.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<!-- Main content -->
<section class="content">
<?php if (session()->getFlashdata('error')) { ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('error'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php } ?>
<form method="post" action="<?= base_url('/permohonan/update'); ?>" enctype="multipart/form-data">
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-edit mr-1"></i>
<?= $title; ?>
</h3>
</div>
<div class="container-fluid card-body">
<?= csrf_field(); ?>
<div class="row mb-3">
<label for="jenis" class="col-sm-2 col-form-label">Jenis Surat</label>
<div class="col-sm-10">
<select onchange="surat()" class="form-control" name="jenis" id="jenis" data-id="getkomponen" required>
<option value="">Pilih Jenis Surat</option>
<?php
for ($i = 0; $i < count($surat); $i++) {
?>)
<option <?php if ($mohon->jenis == $surat[$i]) {
echo 'selected';
} ?> value="<?php echo $surat[$i] ?>"><?php echo $surat[$i] ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row mb-3">
<label for="tujuan" class="col-sm-2 col-form-label">Tujuan Surat</label>
<div class="col-sm-10">
<input autocomplete="off" value="<?= $mohon->tujuan; ?>" type="text" placeholder="Masukkan Tujuan Surat" class="form-control" id="tujuan" name="tujuan" required>
</div>
</div>
<div class="row mb-3" id="divtambah" style="display: none;">
<label for="tambahan" id="labeltambahan" class="col-sm-2 col-form-label">Keterangan Tambahan</label>
<div class="col-sm-10">
<input autocomplete="off" value="<?= $mohon->tambahan; ?>" type="text" placeholder="Masukkan Keterangan Tambahan" class="form-control" id="tambahan" name="tambahan" required>
</div>
</div>
<div class="row mb-3">
<label for="scan_ktp" class="col-sm-2 col-form-label label">Scan KTP</label>
<div class="col-sm-1">
<img class="img-thumbnail img-preview" src="<?= base_url(); ?>/permohonan/<?= $mohon->scan_ktp; ?>" alt="">
</div>
<div class="col-sm-9">
<div class="custom-file">
<input type="file" class="custom-file-input" id="fotoo" name="scan_ktp" onchange="previewImg()">
<input type="hidden" name="lama" value="<?= $mohon->scan_ktp; ?>">
<p style="color: red">Ekstensi yang diperbolehkan .png | .jpg | .jpeg (Ukuran Max 2 MB)</p>
<label for="scan_ktp" class="custom-file-label"><?= $mohon->scan_ktp; ?></label>
</div>
</div>
</div>
<div class="row mb-3">
<label for="scan_kk" class="col-sm-2 col-form-label label">Scan KK</label>
<div class="col-sm-1">
<img class="img-thumbnail img-preview img_prev1" src="<?= base_url(); ?>/permohonan/<?= $mohon->scan_kk; ?>" alt="">
</div>
<div class="col-sm-9">
<div class="custom-file">
<input type="file" class="custom-file-input" id="foto1" name="scan_kk" onchange="previewImg()">
<input type="hidden" name="lama" value="<?= $mohon->scan_kk; ?>">
<p style="color: red">Ekstensi yang diperbolehkan .png | .jpg | .jpeg (Ukuran Max 2 MB)</p>
<label for="scan_kk" class="custom-file-label img_lab1"><?= $mohon->scan_kk; ?></label>
</div>
</div>
</div>
<div class="row mb-3" id="divjamkes" style="display: none;">
<label for="scan_jamkes" class="col-sm-2 col-form-label label">Scan Jamkesmas</label>
<div class="col-sm-1">
<img class="img-thumbnail img-preview img_prev2" src="<?= base_url(); ?>/permohonan/<?= $mohon->scan_jamkes; ?>" alt="">
</div>
<div class="col-sm-9">
<div class="custom-file">
<input type="file" class="custom-file-input" id="foto2" name="scan_jamkes" onchange="previewImg()">
<input type="hidden" name="lama" value="<?= $mohon->scan_jamkes; ?>">
<p style="color: red">Ekstensi yang diperbolehkan .png | .jpg | .jpeg (Ukuran Max 2 MB)</p>
<label for="scan_jamkes" class="custom-file-label img_lab2"><?= $mohon->scan_jamkes; ?></label>
</div>
</div>
</div>
<input type="hidden" name="id_permohonan" value="<?= $mohon->id_permohonan; ?>">
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</section>
<!-- /.content -->
<!-- /.content -->
<?= $this->endSection(); ?><file_sep>/app/Views/web/perangkat.php
<?= $this->extend('web/template'); ?>
<?= $this->section('content'); ?>
<main id="main">
<div class="row">
<div class="col-md-9">
<section style="padding: 40px; background: #f8fcfd;">
<div class="row" align="center">
<?php if ($data != NULL) {
foreach ($data as $data) { ?>
<div class="col-md-3 h" style="padding: 10px;">
<div style="word-wrap: break-word;">
<p><b><?= $data['jabatan']; ?></b></p>
</div>
<div>
<img src="<?= base_url(); ?>/perangkat/<?= $data['foto']; ?>" alt="" width="75%">
</div>
<div>
<?= $data['nama']; ?>
</div>
</div>
<?php }
} ?>
</div>
</section>
</div>
<div class="col-md-3" style="margin-top: 40px; padding-right: 35px;">
<h5 align=" center"><b>Berita Terbaru</b></h5>
<hr>
<?php if ($berita == NULL) { ?>
<div class="row h" style="word-wrap: break-word; padding: 10px;">
Berita belum ada
</div>
<?php } ?>
<?php
foreach ($berita as $data) {
?>
<div class="row h" style="word-wrap: break-word; padding: 10px;">
<a href="<?= base_url('/web/isi/' . $data['id_berita']) ?>" style="color: black;">
<p><b><?= $data['judul']; ?></b></p>
<?= substr($data['isi'], 0, 50); ?>
<p style="color: #061F2D;"> Baca Selengkapnya...</p>
</a>
</div>
<hr>
<?php } ?>
</div>
</div>
</main>
<?= $this->endSection(); ?><file_sep>/app/Views/aduan/view.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<?= $this->include('template/tgl'); ?>
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-eye mr-1"></i>
View Data : Aduan - <?= tgl_indo($aduan->tgl_aduan); ?>
</h3>
<div class="card-tools">
<ul class="nav nav-pills ml-auto">
<li class="nav-item">
<button type="button" style="margin-left: 10vh;" class="btn btn-success">
<?php if (session()->get('level') == 1 or session()->get('level') == 2) { ?>
<a href="<?php echo base_url('/aduan/view/' . $aduan->id_aduan . '/belum'); ?>" style="color: white;">
<?php } elseif (session()->get('level') == 3) { ?>
<a href="<?php echo base_url('/aduan/edit/' . $aduan->id_aduan); ?>" style="color: white;">
<?php } ?>
<i class="far fa-plus-square"> Edit Data</i>
</a>
</button>
</li>
</ul>
</div>
</div>
<div class="card-body">
<table class="table">
<tr>
<th>Tanggal Aduan</th>
<td> : <?= tgl_indo($aduan->tgl_aduan); ?></td>
</tr>
<tr>
<th>Status</th>
<td> : <?= $aduan->ket; ?></td>
</tr>
<tr>
<th>Gambar</th>
<td> : <img style="max-width: 50%;" src="<?= base_url(); ?>/aduan/<?= $aduan->gambar; ?>" alt=""></td>
</tr>
<tr>
<th>Isi Aduan</th>
<td> : <?= $aduan->aduan; ?></td>
</tr>
<tr>
<th>Tanggal Respon</th>
<td> : <?php if ($aduan->tgl_respon != NULL) {
echo tgl_indo($aduan->tgl_respon);
} else {
echo 'Belum ada respon';
} ?></td>
</tr>
<tr>
<th>Respon</th>
<td> : <?php if ($aduan->respon != NULL) {
echo $aduan->respon;
} else {
echo 'Belum ada respon';
} ?></td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
<?= $this->endSection(); ?><file_sep>/app/Views/web/wilayah.php
<?= $this->extend('web/template'); ?>
<?= $this->section('content'); ?>
<main id="main">
<div class="row">
<div class="col-md-9">
<section style="padding: 40px; background: #f8fcfd;">
<div style="padding: 10px;">
<h1><b>Kondisi Geografis</b></h1>
<?= $data->wilayah; ?>
</div>
<div style="padding: 10px;">
<h1><b>Peta Wilayah</b></h1>
<?= $alm->map_wilayah; ?>
</div>
</section>
</div>
<div class="col-md-3" style="margin-top: 40px; padding-right: 35px;">
<h5 align=" center"><b>Berita Terbaru</b></h5>
<hr>
<?php if ($berita == NULL) { ?>
<div class="row h" style="word-wrap: break-word; padding: 10px;">
Berita belum ada
</div>
<?php } ?>
<?php
foreach ($berita as $data) {
?>
<div class="row h" style="word-wrap: break-word; padding: 10px;">
<a href="<?= base_url('/web/isi/' . $data['id_berita']) ?>" style="color: black;">
<p><b><?= $data['judul']; ?></b></p>
<?= substr($data['isi'], 0, 50); ?>
<p style="color: #061F2D;"> Baca Selengkapnya...</p>
</a>
</div>
<hr>
<?php } ?>
</div>
</div>
</main>
<?= $this->endSection(); ?><file_sep>/app/Views/web/isiberita.php
<?= $this->extend('web/template'); ?>
<?= $this->section('content'); ?>
<div style="height: 90px;">
</div>
<main id="main">
<div class="row">
<div class="col-md-9">
<section style="padding: 40px; background: #f8fcfd;">
<div align="center">
<h3><b><?= $data->judul; ?></b></h3>
<?php if ($data->gambar != NULL and $data->gambar != 'no_image.png') { ?>
<img src="<?= base_url(); ?>/berita/<?= $data->gambar; ?>" alt="Foto <?= $data->judul; ?>" height="300wh">
<?php } ?>
</div>
<div class="row" style="margin-top: 30px;">
<div class="col">Admin</div>
<div class="col" align="right"><?= $data->tgl_update; ?></div>
</div>
<div style="word-wrap: break-word; margin-top: 30px;">
<?= $data->isi; ?>
</div>
</section>
</div>
<div class="col-md-3" style="margin-top: 40px; padding-right: 35px;">
<h5 align=" center"><b>Berita Terbaru</b></h5>
<hr>
<?php if ($berita == NULL) { ?>
<div class="row h" style="word-wrap: break-word; padding: 10px;">
Berita belum ada
</div>
<?php } ?>
<?php
foreach ($berita as $data) {
?>
<div class="row h" style="word-wrap: break-word; padding: 10px;">
<a href="<?= base_url('/web/isi/' . $data['id_berita']) ?>" style="color: black;">
<p><b><?= $data['judul']; ?></b></p>
<?= substr($data['isi'], 0, 50); ?>
<p style="color: #061F2D;"> Baca Selengkapnya...</p>
</a>
</div>
<hr>
<?php } ?>
</div>
</div>
</main>
<?= $this->endSection(); ?><file_sep>/app/Models/SuratModel.php
<?php
namespace App\Models;
use CodeIgniter\Model;
class SuratModel extends Model
{
protected $table = 'surat';
public function getSurat($id_surat = false, $jenis = false)
{
if ($id_surat === false) {
return $this->db->table('surat')
->join('penduduk', 'penduduk.id_penduduk = surat.id_penduduk')
->where('jenis', $jenis)->orderBy('id_surat', 'DESC')
->get()->getResultArray();
} else {
return $this->db->table('surat')
->join('penduduk', 'penduduk.id_penduduk = surat.id_penduduk')
->getWhere(['id_surat' => $id_surat])->getRow();
}
}
public function saveSurat($data)
{
$builder = $this->db->table($this->table);
return $builder->insert($data);
}
public function editSurat($data, $id_surat)
{
$builder = $this->db->table($this->table);
$builder->where('id_surat', $id_surat);
return $builder->update($data);
}
public function hapusSurat($id_surat)
{
$builder = $this->db->table($this->table);
return $builder->delete(['id_surat' => $id_surat]);
}
public function no($input)
{
return $this->select('max(no_surat) as x')->getWhere(['jenis' => $input])->getRow();
}
}
<file_sep>/app/Controllers/Profile.php
<?php
namespace App\Controllers;
use App\Models\PendudukModel;
use App\Models\AuthModel;
use App\Models\PerangkatModel;
class Profile extends BaseController
{
protected $model, $user;
public function __construct()
{
helper('form');
// Deklarasi model
$this->model = new PendudukModel();
$this->user = new AuthModel();
$this->perangkat = new PerangkatModel();
}
public function index()
{
$ket = [
'Profile', '<li class="breadcrumb-item active"><a href="' . base_url() . '/profile/index">Profile</a></li>'
];
$data = [
'title' => 'Sistem Informasi Nagari',
'ket' => $ket,
'link' => 'home',
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('profile/adminprof', $data);
}
public function editadmin()
{
$getUser = $this->user->getUser(session()->id);
$x = $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari');
if (isset($getUser)) {
$ket = [
'Edit Data : ' . $x->nama, '<li class="breadcrumb-item active"><a href="' . base_url() . '/profile/index">Profile</a></li>',
'<li class="breadcrumb-item active">Edit Profile</li>'
];
$data = [
'title' => 'Edit Data : ' . $x->nama,
'ket' => $ket,
'data' => $getUser,
'link' => 'home',
'user' => $x,
'isi' => $getUser
];
return view('profile/editadmin', $data);
} else {
session()->setFlashdata('warning_profile', 'User ' . session()->username . ' tidak ditemukan.');
return redirect()->to(base_url() . '/profile/editadmin');
}
}
public function updatadmin()
{
$request = \Config\Services::request();
$id = $request->getPost('id');
$file = $request->getFile('foto');
if ($file->getError() == 4) {
$nm = $request->getPost('lama');
} else {
if (session()->level == 3) {
$folder = 'penduduk';
} else {
$folder = 'perangkat';
}
$nm = $file->getRandomName();
$file->move($folder, $nm);
if ($request->getPost('lama') != 'default.svg') {
unlink($folder . '/' . $request->getPost('lama'));
}
}
$pass = $request->getPost('pass');
if ($pass != NULL) {
$data = array(
'password' => password_hash($pass, PASSWORD_BCRYPT)
);
$this->user->editUser($data, $id);
}
$data = array(
'email' => $request->getPost('email'),
'username' => $request->getPost('username'),
'telp' => $request->getPost('telp'),
'foto' => $nm,
);
$this->user->editUser($data, $id);
$data2 = array(
'nik' => $request->getPost('nik'),
);
$this->perangkat->editPerangkat($data2, session()->get('id_datauser'));
session()->setFlashdata('pesan_profile', 'Pofile berhasi diedit.');
return redirect()->to(base_url() . '/profile/index');
}
public function edit()
{
$getUser = $this->user->getUser(session()->id);
$x = $this->model->getPenduduk(session()->id_datauser);
if (isset($getUser)) {
$ket = [
'Edit Data Profile',
'<li class="breadcrumb-item active">Edit Profile</li>'
];
$data = [
'title' => 'Edit Data Profile',
'ket' => $ket,
'data' => $getUser,
'link' => 'home',
'user' => $x,
'isi' => $getUser
];
return view('profile/edit', $data);
} else {
session()->setFlashdata('warning_profile', 'User ' . session()->username . ' tidak ditemukan.');
return redirect()->to(base_url() . '/profile/edit');
}
}
public function update()
{
$request = \Config\Services::request();
$id = $request->getPost('id');
$file = $request->getFile('foto');
if ($file->getError() == 4) {
$nm = $request->getPost('lama');
} else {
if (session()->level == 3) {
$folder = 'penduduk';
} else {
$folder = 'perangkat';
}
$nm = $file->getRandomName();
$file->move($folder, $nm);
if ($request->getPost('lama') != 'default.svg') {
unlink($folder . '/' . $request->getPost('lama'));
}
}
$pass = $request->getPost('pass');
if ($pass != NULL) {
$data = array(
'password' => password_hash($pass, PASSWORD_<PASSWORD>)
);
$this->user->editUser($data, $id);
}
$data = array(
'email' => $request->getPost('email'),
'username' => $request->getPost('username'),
'telp' => $request->getPost('telp'),
'foto' => $nm,
);
$this->user->editUser($data, $id);
session()->setFlashdata('pesan_profile', 'Pofile berhasi diedit.');
return redirect()->to(base_url() . '/home/index');
}
}
<file_sep>/app/Views/mohon/view.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<?= $this->include('template/tgl'); ?>
<!-- Main content -->
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-eye mr-1"></i>
View Data : <?= $mohon->jenis; ?> ~ <?= tgl_indo($mohon->tgl_masuk); ?>
</h3>
<?php if (session()->get('level') == 3) { ?>
<div class="card-tools">
<ul class="nav nav-pills ml-auto">
<li class="nav-item">
<button type="button" style="margin-left: 10vh;" class="btn btn-success">
<a href="<?php echo base_url('/permohonan/edit/' . $mohon->id_permohonan); ?>" style="color: white;">
<i class="far fa-plus-square"> Edit Data</i>
</a>
</button>
</li>
</ul>
</div>
<?php } ?>
<?php if ((session()->get('level') == 1 or session()->get('level') == 2) and $mohon->ket == 'Diterima') { ?>
<div class="card-tools">
<ul class="nav nav-pills ml-auto">
<li class="nav-item">
<button type="button" style="margin-left: 10vh;" class="btn btn-success">
<a href="<?php echo base_url('/permohonan/surat/' . $mohon->id_permohonan); ?>" style="color: white;">
<i class="far fa-plus-square"> Buat Surat</i>
</a>
</button>
</li>
</ul>
</div>
<?php } ?>
</div><!-- /.card-header -->
<div class="card-body">
<table class="table">
<tr>
<th>Jenis Surat</th>
<td> : </td>
<td><?= $mohon->jenis; ?></td>
</tr>
<tr>
<th>Tanggal Permohoanan Surat</th>
<td> : </td>
<td><?= tgl_indo($mohon->tgl_masuk); ?></td>
</tr>
<tr>
<th>Status</th>
<td> : </td>
<td><b><u><?= $mohon->ket; ?></u></b></td>
</tr>
<tr>
<th>Tujuan Surat</th>
<td> : </td>
<td><?= $mohon->tujuan; ?></td>
</tr>
<tr>
<th><?php if ($mohon->jenis == 'SKU') {
echo 'Jenis Usaha';
} else {
echo 'Penghasilan Orang Tua';
} ?></th>
<td> : </td>
<td><?php if ($mohon->jenis == 'SKU') {
echo $mohon->tambahan;
} else {
echo 'Rp' . number_format($mohon->tambahan, 2, ',', '.');
} ?></td>
</tr>
<tr>
<th>Hasil Pemeriksaan</th>
<td> : </td>
<td><?php if ($mohon->hasil != NULL) {
echo $mohon->hasil;
} else {
echo 'Belum ada';
} ?></td>
</tr>
</table>
<table class="table">
<tr>
<th>Lampiran Scan KTP : </th>
<th>Lampiran Scan KK : </th>
</tr>
<tr>
<td><img src="<?= base_url(); ?>/permohonan/<?= $mohon->scan_ktp; ?>" alt="Scan KTP" width="100%"></td>
<td><img src="<?= base_url(); ?>/permohonan/<?= $mohon->scan_kk; ?>" alt="Scan KK" width="100%"></td>
</tr>
</table>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</div>
<!-- /.container-fluid -->
</section>
<!-- /.content -->
<!-- /.content -->
<?= $this->endSection(); ?><file_sep>/app/Views/user/index.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<!-- Main content -->
<section class="content">
<?= form_open('user/hapusbanyak', ['class' => 'formhapus']) ?>
<div class="container-fluid">
<div class="row">
<div class="col-12">
<?php if (session()->getFlashdata('pesan_user')) : ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('pesan_user'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php elseif (session()->getFlashdata('danger_user')) : ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('danger_user'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php elseif (session()->getFlashdata('warning_user')) : ?>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('warning_user'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-newspaper mr-1"></i>
<?= $ket[0]; ?>
</h3>
<div class="card-tools">
<ul class="nav nav-pills ml-auto">
<li class="nav-item">
<a class="nav-link active" href="#admin" data-toggle="tab">Admin</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#perangkat" data-toggle="tab">Operator</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#warga" data-toggle="tab">Warga</a>
</li>
<li class="nav-item">
<button type="submit" style="margin-left: 10px;" class="btn btn-danger tombolHapusBanyak" onclick="javascript:return confirm('Apakah ingin menghapus data ini ?')">
<i class="far fa-trash-alt"> Hapus</i>
</button>
</li>
</ul>
</div>
</div>
<div class="card-body">
<div class="tab-content p-0">
<div class="tab-pane active" id="admin" style="position: relative;">
<div style="margin-bottom: 20px;">
<button type="button" class="btn btn-success">
<a href="<?php echo base_url('user/input/1'); ?>" style="color: white;">
<i class="far fa-plus-square"> Tambah Data</i>
</a>
</button>
</div>
<table id="example2" class="table table-bordered table-hover">
<thead class="thead-dark" style="text-align: center;">
<tr>
<th>
<input type="checkbox" id="centangsemua">
</th>
<th>No</th>
<th>Nama</th>
<th>Username</th>
<th>Email</th>
<th>Pass</th>
<th>Aksi</th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
foreach ($data_admin as $data) {
?>
<tr>
<td style="text-align: center;">
<input type="checkbox" id="check" name="id[]" class="centang" value="<?= $data['id']; ?>">
</td>
<td><?= $no; ?></td>
<td><?= $data['nama']; ?></td>
<td><?= $data['username']; ?></td>
<td><?= $data['email']; ?></td>
<td style="text-align: center;">
<button type="button" class="btn btn-outline-danger">
<a href="<?= base_url(); ?>/user/reset/<?= $data['id']; ?>" style="text-decoration: none;color: black;">Reset</a>
</button>
</td>
<td style="text-align: center;">
<a href="<?php echo base_url('user/edit/' . $data['id']); ?>" style="color: black;">
<li class="far fa-edit"></li>
</a>
<a href="<?php echo base_url('user/view/' . $data['id']); ?>" style="color: black;">
<li class="far fa-eye"></li>
</a>
<a href="<?php echo base_url('user/delete/' . $data['id']); ?>" onclick="javascript:return confirm('Apakah Anda Yakin Ingin Menghapus Data Ini?')" style="color: black;">
<li class="far fa-trash-alt"></li>
</a>
</td>
</tr>
<?php $no++;
}
?>
</tbody>
</table>
</div>
<div class="tab-pane" id="perangkat" style="position: relative;">
<div style="margin-bottom: 20px;">
<button type="button" class="btn btn-success">
<a href="<?php echo base_url('user/input/2'); ?>" style="color: white;">
<i class="far fa-plus-square"> Tambah Data</i>
</a>
</button>
</div>
<table id="example2-2" class="table table-bordered table-hover">
<thead class="thead-dark" style="text-align: center;">
<tr>
<th>
<input type="checkbox" id="centangsemua2">
</th>
<th>No</th>
<th>Nama</th>
<th>Username</th>
<th>Email</th>
<th>Pass</th>
<th>Aksi</th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
foreach ($data_perangkat as $data) {
?>
<tr>
<td style="text-align: center;">
<input type="checkbox" id="check" name="id[]" class="centang" value="<?= $data['id']; ?>">
</td>
<td><?= $no; ?></td>
<td><?= $data['nama']; ?></td>
<td><?= $data['username']; ?></td>
<td><?= $data['email']; ?></td>
<td style="text-align: center;">
<button type="button" class="btn btn-outline-danger">
<a href="<?= base_url(); ?>/user/reset/<?= $data['id']; ?>" style="text-decoration: none;color: black;">Reset</a>
</button>
</td>
<td style="text-align: center;">
<a href="<?php echo base_url('user/edit/' . $data['id']); ?>" style="color: black;">
<li class="far fa-edit"></li>
</a>
<a href="<?php echo base_url('user/view/' . $data['id']); ?>" style="color: black;">
<li class="far fa-eye"></li>
</a>
<a href="<?php echo base_url('user/delete/' . $data['id']); ?>" onclick="javascript:return confirm('Apakah Anda Yakin Ingin Menghapus Data Ini?')" style="color: black;">
<li class="far fa-trash-alt"></li>
</a>
</td>
</tr>
<?php $no++;
}
?>
</tbody>
</table>
</div>
<div class="tab-pane" id="warga" style="position: relative;">
<div style="margin-bottom: 20px;">
<button type="button" class="btn btn-success">
<a href="<?php echo base_url('user/input/3'); ?>" style="color: white;">
<i class="far fa-plus-square"> Tambah Data</i>
</a>
</button>
</div>
<table id="example2-3" class="table table-bordered table-hover">
<thead class="thead-dark" style="text-align: center;">
<tr>
<th>
<input type="checkbox" id="centangsemua3">
</th>
<th>No</th>
<th>Nama</th>
<th>Username</th>
<th>Email</th>
<th>Pass</th>
<th>Aksi</th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
foreach ($data_warga as $data) {
?>
<tr>
<td style="text-align: center;">
<input type="checkbox" id="check" name="id[]" class="centang" value="<?= $data['id']; ?>">
</td>
<td><?= $no; ?></td>
<td><?= $data['nama']; ?></td>
<td><?= $data['username']; ?></td>
<td><?= $data['email']; ?></td>
<td style="text-align: center;">
<button type="button" class="btn btn-outline-danger">
<a href="<?= base_url(); ?>/user/reset/<?= $data['id']; ?>" style="text-decoration: none;color: black;">Reset</a>
</button>
</td>
<td style="text-align: center;">
<a href="<?php echo base_url('user/edit/' . $data['id']); ?>" style="color: black;">
<li class="far fa-edit"></li>
</a>
<a href="<?php echo base_url('user/view/' . $data['id']); ?>" style="color: black;">
<li class="far fa-eye"></li>
</a>
<a href="<?php echo base_url('user/delete/' . $data['id']); ?>" onclick="javascript:return confirm('Apakah Anda Yakin Ingin Menghapus Data Ini?')" style="color: black;">
<li class="far fa-trash-alt"></li>
</a>
</td>
</tr>
<?php $no++;
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- /.card -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</div>
<!-- /.container-fluid -->
</section>
<!-- /.content -->
<!-- /.content -->
<?= $this->endSection(); ?><file_sep>/app/Views/potensi/input.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<!-- Main content -->
<section class="content">
<?php if (session()->getFlashdata('error')) { ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('error'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php } ?>
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-balance-scale mr-1"></i>
<?= $ket[0]; ?>
</h3>
</div>
<div class="container-fluid card-body">
<form method="post" action="<?= base_url('/potensi/add'); ?>" enctype="multipart/form-data">
<?= csrf_field(); ?>
<div class="row mb-3">
<label for="nama" class="col-sm-2 col-form-label">Nama</label>
<div class="col-sm-10">
<input autocomplete="off" autofocus placeholder="Masukkan Nama" required type="text" class="form-control" id="nama" name="nama">
</div>
</div>
<div class="row mb-3">
<label for="foto" class="col-sm-2 col-form-label label">Foto</label>
<div class="col-sm-2">
<img class="img-thumbnail img-preview" src="<?= base_url(); ?>/potensi/no_image.png" alt="">
</div>
<div class="col-sm-8">
<div class="custom-file">
<input type="file" class="custom-file-input" id="fotoo" name="foto" onchange="previewImg()">
<p style="color: red">Ekstensi yang diperbolehkan .png | .jpg | .jpeg (Ukuran Max 10 MB dan Nama File Sesuai Nama)</p>
<label for="foto" class="custom-file-label">Masukkan Gambar</label>
</div>
</div>
</div>
<div class="row mb-3">
<label for="ket" class="col-sm-2 col-form-label">Keterangan</label>
<div class="col-sm-10">
<div class="card card-outline card-info">
<div class="card-header">
<h3 class="card-title">
Masukkan Keterangan
</h3>
</div>
<div class="card-body pad">
<div class="mb-3">
<textarea name="ket" id="ket" class="textarea" style="width: 100%; height: 200px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;"></textarea>
</div>
</div>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-danger">Clear</button>
</form>
</div>
</div>
</section>
<!-- /.content -->
<!-- /.content -->
<?= $this->endSection(); ?><file_sep>/app/Views/alamat/edit.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<!-- Main content -->
<section class="content">
<?php if (session()->getFlashdata('error')) { ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('error'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php } ?>
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-balance-scale mr-1"></i>
<?= $ket[0]; ?>
</h3>
</div>
<div class="container-fluid card-body">
<form method="post" action="<?= base_url($link . '/update'); ?>" enctype="multipart/form-data">
<?= csrf_field(); ?>
<div class="row mb-3">
<label for="alm" class="col-sm-2 col-form-label">Alamat</label>
<div class="col-sm-10">
<textarea name="alm" id="alm" cols="30" rows="3" class="form-control" style="background:lightgrey"><?= $data->alm; ?></textarea>
</div>
</div>
<div class="row mb-3">
<label for="nagari" class="col-sm-2 col-form-label">Nagari</label>
<div class="col-sm-10">
<input value="<?= $data->nagari; ?>" autocomplete="off" placeholder="Masukkan Nama Nagari" required type="text" class="form-control" id="nagari" name="nagari" style="background:lightgrey">
</div>
</div>
<div class="row mb-3">
<label for="kec" class="col-sm-2 col-form-label">Kecamatan</label>
<div class="col-sm-10">
<input value="<?= $data->kec; ?>" autocomplete="off" placeholder="Masukkan Nama Kecamatan" required type="text" class="form-control" id="kec" name="kec" style="background:lightgrey">
</div>
</div>
<div class="row mb-3">
<label for="kab" class="col-sm-2 col-form-label">Kabupaten</label>
<div class="col-sm-10">
<input value="<?= $data->kab; ?>" autocomplete="off" placeholder="Masukkan Nama Kabupaten" required type="text" class="form-control" id="kab" name="kab" style="background:lightgrey">
</div>
</div>
<div class="row mb-3">
<label for="prov" class="col-sm-2 col-form-label">Provinsi</label>
<div class="col-sm-10">
<input value="<?= $data->prov; ?>" autocomplete="off" placeholder="Masukkan Nama Provinsi" required type="text" class="form-control" id="prov" name="prov" style="background:lightgrey">
</div>
</div>
<div class="row mb-3">
<label for="kd_pos" class="col-sm-2 col-form-label">Kode Pos</label>
<div class="col-sm-10">
<input value="<?= $data->kd_pos; ?>" autocomplete="off" placeholder="Masukkan Kode Pos" required type="text" class="form-control" id="kd_pos" name="kd_pos" style="background:lightgrey">
</div>
</div>
<div class="row mb-3">
<label for="map_kantor" class="col-sm-2 col-form-label">Maps Kantor</label>
<div class="col-sm-10">
<input value="<?= $data->map_kantor; ?>" autocomplete="off" placeholder="Masukkan Link Maps Kantor" required type="text" class="form-control" id="map_kantor" name="map_kantor" style="background:lightgrey">
</div>
</div>
<div class="row mb-3">
<label for="map_wilayah" class="col-sm-2 col-form-label">Maps Wilayah</label>
<div class="col-sm-10">
<textarea autocomplete="off" placeholder="Masukkan Link Maps Wilayah" required type="text" class="form-control" id="map_wilayah" name="map_wilayah" style="background:lightgrey"><?= $data->map_wilayah; ?></textarea>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</section>
<!-- /.content -->
<!-- /.content -->
<?= $this->endSection(); ?><file_sep>/app/Views/web/data.php
<?= $this->extend('web/template'); ?>
<?= $this->section('content'); ?>
<main id="main">
<div class="row">
<div class="col-md-9">
<section style="padding: 40px;">
<div class="card">
<div class="card-header">
<div id="tab" class="card-tools">
<nav>
<a href="#isi" class="act" data-id='1'>Perubahan Penduduk</a>
<a href="#isi" data-id='2'>Pendidikan</a>
<a href="#isi" data-id='3'>Pekerjaan</a>
<a href="#isi" data-id='4'>Agama</a>
<a href="#isi" data-id='5'>Jenis Kelamin</a>
<a href="#isi" data-id='6'>Umur</a>
</nav>
</div>
</div>
<div class="card-body">
<div class="tab-content act" data-content='1'>
<div>
<h5><b>Total Penduduk Tahun <?= date('Y'); ?> : </b> <?= $penduduk; ?> Orang</h5><br>
</div>
<div class="row">
<div class="col-md-6">
<canvas id="pc_penduduk"></canvas>
</div>
<div class="col-md-6">
<canvas id="lc_rubah"></canvas>
</div>
</div>
</div>
<div class="tab-content" data-content='2'>
<canvas id="bc_pendidikan"></canvas>
</div>
<div class="tab-content" data-content='3'>
<h5><b>Penduduk Berdasarkan Pekerjaan Tahun <?= date('Y'); ?></b></h5>
<table class="table table-hover table-bordered">
<thead class="table-secondary" style="text-align: center;">
<tr>
<th>No.</th>
<th>Nama Pekerjaan</th>
<th>Jumlah Penduduk</th>
</tr>
</thead>
<tbody>
<?php $no = 1;
foreach ($kerja as $kerja) { ?>
<tr>
<td style="text-align: center;"><?= $no; ?></td>
<td><?= $kerja['nama']; ?></td>
<td style="text-align: center;"><?= $kerja['tot']; ?></td>
</tr>
<?php $no++;
} ?>
</tbody>
</table>
</div>
<div class="tab-content" data-content='4'>
<canvas id="pc_agama"></canvas>
</div>
<div class="tab-content" data-content='5'>
<div>
<canvas id="pc_jekel"></canvas>
</div>
<div class="row">
<div class="col-md-6">
<canvas id="pc_jkg"></canvas>
</div>
<div class="col-md-6">
<canvas id="pc_jkgru"></canvas>
</div>
</div>
</div>
<div class="tab-content" data-content='6'>
<canvas id="bc_umur"></canvas>
</div>
</div>
</div>
</section>
</div>
<div class="col-md-3" style="margin-top: 40px; padding-right: 35px;">
<h5 align=" center"><b>Berita Terbaru</b></h5>
<hr>
<?php if ($berita == NULL) { ?>
<div class="row h" style="word-wrap: break-word; padding: 10px;">
Berita belum ada
</div>
<?php } ?>
<?php
foreach ($berita as $data) {
?>
<div class="row h" style="word-wrap: break-word; padding: 10px;">
<a href="<?= base_url('/web/isi/' . $data['id_berita']) ?>" style="color: black;">
<p><b><?= $data['judul']; ?></b></p>
<?= substr($data['isi'], 0, 50); ?>
<p style="color: #061F2D;"> Baca Selengkapnya...</p>
</a>
</div>
<hr>
<?php } ?>
</div>
</div>
</main>
<?= $this->include('web/chartweb'); ?>
<?= $this->endSection(); ?><file_sep>/app/Views/web/surat.php
<?= $this->extend('web/template'); ?>
<?= $this->section('content'); ?>
<div style="height: 90px;">
</div>
<main id="main">
<div class="row">
<div class="col-md-9">
<section class="section-bg" style="padding: 40px;">
<?= $data->syarat_surat; ?>
<p> Jika ingin membuat permohonan surat, silahkan masukkan username dan password anda di bawah ini. Jika anda belum mempunyai username dan pasword silahkan kontak ke nomor di bawah ini, username dan password akan di beritahu ke anda. Terimakasih.</p>
<h1><b> Kontak : <a href="tel:<?= $kontak->telp; ?>"> <i class="fab fa-whatsapp"></i><?= $kontak->telp; ?></a></b></h1>
<div class="container card" style="width: 70%;">
<div class="container-fluid card-body">
<script>
window.setTimeout(function() {
$(".alert").fadeTo(500, 0).slideUp(500, function() {
$(this).remove();
});
}, 3000);
</script>
<?php if (session()->getFlashdata('error')) { ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('error'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php } ?>
<form action="<?= base_url() ?>/auth/cek_login" method="POST">
<?= csrf_field() ?>
<div class="row mb-3">
<label for="login" class="col-sm-3 col-form-label">Username</label>
<div class="col-sm-9">
<input autocomplete="off" type="text" placeholder="Masukkan Username" class="form-control" id="login" name="login">
</div>
</div>
<div class="row mb-3">
<label for="password" class="col-sm-3 col-form-label">Password</label>
<div class="col-sm-9">
<input autocomplete="off" type="password" placeholder="<PASSWORD>kan Password" class="form-control" id="password" name="password">
</div>
</div>
<input type="hidden" name="log" id="log" value="surat">
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</div>
</section>
</div>
<div class="col-md-3" style="margin-top: 40px; padding-right: 35px;">
<h5 align=" center"><b>Berita Terbaru</b></h5>
<hr>
<?php if ($berita == NULL) { ?>
<div class="row h" style="word-wrap: break-word; padding: 10px;">
Berita belum ada
</div>
<?php } ?>
<?php
foreach ($berita as $data) {
?>
<div class="row h" style="word-wrap: break-word; padding: 10px;">
<a href="<?= base_url('/web/isi/' . $data['id_berita']) ?>" style="color: black;">
<p><b><?= $data['judul']; ?></b></p>
<?= substr($data['isi'], 0, 50); ?>
<p style="color: #061F2D;"> Baca Selengkapnya...</p>
</a>
</div>
<hr>
<?php } ?>
</div>
</div>
</main>
<?= $this->endSection(); ?><file_sep>/app/Views/perangkat/view.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-user-friends mr-1"></i>
View Data : <?= $perangkat->nama; ?>
</h3>
<div class="card-tools">
<ul class="nav nav-pills ml-auto">
<li class="nav-item">
<button type="button" style="margin-left: 10px;" class="btn btn-success">
<a href="<?php echo base_url($link . '/edit/' . $perangkat->id_pemerintahan); ?>" style="color: white;">
<i class="far fa-plus-square"> Edit Data</i>
</a>
</button>
</li>
</ul>
</div>
</div>
<div class="card-body">
<table class="table">
<tr>
<td rowspan="3" style="width: 1px;">
<img src="<?= base_url(); ?>/perangkat/<?= $perangkat->foto; ?>" alt="Foto <?= $perangkat->nama; ?>" height="150px">
</td>
<td><b>Jabatan </b></td>
<td> : <?= $perangkat->jabatan; ?></td>
<td style="text-align: right;" rowspan="3">
<?php if ($perangkat->tgl_berhenti == NULL or $perangkat->tgl_berhenti == '0000-00-00') {
echo '<b style="color: red;">Masih Menjabat</b>';
} else {
echo '<b style="color: lightgrey;">Sudah Berhenti</b>';
} ?>
</td>
</tr>
<tr>
<td><b>Tanggal Lantik</b></td>
<td> : <?= date('d M Y', strtotime($perangkat->tgl_lantik)); ?></td>
</tr>
<tr>
<td><b>Tanggal Berhenti</b></td>
<td> : <?php if ($perangkat->tgl_berhenti != NULL and $perangkat->tgl_berhenti != '0000-00-00') {
echo date('d M Y', strtotime($perangkat->tgl_berhenti));
} else {
echo '-';
} ?></td>
</tr>
<tr>
<td><b>Nama</b></td>
<td> : <?= $perangkat->nama; ?></td>
</tr>
<tr>
<td><b>NIK</b></td>
<td> : <?= $perangkat->nik; ?></td>
</tr>
<tr>
<td><b>Jenis Kelamin</b></td>
<td> : <?= $perangkat->jekel; ?></td>
</tr>
<tr>
<td><b>Nomor Telepon</b></td>
<td> : <a href="tel:<?= $perangkat->telp; ?>"><?= $perangkat->telp; ?></a></td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
<?= $this->endSection(); ?><file_sep>/app/Views/profile/adminprof.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<section class="content">
<?= $this->include('template/tgl') ?>
<div class="container-fluid">
<div class="row">
<div class="col-12">
<?php if (session()->getFlashdata('pesan_profile')) : ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('pesan_profile'); ?>
</div>
<?php endif; ?>
<div class="card">
<div class="row">
<?php if (session()->get('id_datauser') != 0) { ?>
<div class="col-lg-3 col-md-5" style="padding: 3vh;">
<img src="<?= base_url(); ?>/<?php if (session()->level == 3) {
echo 'penduduk';
} else {
echo 'perangkat';
} ?>/<?= $isi->foto; ?>">
</div>
<div class="col" style="padding: 3vh;">
<h3><b><?= $user->nama; ?></b></h3>
<h5><?= $user->jabatan; ?></h5>
<table class="table">
<tr>
<td>NIK</td>
<td> : <?= $user->nik; ?></td>
</tr>
<tr>
<td>Username</td>
<td> : <?= $isi->username; ?></td>
</tr>
<tr>
<td>Email</td>
<td> : <a href="mailto:<?= $isi->email; ?>"><?= $isi->email; ?></a></td>
</tr>
<tr>
<td>No Telepon</td>
<td> : <a href="tel:<?= $isi->telp; ?>"><?= $isi->telp; ?></a></td>
</tr>
</table>
<button type="button" class="btn btn-success">
<a href="<?php echo base_url('/profile/editadmin'); ?>" style="color: white;">
<i class="far fa-edit"> Edit Profile</i>
</a>
</button>
</div>
<?php } ?>
</div>
</div>
</div>
</div>
</div>
</section>
<?= $this->endSection(); ?><file_sep>/app/Controllers/Home.php
<?php
namespace App\Controllers;
use App\Models\PendudukModel;
use App\Models\AuthModel;
use App\Models\PerangkatModel;
use App\Models\MohonModel;
use App\Models\AduanModel;
class Home extends BaseController
{
protected $model, $user;
public function __construct()
{
helper('form');
// Deklarasi model
$this->penduduk = new PendudukModel();
$this->user = new AuthModel();
$this->perangkat = new PerangkatModel();
$this->mohon = new MohonModel();
$this->aduan = new AduanModel();
}
public function index()
{
if (session()->get('level') == 1 or session()->get('level') == 2) {
$ket = [
'Beranda'
];
$data = [
'title' => 'Sistem Informasi Nagari', // Title Tab
'ket' => $ket, // Untuk link halaman
'link' => 'chart', // Untuk memanggil chart
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'), // Data lengkap dari user yang aktif
'isi' => $this->user->getUser(session()->id), // Data user yang aktif
'penduduk' => $this->penduduk->tot('penduduk'), // Total semua penduduk
'keluarga' => $this->penduduk->tot('keluarga'), // Total semua kepala keluarga
'pr' => $this->penduduk->totjekel('penduduk', 'Perempuan'), // Total semua penduduk yang peremuan
'lk' => $this->penduduk->totjekel('penduduk', 'Laki - Laki'), // Total semua penduduk yang laki - laki
'g' => $this->penduduk->tot('penduduk', false, false, 'Jorong Gantiang'), // Total penduduk jorong gatiang
'gru' => $this->penduduk->tot('penduduk', false, false, 'Jorong Gunuang Rajo Utara'), // Total penduduk jorong gunuang rajo utara
'laki' => $this->penduduk->totjekel('penduduk', "Laki - Laki", false, false, 'Jorong Gantiang'), // Total penduduk jorong gatiang yang laki - laki
'perempuan' => $this->penduduk->totjekel('penduduk', "Perempuan", false, false, 'Jorong Gantiang'), // Total penduduk jorong gatiang yang perempuan
'laki_gru' => $this->penduduk->totjekel('penduduk', "Laki - Laki", false, false, 'Jorong Gunuang Rajo Utara'), // Total penduduk jorong gunuang rajo utara yang laki - laki
'perempuan_gru' => $this->penduduk->totjekel('penduduk', "Perempuan", false, false, 'Jorong Gunuang Rajo Utara') // Total penduduk jorong gunuang rajo utara yang perempuan
];
// Menghitung jumlah penduduk berdasarkan umur
$data['umur'] = array(
count($this->penduduk->jmlUmur(0, 5)),
count($this->penduduk->jmlUmur(6, 12)),
count($this->penduduk->jmlUmur(13, 16)),
count($this->penduduk->jmlUmur(17, 25)),
count($this->penduduk->jmlUmur(26, 35)),
count($this->penduduk->jmlUmur(36, 45)),
count($this->penduduk->jmlUmur(46, 55)),
count($this->penduduk->jmlUmur(56, 65)),
count($this->penduduk->jmlUmurTua(65)),
);
// Mengitung jumlah penduduk yang lahir per tahun
for ($i = 1; $i <= 12; $i++) {
$lahir[$i - 1] = $this->penduduk->countlahir(date('Y'), $i);
}
$data['lahir'] = $lahir;
// Mengitung jumlah penduduk yang meninggal per tahun
for ($i = 1; $i <= 12; $i++) {
$mati[$i - 1] = $this->penduduk->countmati(date('Y'), $i);
}
$data['mati'] = $mati;
$y = date('Y');
$l = array($y - 4, $y - 3, $y - 2, $y - 1, $y);
for ($i = 0; $i < 5; $i++) {
$rubah[$i] = $this->penduduk->tot('penduduk', $l[$i]);
}
$data['rubah'] = $rubah;
$srt = array('SKU', 'SKTM', 'SKM', 'SKPO');
for ($i = 0; $i < 4; $i++) {
$mohon[$i] = $this->mohon->count($srt[$i]);
}
$data['mohon'] = $mohon;
for ($i = 1; $i <= 12; $i++) {
$aduan[$i - 1] = $this->aduan->count(date('Y'), $i);
}
$data['aduan'] = $aduan;
return view('beranda/index', $data);
} elseif (session()->get('level') == 3) {
$ket = [
'My Profile'
];
$data = [
'title' => 'Sistem Informasi Nagari',
'ket' => $ket,
'link' => 'home',
'user' => $this->penduduk->getPenduduk(session()->get('id_datauser')),
'isi' => $this->user->getUser(session()->id)
];
return view('profile/index', $data);
}
}
}
<file_sep>/app/Views/template/sidebar_pemerintah.php
<!-- Pemerintah -->
<?php if (session()->get('level') == 2 or session()->get('level') == 1) : ?>
<li class="nav-item">
<a href="<?= base_url(); ?>/home" class="nav-link">
<i class="nav-icon fas fa-home"></i>
<p>
Beranda
</p>
</a>
</li>
<li class="nav-item">
<a href="<?= base_url(); ?>/profile/index" class="nav-link">
<i class="nav-icon fas fa-user"></i>
<p>
Profile
</p>
</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
<i class="nav-icon fas fa-balance-scale"></i>
<p>
Pemerintahan Nagari
<i class="right fas fa-angle-left"></i>
</p>
</a>
<ul class="nav nav-treeview">
<li class="nav-item">
<a href="<?= base_url(); ?>/nagari/index" class="nav-link">
<i class="far fa-circle nav-icon"></i>
<p>Perangkat Nagari</p>
</a>
</li>
<li class="nav-item">
<a href="<?= base_url(); ?>/bprn/index" class="nav-link">
<i class="far fa-circle nav-icon"></i>
<p>BPRN</p>
</a>
</li>
<li class="nav-item">
<a href="<?= base_url(); ?>/kan/index" class="nav-link">
<i class="far fa-circle nav-icon"></i>
<p>KAN</p>
</a>
</li>
</ul>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
<i class="nav-icon fas fa-building"></i>
<p>
Lembaga Nagari
<i class="right fas fa-angle-left"></i>
</p>
</a>
<ul class="nav nav-treeview">
<li class="nav-item">
<a href="<?= base_url(); ?>/bundo/index" class="nav-link">
<i class="far fa-circle nav-icon"></i>
<p>Bundo Kanduang</p>
</a>
</li>
<li class="nav-item">
<a href="<?= base_url(); ?>/ulama/index" class="nav-link">
<i class="far fa-circle nav-icon"></i>
<p>Alim Ulama</p>
</a>
</li>
<li class="nav-item">
<a href="<?= base_url(); ?>/cadiak/index" class="nav-link">
<i class="far fa-circle nav-icon"></i>
<p>Cadiak Pandai</p>
</a>
</li>
<li class="nav-item">
<a href="<?= base_url(); ?>/pemuda/index" class="nav-link">
<i class="far fa-circle nav-icon"></i>
<p>Pemuda</p>
</a>
</li>
</ul>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
<i class="nav-icon fas fa-users"></i>
<p>
Kependudukan
<i class="right fas fa-angle-left"></i>
</p>
</a>
<ul class="nav nav-treeview">
<li class="nav-item">
<a href="<?= base_url(); ?>/keluarga/index" class="nav-link">
<i class="far fa-circle nav-icon"></i>
<p>Keluarga</p>
</a>
</li>
<li class="nav-item">
<a href="<?= base_url(); ?>/penduduk/index" class="nav-link">
<i class="far fa-circle nav-icon"></i>
<p>Penduduk</p>
</a>
</li>
<li class="nav-item">
<a href="<?= base_url(); ?>/lahir/index" class="nav-link">
<i class="far fa-circle nav-icon"></i>
<p>Kelahiran</p>
</a>
</li>
<li class="nav-item">
<a href="<?= base_url(); ?>/mati/index" class="nav-link">
<i class="far fa-circle nav-icon"></i>
<p>Kematian</p>
</a>
</li>
</ul>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
<i class="nav-icon fas fa-envelope"></i>
<p>
Surat
<i class="right fas fa-angle-left"></i>
</p>
</a>
<ul class="nav nav-treeview">
<li class="nav-item">
<a href="<?= base_url(); ?>/sku/index" class="nav-link">
<i class="far fa-circle nav-icon"></i>
<p>SKU</p>
</a>
</li>
<li class="nav-item">
<a href="<?= base_url(); ?>/sktm/index" class="nav-link">
<i class="far fa-circle nav-icon"></i>
<p>SKTM</p>
</a>
</li>
<li class="nav-item">
<a href="<?= base_url(); ?>/skm/index" class="nav-link">
<i class="far fa-circle nav-icon"></i>
<p>SKM</p>
</a>
</li>
<li class="nav-item">
<a href="<?= base_url(); ?>/skpo/index" class="nav-link">
<i class="far fa-circle nav-icon"></i>
<p>SKPO</p>
</a>
</li>
</ul>
</li>
<div class="dropdown-divider"></div>
<li class="nav-item">
<a href="<?= base_url(); ?>/permohonan/index" class="nav-link">
<i class="nav-icon fas fa-mail-bulk"></i>
<p>
List Permohonan Surat
</p>
</a>
</li>
<li class="nav-item">
<a href="<?= base_url(); ?>/aduan/index" class="nav-link">
<i class="nav-icon fas fa-volume-up"></i>
<p>
List Aduan Warga
</p>
</a>
</li>
<div class="dropdown-divider"></div>
<li class="nav-item">
<a href="<?= base_url(); ?>/berita/index" class="nav-link">
<i class="nav-icon fas fa-newspaper"></i>
<p>
Berita
</p>
</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
<i class="nav-icon fas fa-cog"></i>
<p>
Data Nagari
<i class="right fas fa-angle-left"></i>
</p>
</a>
<ul class="nav nav-treeview">
<li class="nav-item">
<a href="<?= base_url(); ?>/data/index" class="nav-link">
<i class="far fa-circle nav-icon"></i>
<p>Alamat</p>
</a>
</li>
<li class="nav-item">
<a href="<?= base_url(); ?>/data/info" class="nav-link">
<i class="far fa-circle nav-icon"></i>
<p>Info Desa</p>
</a>
</li>
<li class="nav-item">
<a href="<?= base_url(); ?>/potensi/index" class="nav-link">
<i class="far fa-circle nav-icon"></i>
<p>Potensi</p>
</a>
</li>
<li class="nav-item">
<a href="<?= base_url(); ?>/galeri/index" class="nav-link">
<i class="far fa-circle nav-icon"></i>
<p>Galeri</p>
</a>
</li>
</ul>
</li>
<div class="dropdown-divider"></div>
<?php endif; ?><file_sep>/app/Views/user/view.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-user-friends mr-1"></i>
View Data User
</h3>
<div class="card-tools">
<ul class="nav nav-pills ml-auto">
<li class="nav-item" style="margin-right: 10px;">
<button type="button" class="btn btn-info">
<?php if ($datauser->level != 3) { ?>
<a href="<?php echo base_url('/nagari/view/' . $datauser->id_datauser); ?>" style="color: white;">
<?php } else { ?>
<a href="<?php echo base_url('/penduduk/view/' . $datauser->id_datauser); ?>" style="color: white;">
<?php } ?>
<i class="fas fa-eye"> Lihat Data</i>
</a>
</button>
</li>
<li class="nav-item">
<button type="button" class="btn btn-success">
<a href="<?php echo base_url('/user/edit/' . $datauser->id); ?>" style="color: white;">
<i class="fas fa-edit"> Edit Data</i>
</a>
</button>
</li>
</ul>
</div>
</div>
<div class="card-body">
<table class="table">
<tr>
<td rowspan="4" style="width: 1px;">
<img src="<?= base_url(); ?>/<?php if ($datauser->foto == NULL or $datauser->foto == 'default.jpg' or $datauser->foto == 'default.svg') {
echo 'user/default.svg';
} else {
'user/' . $datauser->foto;
} ?>" alt="Foto <?= $datauser->username; ?>" height="150px">
</td>
<th>Username</th>
<td> : <?= $datauser->username; ?></td>
</tr>
<tr>
<th>Email</th>
<td> : <?= $datauser->email; ?></td>
</tr>
<tr>
<th>Telp</th>
<td> : <?= $datauser->telp; ?></td>
</tr>
<tr>
<th>Role</th>
<td> : <?php if ($datauser->level == 1) {
echo 'Super Admin';
} elseif ($datauser->level == 2) {
echo 'Admin';
} elseif ($datauser->level == 3) {
echo 'Warga';
} ?></td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
<?= $this->endSection(); ?><file_sep>/app/Views/surat/input.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<section class="content">
<?php if (session()->getFlashdata('error')) { ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('error'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php } ?>
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-balance-scale mr-1"></i>
<?= $ket[0]; ?>
</h3>
</div>
<div class="container-fluid card-body">
<form method="post" action="<?= base_url($link . '/add'); ?>" enctype="multipart/form-data">
<?= csrf_field(); ?>
<div class="row mb-3">
<label for="id_keluarga" class="col-sm-2 col-form-label">No KK</label>
<div class="col-sm-10">
<select onchange="nik()" class="form-control select2bs4" name="id_keluarga" id="id_keluarga" required>
<option value="">Pilih No KK</option>
<?php
foreach ($keluarga as $k) {
?>
<option value="<?php echo $k['id_keluarga'] ?>"><?php echo $k['no_kk'] ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row mb-3">
<label for="id_penduduk" class="col-sm-2 col-form-label">NIK</label>
<div class="col-sm-10">
<select onchange="ambilNama()" class="form-control select2bs4" name="id_penduduk" id="id_penduduk" required>
<option value="">Pilih NIK</option>
</select>
</div>
</div>
<div class="row mb-3">
<label for="nama" class="col-sm-2 col-form-label">Nama</label>
<div class="col-sm-10">
<input readonly autocomplete="off" type="text" placeholder="Masukkan Nama" class="form-control" id="nama" name="nama">
</div>
</div>
<div class="row mb-3">
<label for="tujuan" class="col-sm-2 col-form-label">Tujuan Surat</label>
<div class="col-sm-10">
<input autocomplete="off" placeholder="Masukkan Tujuan Surat" required type="text" class="form-control" id="tujuan" name="tujuan">
</div>
</div>
<div class="row mb-3">
<label for="ket" class="col-sm-2 col-form-label"><?= $label; ?></label>
<div class="col-sm-10">
<input autocomplete="off" placeholder="Masukkan <?= $label; ?>" required type="<?php if ($link != 'sku') {
echo 'number';
} else {
echo 'text';
} ?>" class="form-control" id="ket" name="ket">
</div>
</div>
<div class="row mb-3">
<label for="ttd" class="col-sm-2 col-form-label">Yang Menandatangani</label>
<div class="col-sm-10">
<select class="form-control select2bs4" name="ttd" id="ttd" required>
<option value="">Pilih Pejabat</option>
<?php
foreach ($ttd as $p) {
?>
<option value="<?php echo $p['id_pemerintahan'] ?>"><?php echo $p['jabatan'] ?> - <?php echo $p['nama'] ?></option>
<?php } ?>
</select>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-danger">Clear</button>
</form>
</div>
</div>
</section>
<?= $this->endSection(); ?><file_sep>/app/Controllers/Web.php
<?php
namespace App\Controllers;
use App\Models\AlamatModel;
use App\Models\GaleriModel;
use App\Models\PerangkatModel;
use App\Models\DataModel;
use App\Models\PotensiModel;
use App\Models\BeritaModel;
use App\Models\PendudukModel;
use App\Models\IsiModel;
class Web extends BaseController
{
public function __construct()
{
$this->alm = new AlamatModel();
$this->gal = new GaleriModel();
$this->perangkat = new PerangkatModel();
$this->data = new DataModel();
$this->potensi = new PotensiModel();
$this->berita = new BeritaModel();
$this->penduduk = new PendudukModel();
$this->isi = new IsiModel();
}
public function index()
{
$x = [
'icon' => $this->gal->gambar('Logo Icon')->x,
'logo' => $this->gal->gambar('Logo Web')->x,
'bg' => $this->gal->gambar('Bg Home')->x,
];
$kontak = $this->alm->getAlamat();
$data = [
'title' => 'Sistem Informasi Nagari',
'link' => '',
'judul' => '<NAME>',
'gambar' => $x,
'kontak' => $kontak,
'ket' => $kontak->alm . ', Nagari ' . $kontak->nagari . ', Kec. ' . $kontak->kec . ', Kab. ' . $kontak->kab . ', ' . $kontak->prov . ', Indonesia, ' . $kontak->kd_pos,
'direct' => $kontak->map_kantor,
'wali' => $this->perangkat->wali(),
'sambutan' => $this->data->getData(),
'potensi' => $this->potensi->getPotensi(),
'berita' => $this->berita->getBerita(false, 5)
];
// dd($this->perangkat->wali());
return view('web/index', $data);
}
public function sambutan()
{
$x = [
'icon' => $this->gal->gambar('Logo Icon')->x,
'logo' => $this->gal->gambar('Logo Web')->x,
'bg' => $this->gal->gambar('Bg Home')->x,
];
$kontak = $this->alm->getAlamat();
$data = [
'title' => 'Kata Sambutan',
'link' => '',
'judul' => 'Kata Sambutan',
'gambar' => $x,
'kontak' => $kontak,
'wali' => $this->perangkat->wali(),
'sambutan' => $this->data->getData(),
'berita' => $this->berita->getBerita(false, 5)
];
return view('web/sambutan', $data);
}
public function isi($id_berita)
{
$data = $this->berita->getberita($id_berita);
$x = [
'icon' => $this->gal->gambar('Logo Icon')->x,
'logo' => $this->gal->gambar('Logo Web')->x,
'bg' => $this->gal->gambar('Bg Berita')->x,
];
$kontak = $this->alm->getAlamat();
$data = [
'title' => 'Berita' . $data->judul,
'link' => '',
'judul' => 'Isi Berita',
'gambar' => $x,
'kontak' => $kontak,
'berita' => $this->berita->getBerita(false, 5),
'data' => $this->berita->getBerita($id_berita)
];
return view('web/isiberita', $data);
}
public function sejarah()
{
$x = [
'icon' => $this->gal->gambar('Logo Icon')->x,
'logo' => $this->gal->gambar('Logo Web')->x,
'bg' => $this->gal->gambar('Bg Sejarah')->x,
];
$kontak = $this->alm->getAlamat();
$data = [
'title' => 'Sejarah',
'link' => 'web/sejarah',
'judul' => 'Sejarah Nagari',
'gambar' => $x,
'kontak' => $kontak,
'ket' => '',
'direct' => '',
'berita' => $this->berita->getBerita(false, 5),
'data' => $this->data->getData(),
'wali' => $this->perangkat->sejarah()
];
return view('web/sejarah', $data);
}
public function visi()
{
$x = [
'icon' => $this->gal->gambar('Logo Icon')->x,
'logo' => $this->gal->gambar('Logo Web')->x,
'bg' => $this->gal->gambar('Bg Visi')->x,
];
$kontak = $this->alm->getAlamat();
$data = [
'title' => 'Visi & Misi',
'link' => 'web/visi',
'judul' => 'Visi & Misi',
'gambar' => $x,
'kontak' => $kontak,
'ket' => '',
'direct' => '',
'berita' => $this->berita->getBerita(false, 5),
'data' => $this->data->getData(),
];
return view('web/visi', $data);
}
public function wilayah()
{
$x = [
'icon' => $this->gal->gambar('Logo Icon')->x,
'logo' => $this->gal->gambar('Logo Web')->x,
'bg' => $this->gal->gambar('Bg Wilayah')->x,
];
$kontak = $this->alm->getAlamat();
$data = [
'title' => 'Profile Wilayah',
'link' => 'web/wilayah',
'judul' => 'Profile Wilayah Administratif',
'gambar' => $x,
'kontak' => $kontak,
'ket' => '',
'direct' => '',
'berita' => $this->berita->getBerita(false, 5),
'alm' => $this->alm->getAlamat(),
'data' => $this->data->getData(),
];
return view('web/wilayah', $data);
}
public function potensi()
{
$x = [
'icon' => $this->gal->gambar('Logo Icon')->x,
'logo' => $this->gal->gambar('Logo Web')->x,
'bg' => $this->gal->gambar('Bg Home')->x,
];
$kontak = $this->alm->getAlamat();
$data = [
'title' => 'Potensi Nagari',
'link' => '',
'judul' => 'Potensi',
'gambar' => $x,
'kontak' => $kontak,
'potensi' => $this->potensi->getPotensi(),
'berita' => $this->berita->getBerita(false, 5)
];
return view('web/potensi', $data);
}
public function berita()
{
$x = [
'icon' => $this->gal->gambar('Logo Icon')->x,
'logo' => $this->gal->gambar('Logo Web')->x,
'bg' => $this->gal->gambar('Bg Berita')->x,
];
$kontak = $this->alm->getAlamat();
$data = [
'title' => 'Berita',
'link' => 'web/berita',
'judul' => 'Berita',
'gambar' => $x,
'kontak' => $kontak,
'ket' => '',
'direct' => '',
'berita' => $this->berita->getBerita(false, 5),
'data' => $this->berita->orderBy('tgl_update', 'DESC')->paginate(10, 'data'),
'pager' => $this->berita->pager
];
return view('web/berita', $data);
}
public function perangkat()
{
$x = [
'icon' => $this->gal->gambar('Logo Icon')->x,
'logo' => $this->gal->gambar('Logo Web')->x,
'bg' => $this->gal->gambar('Bg Perangkat')->x,
];
$kontak = $this->alm->getAlamat();
$data = [
'title' => 'Perangkat Nagari',
'link' => 'web/perangkat',
'judul' => 'Perangkat Nagari',
'gambar' => $x,
'kontak' => $kontak,
'ket' => '',
'direct' => '',
'berita' => $this->berita->getBerita(false, 5),
'data' => $this->perangkat->data('Perangkat Nagari'),
];
return view('web/perangkat', $data);
}
public function kan()
{
$x = [
'icon' => $this->gal->gambar('Logo Icon')->x,
'logo' => $this->gal->gambar('Logo Web')->x,
'bg' => $this->gal->gambar('Bg KAN')->x,
];
$kontak = $this->alm->getAlamat();
$data = [
'title' => 'KAN',
'link' => 'web/kan',
'judul' => 'KAN',
'gambar' => $x,
'kontak' => $kontak,
'ket' => '',
'direct' => '',
'berita' => $this->berita->getBerita(false, 5),
'data' => $this->perangkat->data('KAN'),
];
return view('web/perangkat', $data);
}
public function bprn()
{
$x = [
'icon' => $this->gal->gambar('Logo Icon')->x,
'logo' => $this->gal->gambar('Logo Web')->x,
'bg' => $this->gal->gambar('Bg BPRN')->x,
];
$kontak = $this->alm->getAlamat();
$data = [
'title' => 'BPRN',
'link' => 'web/bprn',
'judul' => 'BPRN',
'gambar' => $x,
'kontak' => $kontak,
'ket' => '',
'direct' => '',
'berita' => $this->berita->getBerita(false, 5),
'data' => $this->perangkat->data('BPRN'),
];
return view('web/perangkat', $data);
}
public function bundo()
{
$x = [
'icon' => $this->gal->gambar('Logo Icon')->x,
'logo' => $this->gal->gambar('Logo Web')->x,
'bg' => $this->gal->gambar('Bg Bundo')->x,
];
$kontak = $this->alm->getAlamat();
$data = [
'title' => 'Bundo Kanduang',
'link' => 'web/bundo',
'judul' => 'Bundo Kanduang',
'gambar' => $x,
'kontak' => $kontak,
'ket' => '',
'direct' => '',
'berita' => $this->berita->getBerita(false, 5),
'data' => $this->perangkat->data('Bundo Kanduang'),
];
return view('web/perangkat', $data);
}
public function ulama()
{
$x = [
'icon' => $this->gal->gambar('Logo Icon')->x,
'logo' => $this->gal->gambar('Logo Web')->x,
'bg' => $this->gal->gambar('Bg Ulama')->x,
];
$kontak = $this->alm->getAlamat();
$data = [
'title' => 'Alim Ulama',
'link' => 'web/ulama',
'judul' => 'Alim Ulama',
'gambar' => $x,
'kontak' => $kontak,
'ket' => '',
'direct' => '',
'berita' => $this->berita->getBerita(false, 5),
'data' => $this->perangkat->data('Alim Ulama'),
];
return view('web/perangkat', $data);
}
public function cadiak()
{
$x = [
'icon' => $this->gal->gambar('Logo Icon')->x,
'logo' => $this->gal->gambar('Logo Web')->x,
'bg' => $this->gal->gambar('Bg Cadiak')->x,
];
$kontak = $this->alm->getAlamat();
$data = [
'title' => 'Cadiak Pandai',
'link' => 'web/cadiak',
'judul' => 'Cadiak Pandai',
'gambar' => $x,
'kontak' => $kontak,
'ket' => '',
'direct' => '',
'berita' => $this->berita->getBerita(false, 5),
'data' => $this->perangkat->data('Cadiak Pandai'),
];
return view('web/perangkat', $data);
}
public function pemuda()
{
$x = [
'icon' => $this->gal->gambar('Logo Icon')->x,
'logo' => $this->gal->gambar('Logo Web')->x,
'bg' => $this->gal->gambar('Bg Pemuda')->x,
];
$kontak = $this->alm->getAlamat();
$data = [
'title' => 'Pemuda',
'link' => 'web/pemuda',
'judul' => 'Pemuda',
'gambar' => $x,
'kontak' => $kontak,
'ket' => '',
'direct' => '',
'berita' => $this->berita->getBerita(false, 5),
'data' => $this->perangkat->data('Pemuda Nagari'),
];
return view('web/perangkat', $data);
}
public function data()
{
$x = [
'icon' => $this->gal->gambar('Logo Icon')->x,
'logo' => $this->gal->gambar('Logo Web')->x,
'bg' => $this->gal->gambar('Bg Kontak')->x,
];
$kontak = $this->alm->getAlamat();
$data = [
'title' => 'Data Nagari',
'link' => 'web/data',
'judul' => 'Data Nagari',
'gambar' => $x,
'kontak' => $kontak,
'ket' => '',
'direct' => '',
'berita' => $this->berita->getBerita(false, 5),
'data' => '',
'g' => $this->penduduk->tot('penduduk', false, false, 'Jorong Gantiang'),
'gru' => $this->penduduk->tot('penduduk', false, false, 'Jorong Gunuang Rajo Utara'),
'penduduk' => $this->penduduk->tot('penduduk')
];
$y = date('Y');
$l = array($y - 4, $y - 3, $y - 2, $y - 1, $y);
for ($i = 0; $i < 5; $i++) {
$rubah[$i] = $this->penduduk->tot('penduduk', $l[$i]);
$rubah_g[$i] = $this->penduduk->tot('penduduk', $l[$i], false, 'Jorong Gantiang');
$rubah_gru[$i] = $this->penduduk->tot('penduduk', $l[$i], false, 'Jorong Gunuang Rajo Utara');
}
$data['rubah'] = $rubah;
$data['rubah_g'] = $rubah_g;
$data['rubah_gru'] = $rubah_gru;
$pendidikan = $this->isi->getIsi(false, 'pendidikan');
for ($i = 0; $i < count($pendidikan); $i++) {
$pen[$i] = $pendidikan[$i]['nama'];
$isi_p[$i] = $this->penduduk->count('pendidikan', $pen[$i]);
}
$data['pen'] = $pen;
$data['isi_p'] = $isi_p;
$pekerjaan = $this->isi->getIsi(false, 'pekerjaan');
$c = 0;
for ($i = 0; $i < count($pekerjaan); $i++) {
if ($this->penduduk->count('kerja', $pekerjaan[$i]) != 0) {
$kerja[$c]['nama'] = $pekerjaan[$i]['nama'];
$kerja[$c]['tot'] = $this->penduduk->count('kerja', $pekerjaan[$i]);
$c++;
}
}
$data['kerja'] = $kerja;
$agama = $this->isi->getIsi(false, 'agama');
for ($i = 0; $i < count($agama); $i++) {
$agm[$i] = $agama[$i]['nama'];
$isi_a[$i] = $this->penduduk->count('agama', $agm[$i]);
}
$data['agm'] = $agm;
$data['isi_a'] = $isi_a;
$data['laki'] = $this->penduduk->totjekel('penduduk', "Laki - Laki", false, false, false);
$data['perempuan'] = $this->penduduk->totjekel('penduduk', "Perempuan", false, false, false);
$data['laki_g'] = $this->penduduk->totjekel('penduduk', "Laki - Laki", false, false, 'Jorong Gantiang');
$data['perempuan_g'] = $this->penduduk->totjekel('penduduk', "Perempuan", false, false, 'Jorong Gantiang');
$data['laki_gru'] = $this->penduduk->totjekel('penduduk', "Laki - Laki", false, false, 'Jorong Gunuang Rajo Utara');
$data['perempuan_gru'] = $this->penduduk->totjekel('penduduk', "Perempuan", false, false, 'Jorong Gunuang Rajo Utara');
$data['umur'] = array(
count($this->penduduk->jmlUmur(0, 5)),
count($this->penduduk->jmlUmur(6, 12)),
count($this->penduduk->jmlUmur(13, 16)),
count($this->penduduk->jmlUmur(17, 25)),
count($this->penduduk->jmlUmur(26, 35)),
count($this->penduduk->jmlUmur(36, 45)),
count($this->penduduk->jmlUmur(46, 55)),
count($this->penduduk->jmlUmur(56, 65)),
count($this->penduduk->jmlUmurTua(65)),
);
return view('web/data', $data);
}
public function kontak()
{
$x = [
'icon' => $this->gal->gambar('Logo Icon')->x,
'logo' => $this->gal->gambar('Logo Web')->x,
'bg' => $this->gal->gambar('Bg Kontak')->x,
];
$kontak = $this->alm->getAlamat();
$data = [
'title' => 'Kontak',
'link' => 'web/kontak',
'judul' => 'Kontak',
'gambar' => $x,
'kontak' => $kontak,
'ket' => '',
'direct' => '',
'data' => $this->alm->getAlamat(),
];
return view('web/kontak', $data);
}
public function surat()
{
$x = [
'icon' => $this->gal->gambar('Logo Icon')->x,
'logo' => $this->gal->gambar('Logo Web')->x,
'bg' => $this->gal->gambar('Bg Kontak')->x,
];
$kontak = $this->alm->getAlamat();
$data = [
'title' => 'Surat',
'judul' => 'Surat',
'gambar' => $x,
'kontak' => $kontak,
'ket' => '',
'direct' => '',
'berita' => $this->berita->getBerita(false, 5),
'data' => $this->data->getData(),
];
return view('web/surat', $data);
}
}
<file_sep>/app/Views/aduan/indexadmin.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<?= $this->include('template/tgl'); ?>
<!-- Main content -->
<section class="content">
<?= form_open('mati/hapusbanyak', ['class' => 'formhapus']) ?>
<div class="container-fluid">
<div class="row">
<div class="col-12">
<?php if (session()->getFlashdata('pesan_aduan')) : ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('pesan_aduan'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php elseif (session()->getFlashdata('danger_aduan')) : ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('danger_aduan'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php elseif (session()->getFlashdata('warning_aduan')) : ?>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('warning_aduan'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-newspaper mr-1"></i>
<?= $ket[0]; ?>
</h3>
<div class="card-tools">
<ul class="nav nav-pills ml-auto">
<li class="nav-item">
<a class="nav-link active" href="#belum" data-toggle="tab">Belum Diproses</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#sudah" data-toggle="tab">Sudah Diproses</a>
</li>
<li class="nav-item">
<button type="submit" style="margin-left: 10px;" class="btn btn-danger tombolHapusBanyak" onclick="javascript:return confirm('Apakah ingin menghapus data ini ?')">
<i class="far fa-trash-alt"> Hapus</i>
</button>
</li>
</ul>
</div>
</div>
<div class="card-body">
<div class="tab-content p-0">
<div class="tab-pane active" id="belum" style="position: relative; height: 300px;">
<table id="example2" class="table table-bordered table-hover">
<thead class="thead-dark" style="text-align: center;">
<tr>
<th>
<input type="checkbox" id="centangsemua">
</th>
<th style="text-align:center">No</th>
<th style="text-align:center">Tanggal Aduan</th>
<th style="text-align:center">Isi Aduan/th>
<th>Aksi</th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
foreach ($aduan_blm as $data) {
?>
<tr>
<td style="text-align: center;">
<input type="checkbox" id="check" name="id_aduan[]" class="centang" value="<?= $data['id_aduan']; ?>">
</td>
<td><?= $no; ?></td>
<td><?= $data['tgl_aduan']; ?></td>
<td><?= $data['aduan']; ?></td>
<td style="text-align: center;">
<a href="<?php echo base_url('aduan/view/' . $data['id_aduan'] . '/belum'); ?>" style="color: black;">
<li class="far fa-eye"></li>
</a>
<a href="<?php echo base_url('aduan/delete/' . $data['id_aduan']); ?>" onclick="javascript:return confirm('Apakah Anda Yakin Ingin Menghapus Data Ini?')" style="color: black;">
<li class="far fa-trash-alt"></li>
</a>
</td>
</tr>
<?php $no++;
}
?>
</tbody>
</table>
</div>
<div class="tab-pane" id="sudah" style="position: relative; height: 300px;">
<table id="example2-2" class="table table-bordered table-hover">
<thead class="thead-dark" style="text-align: center;">
<tr>
<th>
<input type="checkbox" id="centangsemua2">
</th>
<th style="text-align:center">No</th>
<th style="text-align:center">Tanggal Aduan</th>
<th style="text-align:center">Isi Aduan/th>
<th>Aksi</th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
foreach ($aduan_sdh as $data) {
?>
<tr>
<td style="text-align: center;">
<input type="checkbox" id="check" name="id_aduan[]" class="centang" value="<?= $data['id_aduan']; ?>">
</td>
<td><?= $no; ?></td>
<td><?= $data['tgl_aduan']; ?></td>
<td><?= $data['aduan']; ?></td>
<td style="text-align: center;">
<a href="<?php echo base_url('aduan/view/' . $data['id_aduan'] . '/belum'); ?>" style="color: black;">
<li class="far fa-edit"></li>
</a>
<a href="<?php echo base_url('aduan/view/' . $data['id_aduan'] . '/sudah'); ?>" style="color: black;">
<li class="far fa-eye"></li>
</a>
<a href="<?php echo base_url('aduan/delete/' . $data['id_aduan']); ?>" onclick="javascript:return confirm('Apakah Anda Yakin Ingin Menghapus Data Ini?')" style="color: black;">
<li class="far fa-trash-alt"></li>
</a>
</td>
</tr>
<?php $no++;
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</div>
<!-- /.container-fluid -->
</section>
<!-- /.content -->
<!-- /.content -->
<?= $this->endSection(); ?><file_sep>/app/Models/KematianModel.php
<?php
namespace App\Models;
use CodeIgniter\Model;
class KematianModel extends Model
{
protected $table = 'kematian';
public function getKematian($id_kematian = false)
{
if ($id_kematian === false) {
return $this->db->table('kematian')
->join('penduduk', 'penduduk.id_penduduk = kematian.id_penduduk')
->orderBy('id_kematian', 'DESC')
->get()->getResultArray();
} else {
return $this->db->table('kematian')
->join('penduduk', 'penduduk.id_penduduk = kematian.id_penduduk')
->getWhere(['id_kematian' => $id_kematian])->getRow();
}
}
// Save data
public function saveKematian($data)
{
$builder = $this->db->table($this->table);
return $builder->insert($data);
}
// Edit data
public function editKematian($data, $id_kematian)
{
$builder = $this->db->table($this->table);
$builder->where('id_kematian', $id_kematian);
return $builder->update($data);
}
// Hapus data
public function hapusKematian($id_kematian)
{
$builder = $this->db->table($this->table);
return $builder->delete(['id_kematian' => $id_kematian]);
}
// Mencari ID
public function id($input, $field)
{
return $this->getWhere([$field => $input])->getRow();
}
// Mencari ID
public function id_array($input, $field)
{
return $this->getWhere([$field => $input])->getResultArray();
}
}
<file_sep>/app/Controllers/Potensi.php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\PotensiModel;
use App\Models\PendudukModel;
use App\Models\AuthModel;
use App\Models\PerangkatModel;
class Potensi extends Controller
{
protected $model;
public function __construct()
{
helper('form');
// Deklarasi model
$this->model = new PotensiModel();
$this->penduduk = new PendudukModel();
$this->user = new AuthModel();
$this->perangkat = new PerangkatModel();
}
// Menampilkan list Data Potensi
public function index()
{
$ket = [
'Data Potensi', '<li class="breadcrumb-item active"><a href="/potensi/index">Data Potensi</a></li>'
];
$data = [
'title' => 'Data Potensi',
'ket' => $ket,
'link' => 'potensi',
'potensi' => $this->model->getPotensi(),
'link' => 'home',
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('potensi/index', $data);
}
// View detail data
public function view($id_potensi)
{
$data = $this->model->getPotensi($id_potensi);
$ket = [
'View Data Potensi', '<li class="breadcrumb-item active"><a href="/potensi/index">Data Potensi</a></li>',
'<li class="breadcrumb-item active">View Data</li>'
];
$data = [
'title' => 'View Data Potensi',
'ket' => $ket,
'link' => 'potensi',
'potensi' => $this->model->getPotensi($id_potensi),
'link' => 'home',
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('potensi/view', $data);
}
// Menampilkan form input
public function input()
{
$ket = [
'Tambah Data Potensi',
'<li class="breadcrumb-item active"><a href="/potensi/index">Data Potensi</a></li>',
'<li class="breadcrumb-item active">Tambah Data</li>'
];
$data = [
'title' => 'Tambah Data Potensi',
'ket' => $ket,
'link' => 'potensi',
'link' => 'home',
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('potensi/input', $data);
}
public function add()
{
$request = \Config\Services::request();
$file = $request->getFile('foto');
if ($file->getError() == 4) {
$nm = "no_image.png";
} else {
$nm = $file->getRandomName();
$file->move('potensi', $nm);
}
$data = array(
'nama' => $request->getPost('nama'),
'foto' => $nm,
'ket' => $request->getPost('ket'),
'tgl_update' => date('Y-m-d')
);
$this->model->savePotensi($data);
return redirect()->to('potensi/index');
}
///edit data
public function edit($id_potensi)
{
$potensi = $this->model->getPotensi($id_potensi);
if (isset($potensi)) {
$ket = [
'Edit ' . $potensi->nama,
'<li class="breadcrumb-item active"><a href="/potensi/index">Data Potensi</a></li>',
'<li class="breadcrumb-item active">Edit Data</li>'
];
$data = [
'title' => 'Edit ' . $potensi->nama,
'ket' => $ket,
'link' => 'potensi',
'potensi' => $potensi,
'link' => 'home',
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('potensi/edit', $data);
} else {
session()->setFlashdata('warning_potensi', 'berita dengan Nama : ' . $potensi->nama . ' Tidak Ditemukan.');
return redirect()->to('potensi/index');
}
}
public function update()
{
$request = \Config\Services::request();
$id_potensi = $request->getPost('id_potensi');
$file = $request->getFile('foto');
if ($file->getError() == 4) {
$nm = $request->getPost('lama');
} else {
$nm = $file->getRandomName();
$file->move('potensi', $nm);
if ($request->getPost('lama') != 'no_image.png') {
unlink('potensi/' . $request->getPost('lama'));
}
}
$data = array(
'nama' => $request->getPost('nama'),
'foto' => $nm,
'ket' => $request->getPost('ket'),
'tgl_update' => date('Y-m-d')
);
$this->model->editPotensi($data, $id_potensi);
session()->setFlashdata('pesan_potensi', 'Data Potensi Berhasi Diedit.');
return redirect()->to('potensi/index');
}
// Menghapus data
public function delete($id_potensi)
{
$potensi = $this->model->getPotensi($id_potensi);
if (isset($potensi)) {
$this->model->hapusPotensi($id_potensi);
session()->setFlashdata('danger_potensi', 'Data Potensi : ' . $potensi->nama . ' Berhasi Dihapus.');
return redirect()->to('potensi/index');
} else {
session()->setFlashdata('warning_potensi', 'Data Potensi : ' . $potensi->nama . ' Tidak Ditemukan.');
return redirect()->to('potensi/index');
}
}
// Menghapus data pilihan
public function hapusbanyak()
{
$request = \Config\Services::request();
$id_potensi = $request->getPost('id_potensi');
if ($id_potensi == null) {
session()->setFlashdata('warning', 'Data Pejabat dan berita Desa Belum Dipilih, Silahkan Pilih Data Terlebih Dahulu.');
$data['title'] = 'Data Potensi dan Pejabat Desa';
return redirect()->to('potensi/index');
}
$jmldata = count($id_potensi);
for ($i = 0; $i < $jmldata; $i++) {
$this->model->hapusPotensi($id_potensi[$i]);
}
session()->setFlashdata('pesan', 'Data Pejabat dan berita Desa Berhasi Dihapus Sebanyak ' . $jmldata . ' Data.');
$data['title'] = 'Data Potensi dan Pejabat Desa';
return redirect()->to('potensi/index');
}
}
<file_sep>/app/Models/DataModel.php
<?php
namespace App\Models;
use CodeIgniter\Model;
class DataModel extends Model
{
protected $table = 'data';
public function getData()
{
return $this->where('id_data', 1)->get()->getRow();
}
public function editData($data)
{
$builder = $this->db->table($this->table);
$builder->where('id_data', 1);
return $builder->update($data);
}
}
<file_sep>/app/Views/template/sidebar_warga.php
<!-- Warga -->
<?php if (session()->get('level') == 3) : ?>
<li class="nav-item">
<a href="<?= base_url(); ?>/home" class="nav-link">
<i class="nav-icon fas fa-user"></i>
<p>
My Profile
</p>
</a>
</li>
<li class="nav-item">
<a href="<?= base_url(); ?>/permohonan/index" class="nav-link">
<i class="nav-icon fas fa-envelope"></i>
<p>
Permohonan Surat
</p>
</a>
</li>
<li class="nav-item">
<a href="<?= base_url(); ?>/aduan/index" class="nav-link">
<i class="nav-icon fas fa-volume-up"></i>
<p>
Pojok Aduan
</p>
</a>
</li>
<div class="dropdown-divider"></div>
<?php endif; ?><file_sep>/app/Views/mati/view.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<?= $this->include('template/tgl'); ?>
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-user-friends mr-1"></i>
View Data Kematian
</h3>
<div class="card-tools">
<ul class="nav nav-pills ml-auto">
<li class="nav-item">
<button type="button" class="btn btn-success">
<a href="<?php echo base_url('/mati/edit/' . $mati->id_kematian); ?>" style="color: white;">
<i class="fas fa-edit"> Edit Data</i>
</a>
</button>
</li>
</ul>
</div>
</div>
<div class="card-body">
<table class="table">
<tr>
<th>NIK</th>
<td> : <a href="<?= base_url(); ?>/penduduk/view/<?= $mati->id_penduduk; ?>"><?= $mati->nik; ?></a></td>
</tr>
<tr>
<th>Nama</th>
<td> : <?= $mati->nama; ?></a></td>
</tr>
<tr>
<th>Tempat Kematian</th>
<td> : <?= $mati->tpt_kematian; ?></td>
</tr>
<tr>
<th>Tanggal Kematian</th>
<td> : <?= tgl_indo($mati->tgl_kematian); ?> (<?= $umur; ?> tahun)</td>
</tr>
<tr>
<th>Sebab Kematian</th>
<td> : <?= $mati->sebab; ?></td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
<?= $this->endSection(); ?><file_sep>/app/Views/web/template.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<title><?= $title; ?></title>
<meta content="" name="description">
<meta content="" name="keywords">
<!-- Favicons -->
<link href="<?= base_url(); ?>/aset/img/<?= $gambar['icon']; ?>" rel="icon">
<link href="<?= base_url(); ?>/assets/img/apple-touch-icon.png" rel="apple-touch-icon">
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,500,700|Open+Sans:300,300i,400,400i,700,700i" rel="stylesheet">
<!-- Vendor CSS Files -->
<link href="<?= base_url(); ?>/assets/vendor/aos/aos.css" rel="stylesheet">
<link href="<?= base_url(); ?>/assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="<?= base_url(); ?>/assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
<link href="<?= base_url(); ?>/assets/vendor/glightbox/css/glightbox.min.css" rel="stylesheet">
<!-- Template Main CSS File -->
<link rel="stylesheet" href="<?= base_url(); ?>/aset/plugins/fontawesome-free/css/all.min.css">
<link href="<?= base_url(); ?>/assets/css/style.css" rel="stylesheet">
<!-- =======================================================
* Template Name: Avilon - v4.3.0
* Template URL: https://bootstrapmade.com/avilon-bootstrap-landing-page-template/
* Author: BootstrapMade.com
* License: https://bootstrapmade.com/license/
======================================================== -->
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/0.2.0/Chart.min.js" type="text/javascript"></script> -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
#tab nav {
display: flex;
}
#tab nav a {
color: black;
text-decoration: none;
padding: 0.5rem;
/* border: 1px solid silver; */
}
#tab nav .act {
background: #d8d8d8;
border-radius: 10px;
}
.tab-content {
display: none;
border: 1px solid silver;
padding: 1rem;
}
.tab-content.act {
display: block;
}
</style>
</head>
<body>
<style>
.h:hover {
background-color: #e0e0e0;
/* opacity: 20%; */
}
</style>
<!-- ======= Header ======= -->
<header id="header" class="fixed-top d-flex align-items-center header-transparent">
<div class="container d-flex justify-content-between align-items-center">
<?= $this->include('web/slide'); ?>
<div id="logo">
<a href="<?= base_url(); ?>/"><img src="<?= base_url(); ?>/aset/img/<?= $gambar['logo']; ?>" alt="" height="35px"> </a>
</div>
<nav id="navbar" class="navbar">
<ul>
<li><a class="nav-link scrollto" href="<?= base_url(); ?>/">Home</a></li>
<li class="dropdown"><a href="#"><span>Profile Nagari</span> <i class="bi bi-chevron-down"></i></a>
<ul>
<li><a href="<?= base_url(); ?>/web/sejarah">Sejarah Nagari</a></li>
<li><a href="<?= base_url(); ?>/web/visi">Visi & Misi</a></li>
<li><a href="<?= base_url(); ?>/web/wilayah">Profile Wilayah</a></li>
<li><a href="<?= base_url(); ?>/web/potensi">Potensi Wilayah</a></li>
</ul>
</li>
<li><a class="nav-link scrollto" href="<?= base_url(); ?>/web/berita">Berita</a></li>
<li class="dropdown"><a href="#"><span>Pemerintahan Nagari</span> <i class="bi bi-chevron-down"></i></a>
<ul>
<li><a href="<?= base_url(); ?>/web/perangkat">Perangkat Nagari</a></li>
<li><a href="<?= base_url(); ?>/web/kan">KAN</a></li>
<li><a href="<?= base_url(); ?>/web/bprn">BPRN</a></li>
</ul>
</li>
<li class="dropdown"><a href="#"><span>Lembaga Nagari</span> <i class="bi bi-chevron-down"></i></a>
<ul>
<li><a href="<?= base_url(); ?>/web/bundo">Bundo Kanduang</a></li>
<li><a href="<?= base_url(); ?>/web/ulama">Alim Ulama</a></li>
<li><a href="<?= base_url(); ?>/web/cadiak">Cadiak Pandai</a></li>
<li><a href="<?= base_url(); ?>/web/pemuda">Pemuda</a></li>
</ul>
</li>
<li><a class="nav-link scrollto" href="<?= base_url(); ?>/web/data">Data Nagari</a></li>
<li><a class="nav-link scrollto" href="<?= base_url(); ?>/web/surat">Surat</a></li>
<li><a class="nav-link scrollto" href="<?= base_url(); ?>/web/kontak">Kontak</a></li>
<li><a class="nav-link scrollto" href="<?= base_url(); ?>/auth/login" target="_blank">PPID</a></li>
</ul>
<i class="bi bi-list mobile-nav-toggle" style="color:black"></i>
</nav><!-- .navbar -->
</div>
</header><!-- End Header -->
<!-- ======= Hero Section ======= -->
<style>
#hero {
width: 100%;
height: 100vh;
background: linear-gradient(45deg,
/* rgba(29, 224, 153, 0.8),
rgba(29, 200, 205, 0.8) */
rgba(171, 171, 171, 0.8),
rgba(171, 171, 171, 0.8)),
url("<?= base_url(); ?>/aset/img/<?= $gambar['bg']; ?>") center top no-repeat;
background-size: cover;
position: relative;
}
</style>
<?php if ($judul != 'Kata Sambutan' and $judul != 'Isi Berita' and $judul != 'Surat' and $judul != 'Potensi') { ?>
<section id="hero">
<div class="hero-text" data-aos="zoom-out" style="padding: 40px;">
<div class="row">
<h1 style="font-size: 5vw;"><b><a style="color: black;" href="<?= base_url(); ?>/<?= $link; ?>"><?= $judul; ?></a></b></h1>
<p style="color: black; font-size: 2vw;"><a style="color: black;" target="_blank" href="<?= $direct; ?>"><?= $ket; ?></a></p>
</div>
<div class="row">
<?php if ($kontak->telp != NULL) : ?>
<div class="col">
<a href="tel:<?= $kontak->telp; ?>" class="btn-get-started scrollto" style="width: 250px;"><i class="fab fa-whatsapp"></i> Telepon</a>
</div>
<?php endif; ?>
<?php if ($kontak->email != NULL) : ?>
<div class="col">
<a href="mailto:<?= $kontak->email; ?>" class="btn-get-started scrollto" style="width: 250px;"><i class="fas fa-envelope"></i> Email</a>
</div>
<?php endif; ?>
<div class="col">
<a href="<?= base_url() ?>/auth/login" target="_blank" class="btn-get-started scrollto" style="width: 250px;"><i class="fas fa-user"></i> Layanan Mandiri</a>
</div>
</div>
</div>
</section>
<?php } ?>
<!-- End Hero Section -->
<?= $this->renderSection('content'); ?>
<!-- ======= Footer ======= -->
<footer id="footer">
<div class="container">
<div class="row">
<div class="col-lg-6 text-lg-start text-center">
<div class="copyright">
© Copyright <?= date('Y') ?> <strong><NAME></strong> - Politeknik Negeri Padang
</div>
<div class="credits">
<!--
All the links in the footer should remain intact.
You can delete the links only if you purchased the pro version.
Licensing information: https://bootstrapmade.com/license/
Purchase the pro version with working PHP/AJAX contact form: https://bootstrapmade.com/buy/?theme=Avilon
-->
Designed by <a href="https://bootstrapmade.com/">BootstrapMade</a>
</div>
</div>
<div class="col-lg-6">
<nav class="footer-links text-lg-right text-center pt-2 pt-lg-0">
<a href="<?= base_url(); ?>/">Home</a>
<a href="tel:<?= $kontak->telp; ?>" class="btn-get-started scrollto"><i class="fab fa-whatsapp"></i> : <?= $kontak->telp; ?></a>
<a href="mailto:<?= $kontak->email; ?>" class="btn-get-started scrollto"><i class="fas fa-envelope"></i> : <?= $kontak->email; ?></a>
</nav>
</div>
</div>
</div>
</footer><!-- End Footer -->
<a href="#" class="back-to-top d-flex align-items-center justify-content-center"><i class="bi bi-chevron-up"></i></a>
<!-- Vendor JS Files -->
<script src="<?= base_url(); ?>/assets/vendor/aos/aos.js"></script>
<script src="<?= base_url(); ?>/assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="<?= base_url(); ?>/assets/vendor/glightbox/js/glightbox.min.js"></script>
<script src="<?= base_url(); ?>/assets/vendor/php-email-form/validate.js"></script>
<!-- Template Main JS File -->
<script src="<?= base_url(); ?>/assets/js/main.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" crossorigin="anonymous"></script>
<script>
$("#tab nav a").click(function() {
const id = $(this).data('id');
if (!$(this).hasClass('act')) {
$("#tab nav a").removeClass('act');
$(this).addClass('act');
$('.tab-content').hide();
$(`[data-content=${id}]`).fadeIn();
}
});
</script>
</body>
</html>
<file_sep>/app/Controllers/Berita.php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\BeritaModel;
use App\Models\AuthModel;
use App\Models\PerangkatModel;
class Berita extends Controller
{
protected $model;
public function __construct()
{
helper('form');
$this->model = new BeritaModel();
$this->user = new AuthModel();
$this->perangkat = new PerangkatModel();
}
public function index()
{
$request = \Config\Services::request();
$ket = [
'Data Berita', '<li class="breadcrumb-item active"><a href="/berita/index">Data Berita</a></li>'
];
$data = [
'title' => 'Data Berita',
'ket' => $ket,
'berita' => $this->model->getBerita(),
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('berita/index', $data);
}
public function view($id_berita)
{
$data = $this->model->getberita($id_berita);
$ket = [
'View Data Berita', '<li class="breadcrumb-item active"><a href="/berita/index">Data Berita</a></li>',
'<li class="breadcrumb-item active">View Data</li>'
];
$data = [
'title' => 'View Data Berita',
'ket' => $ket,
'berita' => $this->model->getBerita($id_berita),
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('berita/view', $data);
}
public function input()
{
$ket = [
'Tambah Data Berita',
'<li class="breadcrumb-item active"><a href="/berita/index">Data Berita</a></li>',
'<li class="breadcrumb-item active">Tambah Data</li>'
];
$data = [
'title' => 'Tambah Data Berita',
'ket' => $ket,
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('berita/input', $data);
}
public function add()
{
$request = \Config\Services::request();
$file = $request->getFile('foto');
if ($file->getError() == 4) {
$nm = "no_image.png";
} else {
$nm = $file->getRandomName();
$file->move('berita', $nm);
}
$penulis = $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari');
$data = array(
'judul' => $request->getPost('judul'),
'penulis' => $penulis->nama,
'gambar' => $nm,
'isi' => $request->getPost('isi'),
'tgl_update' => date('Y-m-d')
);
$this->model->saveberita($data);
session()->setFlashdata('pesan_berita', 'Berita baru berhasil ditambah.');
return redirect()->to(base_url() . '/berita/index');
}
public function edit($id_berita)
{
$getberita = $this->model->getberita($id_berita);
if (isset($getberita)) {
$ket = [
'Edit ' . $getberita->judul,
'<li class="breadcrumb-item active"><a href="/berita/index">Data Berita</a></li>',
'<li class="breadcrumb-item active">Edit Data</li>'
];
$data = [
'title' => 'Edit ' . $getberita->judul,
'ket' => $ket,
'berita' => $getberita,
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('berita/edit', $data);
} else {
session()->setFlashdata('warning_berita', 'berita dengan Nama : ' . $getberita->judul . ' Tidak Ditemukan.');
return redirect()->to(base_url() . '/berita/index');
}
}
public function update()
{
$request = \Config\Services::request();
$id_berita = $request->getPost('id_berita');
$file = $request->getFile('foto');
if ($file->getError() == 4) {
$nm = $request->getPost('lama');
} else {
$nm = $file->getRandomName();
$file->move('berita', $nm);
if ($request->getPost('lama') != 'no_image.png') {
unlink('berita/' . $request->getPost('lama'));
}
}
$penulis = $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari');
$data = array(
'judul' => $request->getPost('judul'),
'penulis' => $penulis->nama,
'gambar' => $nm,
'isi' => $request->getPost('isi'),
'tgl_update' => date('Y-m-d')
);
$this->model->editberita($data, $id_berita);
session()->setFlashdata('pesan_berita', 'Data berita berhasi diedit.');
return redirect()->to(base_url() . '/berita/index');
}
public function delete($id_berita)
{
$getberita = $this->model->getberita($id_berita);
if (isset($getberita)) {
$this->model->hapusberita($id_berita);
session()->setFlashdata('danger_berita', 'Data Berita : ' . $getberita->judul . ' Berhasi Dihapus.');
return redirect()->to(base_url() . '/berita/index');
} else {
session()->setFlashdata('warning_berita', 'Data Berita : ' . $getberita->judul . ' Tidak Ditemukan.');
return redirect()->to(base_url() . '/berita/index');
}
}
public function hapusbanyak()
{
$request = \Config\Services::request();
$id_berita = $request->getPost('id_berita');
if ($id_berita == null) {
session()->setFlashdata('warning', 'Data Pejabat dan berita Desa Belum Dipilih, Silahkan Pilih Data Terlebih Dahulu.');
$data['title'] = 'Data berita dan Pejabat Desa';
return redirect()->to(base_url() . '/berita/index');
}
$jmldata = count($id_berita);
for ($i = 0; $i < $jmldata; $i++) {
$this->model->hapusberita($id_berita[$i]);
}
session()->setFlashdata('pesan', 'Data Pejabat dan berita Desa Berhasi Dihapus Sebanyak ' . $jmldata . ' Data.');
$data['title'] = 'Data berita dan Pejabat Desa';
return redirect()->to(base_url() . '/berita/index');
}
}
<file_sep>/app/Views/penduduk/laporan.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<!-- Main content -->
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<?php if (session()->getFlashdata('pesan_penduduk')) : ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('pesan_penduduk'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php elseif (session()->getFlashdata('danger_penduduk')) : ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('danger_penduduk'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php elseif (session()->getFlashdata('warning_penduduk')) : ?>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('warning_penduduk'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-file mr-1"></i>
<?= $ket[0]; ?>
</h3>
</div><!-- /.card-header -->
<div class="card-body">
<form method="post" action="<?= base_url('penduduk/print'); ?>">
<div class="row mb-3">
<label for="tahun" class="col-sm-2 col-form-label">Tahun</label>
<div class="col-sm-3">
<select class="form-control select2bs4" name="tahun" id="tahun" required style="background:lightgrey">
<option value="">Pilih Tahun </option>
<?php
$x = 2021;
$jml = date('Y') - 2021;
for ($i = 0; $i < $jml + 1; $i++) {
?>
<option value="<?php echo $x ?>"><?php echo $x ?></option>
<?php $x++;
} ?>
</select>
</div>
<label for="bulan" class="col-sm-2 col-form-label">Bulan</label>
<div class="col-sm-3">
<select class="form-control select2bs4" name="bulan" id="bulan" required style="background:lightgrey">
<option value="">Pilih Bulan </option> -->
<?php
$data = [
'', 'Januari', 'Februari', 'Maret', 'April', 'Mei',
'Juni', 'Juli', 'Agustus', 'September', 'Oktober',
'November', 'Desember'
];
for ($i = 1; $i < count($data); $i++) {
?>
<option value="<?php echo $i ?>"><?php echo $data[$i] ?></option>
<?php } ?>
</select>
</div>
<div class="col">
<button type="submit" class="btn btn-primary"><i class="fas fa-download"></i> Cetak</button>
</div>
</div>
</form>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</div>
<!-- /.container-fluid -->
</section>
<!-- /.content -->
<!-- /.content -->
<?= $this->endSection(); ?><file_sep>/app/Views/web/sejarah.php
<?= $this->extend('web/template'); ?>
<?= $this->section('content'); ?>
<main id="main">
<div class="row">
<div class="col-md-9">
<section style="padding: 40px; background: #f8fcfd;">
<div style="padding: 10px;">
<h1><b>Asal-Usul / Legenda Nagari</b></h1>
<?= $data->sejarah; ?>
</div>
<div style="padding: 10px;">
<h1><b>Sejarah Pemerintahan Nagari</b></h1>
<table class="table table-bordered">
<tr align="center">
<th>No</th>
<th>Periode</th>
<th>Nama Kepala Desa</th>
<th>Keterangan</th>
</tr>
<?php $no = 1;
foreach ($wali as $wali) { ?>
<tr>
<td><?= $no; ?></td>
<td><?= date('Y', strtotime($wali['tgl_lantik'])); ?> - <?php if ($wali['tgl_berhenti'] != NULL and $wali['tgl_berhenti'] != '0000-00-00') {
echo date('Y', strtotime($wali['tgl_berhenti']));
} else {
echo 'Sekarang';
} ?></td>
<td><?= $wali['nama']; ?></td>
<td><?php if ($wali['nama'] != '-') {
echo '-';
} else {
echo 'Desa';
} ?></td>
</tr>
<?php $no++;
} ?>
</table>
</div>
</section>
</div>
<div class="col-md-3" style="margin-top: 40px; padding-right: 35px;">
<h5 align=" center"><b>Berita Terbaru</b></h5>
<hr>
<?php if ($berita == NULL) { ?>
<div class="row h" style="word-wrap: break-word; padding: 10px;">
Berita belum ada
</div>
<?php } ?>
<?php
foreach ($berita as $data) {
?>
<div class="row h" style="word-wrap: break-word; padding: 10px;">
<a href="<?= base_url('/web/isi/' . $data['id_berita']) ?>" style="color: black;">
<p><b><?= $data['judul']; ?></b></p>
<?= substr($data['isi'], 0, 50); ?>
<p style="color: #061F2D;"> Baca Selengkapnya...</p>
</a>
</div>
<hr>
<?php } ?>
</div>
</div>
</main>
<?= $this->endSection(); ?><file_sep>/app/Config/Filters.php
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Filters\CSRF;
use CodeIgniter\Filters\DebugToolbar;
use CodeIgniter\Filters\Honeypot;
class Filters extends BaseConfig
{
/**
* Configures aliases for Filter classes to
* make reading things nicer and simpler.
*
* @var array
*/
public $aliases = [
'csrf' => CSRF::class,
'toolbar' => DebugToolbar::class,
'honeypot' => Honeypot::class,
'user' => \App\Filters\UserFilter::class,
'admin' => \App\Filters\AdminFilter::class,
'perangkat' => \App\Filters\PerangkatFilter::class,
];
/**
* List of filter aliases that are always
* applied before and after every request.
*
* @var array
*/
public $globals = [
'before' => [
// 'honeypot',
// 'csrf',
'user' => ['except' =>
[
'auth', 'auth/*', // Login
'web', 'web/*', '/' // Web
]],
'admin' => ['except' =>
[
'auth', 'auth/*', // Login
'web', 'web/*', '/' // Web
]],
'perangkat' => ['except' =>
[
'auth', 'auth/*', // Login
'web', 'web/*', '/' // Web
]]
],
'after' => [
// 'honeypot',
'toolbar',
'user' => ['except' =>
[
'web', 'web/*', '/', // Web
'home', 'home/*', // Beranda
'profile', 'profile/*', // My Profile
'permohonan', 'permohonan/*', // Permohonan Surat
'aduan', 'aduan/*', // Pojok Aduan
]],
'admin' => ['except' => // Wali Nagari
[
// Web
'web', 'web/*', '/',
// Beranda
'home', 'home/*',
// Profile
'profile', 'profile/*',
// Pemerintahan Nagari
'nagari', 'nagari/*', // Perangkat Nagari
'bprn', 'bprn/*', // BPRN
'kan', 'kan/*', // KAN
// Lembaga Nagari
'bundo', 'bundo/*', // Bundo Kanduang
'ulama', 'ulama/*', // Alim Ulama
'cadiak', 'cadiak/*', // Cadiak Pandai
'pemuda', 'pemuda/*', // Pemuda
// Kependudukan
'keluarga', 'keluarga/*', // Keluarga
'penduduk', 'penduduk/*', // Penduduk
'lahir', 'lahir/*', // Kelahiran
'mati', 'mati/*', // Kematian
// Surat
'sku', 'sku/*', // SKU
'sktm', 'sktm/*', // SKTM
'skm', 'skm/*', // SKM
'skpo', 'skpo/*', // SKPO
// List Permohonan Surat
'permohonan', 'permohonan/index', 'permohonan/edit/*', 'permohonan/surat/*', 'permohonan/update', 'permohonan/view/*', 'permohonan/delete/*',
// List Aduan Warga
'aduan', 'aduan/index', 'aduan/edit/*', 'aduan/update', 'aduan/view/*', 'aduan/delete/*',
// Berita
'berita', 'berita/*',
// Data Nagari
'data', 'data/*', // Alamat & Info Desa
'potensi', 'potensi/*', // Potensi
'galeri', 'galeri/*', // Foto Web
'user', 'user/*', // Users
]],
'perangkat' => ['except' => // Perangkat Nagari
[
// Web
'web', 'web/*', '/',
// Beranda
'home', 'home/*',
// Profile
'profile', 'profile/*',
// Pemerintahan Nagari
'nagari', 'nagari/*', // Perangkat Nagari
'bprn', 'bprn/*', // BPRN
'kan', 'kan/*', // KAN
// Lembaga Nagari
'bundo', 'bundo/*', // Bundo Kanduang
'ulama', 'ulama/*', // Alim Ulama
'cadiak', 'cadiak/*', // Cadiak Pandai
'pemuda', 'pemuda/*', // Pemuda
// Kependudukan
'keluarga', 'keluarga/*', // Keluarga
'penduduk', 'penduduk/*', // Penduduk
'lahir', 'lahir/*', // Kelahiran
'mati', 'mati/*', // Kematian
// Surat
'sku', 'sku/*', // SKU
'sktm', 'sktm/*', // SKTM
'skm', 'skm/*', // SKM
'skpo', 'skpo/*', // SKPO
// List Permohonan Surat
'permohonan', 'permohonan/index', 'permohonan/edit/*', 'permohonan/surat/*', 'permohonan/update', 'permohonan/view/*', 'permohonan/delete/*',
// List Aduan Warga
'aduan', 'aduan/index', 'aduan/edit/*', 'aduan/update', 'aduan/view/*', 'aduan/delete/*',
// Berita
'berita', 'berita/*',
// Data Nagari
'data', 'data/*', // Alamat & Info Desa
'potensi', 'potensi/*', // Potensi
'galeri', 'galeri/*', // Foto Web
]],
],
];
/**
* List of filter aliases that works on a
* particular HTTP method (GET, POST, etc.).
*
* Example:
* 'post' => ['csrf', 'throttle']
*
* @var array
*/
public $methods = [];
/**
* List of filter aliases that should run on any
* before or after URI patterns.
*
* Example:
* 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']]
*
* @var array
*/
public $filters = [];
}
<file_sep>/app/Models/PendudukModel.php
<?php
namespace App\Models;
use CodeIgniter\Model;
class PendudukModel extends Model
{
protected $table = 'penduduk';
public function getPenduduk($id_penduduk = false)
{
if ($id_penduduk === false) {
return $this->db->table('penduduk')
->join('keluarga', 'keluarga.id_keluarga = penduduk.id_keluarga')
->orderBy('id_penduduk', 'DESC')
->get()->getResultArray();
} else {
return $this->db->table('penduduk')
->join('keluarga', 'keluarga.id_keluarga = penduduk.id_keluarga')
->getWhere(['id_penduduk' => $id_penduduk])->getRow();
}
}
public function lahir($id_penduduk = false)
{
if ($id_penduduk === false) {
return $this->db->table('penduduk')
->join('keluarga', 'keluarga.id_keluarga = penduduk.id_keluarga')
->where('nik', NULL)
->orderBy('id_penduduk', 'DESC')
->get()->getResultArray();
} else {
return $this->db->table('penduduk')
->join('keluarga', 'keluarga.id_keluarga = penduduk.id_keluarga')
->getWhere(['id_penduduk' => $id_penduduk])->getRow();
}
}
public function cari($input)
{
return $this->where('nik', $input)->findAll();
}
public function savePenduduk($data)
{
$builder = $this->db->table($this->table);
return $builder->insert($data);
}
public function editPenduduk($data, $id_penduduk)
{
$builder = $this->db->table($this->table);
$builder->where('id_penduduk', $id_penduduk);
return $builder->update($data);
}
public function hapusPenduduk($id_penduduk)
{
$builder = $this->db->table($this->table);
return $builder->delete(['id_penduduk' => $id_penduduk]);
}
public function id($input, $field)
{
return $this->getWhere([$field => $input])->getRow();
}
public function id_array($input, $field)
{
return $this->getWhere([$field => $input])->getResultArray();
}
public function mati($input, $field, $ket)
{
return $this->where($field, $input)->like('ket', 'Hidup')->get()->getResultArray();
}
public function search($input)
{
return $this->like('nik', $input)->orLike('no_kk', $input)->orLike('nama', $input);
}
public function jml($input, $field)
{
return $this->select('count(id_keluarga) as x')->getWhere([$field => $input])->getRow();
}
public function tot($tabel, $tahun = false, $bulan = false, $jorong = false)
{
if ($tahun === false and $bulan === false and $jorong === false) {
return $this->db->table($tabel)->countAllResults();
} elseif ($tahun != false and $bulan != false and $jorong === false) {
return $this->db->table($tabel)->where('year(tgl_update) <= ', $tahun)->where('month(tgl_update) <= ', $bulan)->countAllResults();
} elseif ($tahun === false and $bulan === false and $jorong != false) {
return $this->db->table($tabel)
->join('keluarga', 'keluarga.id_keluarga = penduduk.id_keluarga')
->where('keluarga.alamat', $jorong)->countAllResults();
} elseif ($tahun != false and $bulan === false and $jorong === false) {
return $this->db->table($tabel)->where('year(tgl_update) <= ', $tahun)->countAllResults();
} elseif ($tahun != false and $bulan === false and $jorong != false) {
return $this->db->table($tabel)
->join('keluarga', 'keluarga.id_keluarga = penduduk.id_keluarga')
->where('year(penduduk.tgl_update) <= ', $tahun)
->where('keluarga.alamat', $jorong)
->countAllResults();
} else {
return $this->db->table($tabel)
->join('keluarga', 'keluarga.id_keluarga = penduduk.id_keluarga')
->where('year(penduduk.tgl_update) <= ', $tahun)->where('month(penduduk.tgl_update) <= ', $bulan)->where('keluarga.alamat', $jorong)->countAllResults();
}
}
public function totjekel($tabel, $jekel, $tahun = false, $bulan = false, $jorong = false)
{
if ($tahun === false and $bulan === false and $jorong === false) {
return $this->db->table($tabel)->where('jekel', $jekel)->countAllResults();
} elseif ($tahun != false and $bulan != false and $jorong === false) {
return $this->db->table('penduduk')->where('jekel', $jekel)->where('year(tgl_update) <=', $tahun)->where('month(tgl_update) <= ', $bulan)->countAllResults();
} elseif ($tahun === false and $bulan === false and $jorong != false) {
return $this->db->table('penduduk')
->join('keluarga', 'keluarga.id_keluarga = penduduk.id_keluarga')
->where('jekel', $jekel)->where('keluarga.alamat', $jorong)->countAllResults();
} else {
return $this->db->table('penduduk')
->join('keluarga', 'keluarga.id_keluarga = penduduk.id_keluarga')
->where('jekel', $jekel)->where('year(penduduk.tgl_update) <=', $tahun)->where('month(penduduk.tgl_update) <= ', $bulan)->where('keluarga.alamat', $jorong)->countAllResults();
}
}
public function umur($a)
{
$query = $this->db->query("select TIMESTAMPDIFF(YEAR, tgl_lahir, CURDATE()) as x from penduduk where id_penduduk = " . $a);
return $query->getResultArray();
}
public function jmlUmur($a, $e)
{
$query = $this->db->query("select TIMESTAMPDIFF(YEAR, tgl_lahir, CURDATE()) as x from penduduk where TIMESTAMPDIFF(YEAR, tgl_lahir, CURDATE()) between " . $a . " and " . $e);
return $query->getResultArray();
}
public function jmlUmurTua()
{
$query = $this->db->query("select TIMESTAMPDIFF(YEAR, tgl_lahir, CURDATE()) as x from penduduk where TIMESTAMPDIFF(YEAR, tgl_lahir, CURDATE()) > 65");
return $query->getResultArray();
}
public function countlahir($year, $bulan)
{
return $this->db->table('penduduk')->where('nik', NULL)->where("year(tgl_lahir)", $year)->where("month(tgl_lahir)", $bulan)->countAllResults();
}
public function countmati($year, $bulan)
{
return $this->db->table('kematian')->where("year(tgl_kematian)", $year)->where("month(tgl_kematian)", $bulan)->countAllResults();
}
public function count($x, $isi)
{
return $this->db->table('penduduk')->where($x, $isi)->countAllResults();
}
}
<file_sep>/app/Views/perangkat/input.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<section class="content">
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-balance-scale mr-1"></i>
<?= $ket[0]; ?>
</h3>
</div>
<div class="container-fluid card-body">
<form method="post" action="<?= base_url($link . '/add'); ?>" enctype="multipart/form-data">
<?= csrf_field(); ?>
<div class="row mb-3">
<label for="nik" class="col-sm-2 col-form-label">NIK</label>
<div class="col-sm-10">
<input numeric autocomplete="off" type="text" placeholder="0000000000000000" maxlength="16" minlength="16" class="form-control" id="nik" name="nik" required>
</div>
</div>
<div class="row mb-3">
<label for="nama" class="col-sm-2 col-form-label">Nama</label>
<div class="col-sm-10">
<input autocomplete="off" type="text" placeholder="Masukkan Nama" class="form-control" id="nama" name="nama" required>
</div>
</div>
<div class="row mb-3">
<label for="jabatan" class="col-sm-2 col-form-label">Jabatan</label>
<div class="col-sm-10">
<select class="form-control select2bs4" name="jabatan" id="jabatan" required>
<option value="">Pilih Jabatan </option>
<?php
if ($jabatan != NULL) {
for ($i = 0; $i < count($jabatan); $i++) {
?>
<option value="<?php echo $jabatan[$i] ?>"><?php echo $jabatan[$i] ?></option>
<?php }
} ?>
</select>
</div>
</div>
<div class="row mb-3">
<label for="jekel" class="col-sm-2 col-form-label">Jenis Kelamin</label>
<div class="col-sm-10">
<input autocomplete="off" type="radio" name="jekel" value="Laki - Laki" checked> Laki-laki
<input autocomplete="off" type="radio" name="jekel" value="Perempuan" style="margin-left: 20px;"> Perempuan
</div>
</div>
<div class="row mb-3">
<label for="tgl_lantik" class="col-sm-2 col-form-label">Tanggal Dilantik</label>
<div class="col-sm-10">
<input value="<?= date('Y-m-d'); ?>" autocomplete="off" type="date" placeholder="Masukkan Tanggal Dilantik" class="form-control" id="tgl_lantik" name="tgl_lantik" required>
</div>
</div>
<div class="row mb-3">
<label for="telp" class="col-sm-2 col-form-label">Nomor Telepon</label>
<div class="col-sm-10">
<input autocomplete="off" type="text" placeholder="Masukkan Nomor Telepon" class="form-control" id="telp" name="telp" required>
</div>
</div>
<div class="row mb-3">
<label for="foto" class="col-sm-2 col-form-label label">Foto</label>
<div class="col-sm-1">
<img class="img-thumbnail img-preview" src="<?= base_url(); ?>/img/default.jpg" alt="">
</div>
<div class="col-sm-9">
<div class="custom-file">
<input type="file" class="custom-file-input" id="fotoo" name="foto" onchange="previewImg()">
<p style="color: red">Ekstensi yang diperbolehkan .png | .jpg | .jpeg (Ukuran Max 10 MB dan Nama File Sesuai Nama)</p>
<label for="foto" class="custom-file-label">Masukkan Gambar</label>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Save</button>
<button type="reset" class="btn btn-danger">Clear</button>
</form>
</div>
</div>
</section>
<?= $this->endSection(); ?><file_sep>/app/Views/web/potensi.php
<?= $this->extend('web/template'); ?>
<?= $this->section('content'); ?>
<div style="height: 90px;">
</div>
<main id="main">
<div class="row">
<div class="col-md-9">
<section style="padding: 40px; background: #f8fcfd;">
<?php if ($potensi != NULL) {
for ($i = 0; $i < count($potensi); $i++) {
if ($i % 2 == 0) { ?>
<div class="row" style="padding: 10px;" id="<?= $potensi[$i]['id_potensi']; ?>">
<h3 style="background: #e2e2e2;"><b><?= $potensi[$i]['nama']; ?></b></h3>
<div class="col-md-5">
<img style="max-height: 50vh; max-width: 60vh;" src="<?= base_url(); ?>/potensi/<?= $potensi[$i]['foto']; ?>" alt="">
</div>
<div class="col">
<?= $potensi[$i]['ket']; ?>
</div>
</div>
<?php } else { ?>
<div class="row" style="padding: 10px;" id="<?= $potensi[$i]['id_potensi']; ?>">
<h3 style=" text-align: right;background: #e2e2e2;"><b><?= $potensi[$i]['nama']; ?></b></h3>
<div class="col">
<?= $potensi[$i]['ket']; ?>
</div>
<div class="col-md-5">
<img style="max-height: 50vh; max-width: 60vh;" src="<?= base_url(); ?>/potensi/<?= $potensi[$i]['foto']; ?>" alt="">
</div>
</div>
<?php }
}
} else {
echo 'Potensi tidak ada';
} ?>
</section>
</div>
<div class="col-md-3" style="margin-top: 40px; padding-right: 35px;">
<h5 align=" center"><b>Berita Terbaru</b></h5>
<hr>
<?php if ($berita == NULL) { ?>
<div class="row h" style="word-wrap: break-word; padding: 10px;">
Berita belum ada
</div>
<?php } ?>
<?php
foreach ($berita as $data) {
?>
<div class="row h" style="word-wrap: break-word; padding: 10px;">
<a href="<?= base_url('/web/isi/' . $data['id_berita']) ?>" style="color: black;">
<p><b><?= $data['judul']; ?></b></p>
<?= substr($data['isi'], 0, 50); ?>
<p style="color: #061F2D;"> Baca Selengkapnya...</p>
</a>
</div>
<hr>
<?php } ?>
</div>
</div>
</main>
<?= $this->endSection(); ?><file_sep>/app/Views/potensi/view.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-user-friends mr-1"></i>
View Data : <?= $potensi->nama; ?>
</h3>
<div class="card-tools">
<ul class="nav nav-pills ml-auto">
<li class="nav-item">
<button type="button" style="margin-left: 10px;" class="btn btn-success">
<a href="<?php echo base_url($link . '/edit/' . $potensi->id_potensi); ?>" style="color: white;">
<i class="far fa-plus-square"> Edit Data</i>
</a>
</button>
</li>
</ul>
</div>
</div>
<div class="row card-body" align="center">
<h1><b><u><?= $potensi->nama; ?></u></b></h1>
<div>
<img width="50%" src="<?= base_url(); ?>/potensi/<?= $potensi->foto; ?>" alt="foto <?= $potensi->foto; ?>">
</div>
<div class="dropdown-divider"></div>
<div class="col" align="left">
Nama : <b><i><?= $potensi->nama; ?></i></b>
</div>
<div class="dropdown-divider"></div>
<p style="text-align: left;"><?= $potensi->ket; ?></p>
</div>
</div>
</div>
</div>
</div>
</section>
<?= $this->endSection(); ?><file_sep>/app/Views/template/footer.php
<footer class="main-footer">
<strong>Copyright © <?= date('Y'); ?></strong>
<NAME> - Politeknik Negeri Padang
</footer>
<aside class="control-sidebar control-sidebar-dark">
</aside>
</div>
</body><file_sep>/app/Views/web/index.php
<?= $this->extend('web/template'); ?>
<?= $this->section('content'); ?>
<main id="main">
<div class="row">
<div class="col-md-9">
<?php if ($wali != NULL and $sambutan->kata_sambutan != NULL) { ?>
<section class="section-bg" style="padding: 40px;">
<div class="row">
<div class="col-md-4 col-lg-1">
<img src="<?= base_url(); ?>/perangkat/<?= $wali->foto; ?>" alt="Foto <?= $wali->nama; ?>" height="200wh">
</div>
<div class="container col-md-8 col-lg-8">
<h5>Kata Sambutan </h5>
<p><?= substr($sambutan->kata_sambutan, 0, 500); ?></p>
<a href="<?= base_url(); ?>/web/sambutan" style="color: darkgray;">Baca Selengkapnya...</a>
</div>
</div>
</section>
<?php } ?>
<?php if ($potensi != NULL) { ?>
<section style="padding: 40px; background: #f8fcfd;">
<h5 align="center"><b>Potensi Wilayah</b></h5>
<div id="carouselExampleCaptions" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-indicators">
<button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button>
<?php if (count($potensi) > 1) {
for ($i = 1; $i < count($potensi); $i++) { ?>
<button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="<?= $i; ?>" aria-label="Slide <?= ($i + 1); ?>"></button>
<?php }
} ?>
</div>
<div class="carousel-inner">
<div class="carousel-item active">
<a href="<?= base_url(); ?>/web/potensi/#<?= $potensi[0]['id_potensi']; ?>">
<img height="500px" src="<?= base_url(); ?>/potensi/<?= $potensi[0]['foto']; ?>" class="d-block w-100" alt="<?= $potensi[0]['nama']; ?>">
<div class="carousel-caption d-none d-md-block">
<h5 style="background: grey;"><?= $potensi[0]['nama']; ?></h5>
</div>
</a>
</div>
<?php if (count($potensi) > 1) {
for ($i = 1; $i < count($potensi); $i++) { ?>
<div class="carousel-item">
<a href="<?= base_url(); ?>/web/potensi/#<?= $potensi[$i]['id_potensi']; ?>">
<img height="500px" src="<?= base_url(); ?>/potensi/<?= $potensi[$i]['foto']; ?>" class="d-block w-100" alt="<?= $potensi[$i]['nama']; ?>">
<div class="carousel-caption d-none d-md-block">
<h5 style="background: grey;"><?= $potensi[$i]['nama']; ?></h5>
</div>
</a>
</div>
<?php }
} ?>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
</section>
<?php } ?>
</div>
<div class="col-md-3" style="margin-top: 40px; padding-right: 35px;">
<h5 align=" center"><b>Berita Terbaru</b></h5>
<hr>
<?php if ($berita == NULL) { ?>
<div class="row h" style="word-wrap: break-word; padding: 10px;">
Berita belum ada
</div>
<?php } ?>
<?php
foreach ($berita as $data) {
?>
<div class="row h" style="word-wrap: break-word; padding: 10px;">
<a href="<?= base_url('/web/isi/' . $data['id_berita']) ?>" style="color: black;">
<p><b><?= $data['judul']; ?></b></p>
<?= substr($data['isi'], 0, 50); ?>
<p style="color: #061F2D;"> Baca Selengkapnya...</p>
</a>
</div>
<hr>
<?php } ?>
</div>
</div>
</main>
<?= $this->endSection(); ?>
<file_sep>/app/Views/web/slide.php
<style>
* {
box-sizing: border-box;
}
body {
font-family: Verdana, sans-serif;
}
.mySlides {
display: none;
}
img {
vertical-align: middle;
}
/* Slideshow container */
.slideshow-container {
max-width: 1000px;
position: relative;
margin: auto;
}
/* Caption text */
.text {
color: #f2f2f2;
font-size: 15px;
padding: 8px 12px;
position: absolute;
bottom: 8px;
width: 100%;
text-align: center;
}
/* Number text (1/3 etc) */
.numbertext {
color: #f2f2f2;
font-size: 12px;
padding: 8px 12px;
position: absolute;
top: 0;
}
/* The dots/bullets/indicators */
.dot {
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
.active {
background-color: #717171;
}
/* Fading animation */
.fade {
-webkit-animation-name: fade;
-webkit-animation-duration: 1.5s;
animation-name: fade;
animation-duration: 1.5s;
}
@-webkit-keyframes fade {
from {
opacity: .4
}
to {
opacity: 1
}
}
@keyframes fade {
from {
opacity: .4
}
to {
opacity: 1
}
}
/* On smaller screens, decrease text size */
@media only screen and (max-width: 300px) {
.text {
font-size: 11px
}
}
</style><file_sep>/app/Views/lahir/input.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<!-- Main content -->
<section class="content">
<?php if (session()->getFlashdata('error')) { ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('error'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php } ?>
<form method="post" action="<?= base_url('lahir/add'); ?>">
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-id-card mr-1"></i>
Data Kelahiran
</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse">
<i class="fas fa-minus"></i>
</button>
</div>
</div>
<div class="container-fluid card-body">
<?= csrf_field(); ?>
<div class="row mb-3">
<label for="id_keluarga" class="col-sm-2 col-form-label">No Kartu Keluarga</label>
<div class="col-md-10 col-sm-10">
<select onchange="ambilDataOrtu()" class="form-control select2bs4" name="id_keluarga" id="id_keluarga" required>
<option value="">Pilih No Kartu Keluarga</option>
<?php
foreach ($no_kk as $kel) {
?>
<option value="<?php echo $kel['id_keluarga'] ?>"><?php echo $kel['no_kk'] ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row mb-3">
<label for="nm_ayah" class="col-sm-2 col-form-label">Nama Ayah</label>
<div class="col-sm-10">
<input autocomplete="off" type="text" placeholder="Masukkan Nama Ayah" class="form-control" id="nm_ayah" name="nm_ayah" required>
</div>
</div>
<div class="row mb-3">
<label for="nik_ayah" class="col-sm-2 col-form-label">NIK Ayah</label>
<div class="col-sm-10">
<input autocomplete="off" type="text" placeholder="Masukkan NIK Ayah" class="form-control" id="nik_ayah" name="nik_ayah" required>
</div>
</div>
<div class="row mb-3">
<label for="nm_ibu" class="col-sm-2 col-form-label">Nama Ibu</label>
<div class="col-sm-10">
<input autocomplete="off" type="text" placeholder="Masukkan Nama Ibu" class="form-control" id="nm_ibu" name="nm_ibu" required>
</div>
</div>
<div class="row mb-3">
<label for="nik_ibu" class="col-sm-2 col-form-label">NIK Ibu</label>
<div class="col-sm-10">
<input autocomplete="off" type="text" placeholder="Masukkan NIK Ibu" class="form-control" id="nik_ibu" name="nik_ibu" required>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-user mr-1"></i>
Data Pribadi
</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse">
<i class="fas fa-minus"></i>
</button>
</div>
</div>
<div class="container-fluid card-body">
<?= csrf_field(); ?>
<div class="row mb-3">
<label for="nama" class="col-sm-2 col-form-label">Nama</label>
<div class="col-sm-10">
<input autocomplete="off" type="text" placeholder="Masukkan Nama" class="form-control" id="nama" name="nama" required>
</div>
</div>
<div class="row mb-3">
<label for="tpt_lahir" class="col-sm-2 col-form-label">Tempat Lahir</label>
<div class="col-sm-10">
<input autocomplete="off" type="text" placeholder="Masukkan Tempat Lahir" class="form-control" id="tpt_lahir" name="tpt_lahir" required>
</div>
</div>
<div class="row mb-3">
<label for="tgl_lahir" class="col-sm-2 col-form-label">Tanggal Lahir</label>
<div class="col-sm-10">
<input autocomplete="off" value="<?= date('Y-m-d'); ?>" placeholder="yyyy-mm-dd" type="date" id="datepicker" class="form-control" name="tgl_lahir" required>
</div>
</div>
<div class="row mb-3">
<label for="jekel" class="col-sm-2 col-form-label">Jenis Kelamin</label>
<div class="col-sm-10">
<input type="radio" name="jekel" value="Laki - Laki" checked> Laki - laki
<input type="radio" name="jekel" value="Perempuan"> Perempuan
</div>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-danger">Clear</button>
</form>
</section>
<!-- /.content -->
<!-- /.content -->
<?= $this->endSection(); ?><file_sep>/app/Models/AlamatModel.php
<?php
namespace App\Models;
use CodeIgniter\Model;
class AlamatModel extends Model
{
protected $table = 'alamat';
public function getAlamat()
{
return $this->where('id_alamat', 1)->get()->getRow();
}
public function editAlamat($data)
{
$builder = $this->db->table($this->table);
$builder->where('id_alamat', 1);
return $builder->update($data);
}
}
<file_sep>/app/Views/info/edit.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<!-- Main content -->
<section class="content">
<?php if (session()->getFlashdata('error')) { ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('error'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php } ?>
<form method="post" action="<?= base_url('/data/updateinfo'); ?>" enctype="multipart/form-data">
<?= csrf_field(); ?>
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-phone mr-1"></i>
Kontak
</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse">
<i class="fas fa-minus"></i>
</button>
</div>
</div>
<div class="container-fluid card-body">
<div class="row mb-3">
<label for="telp" class="col-sm-2 col-form-label">Nomor Telepon</label>
<div class="col-sm-10">
<input value="<?= $tambah->telp; ?>" autocomplete="off" placeholder="Masukkan Nomor Telepon" type="text" class="form-control" id="telp" name="telp" style="background:lightgrey">
</div>
</div>
<div class="row mb-3">
<label for="email" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input type="email" value="<?= $tambah->email; ?>" autocomplete="off" placeholder="Masukkan Email" type="text" class="form-control" id="email" name="email" style="background:lightgrey">
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-info mr-1"></i>
Info
</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse">
<i class="fas fa-minus"></i>
</button>
</div>
</div>
<div class="container-fluid card-body">
<div class="row mb-3">
<label for="kata_sambutan" class="col-sm-2 col-form-label">Kata Sambutan</label>
<div class="col-sm-10">
<div class="card card-outline card-info">
<div class="card-header" style="background:lightgrey">
<h3 class="card-title">
Masukkan Kata Sambutan
</h3>
</div>
<div class="card-body pad">
<div class="mb-3">
<textarea name="kata_sambutan" id="kata_sambutan" class="textarea" style="width: 100%; height: 200px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;"><?= $data->kata_sambutan; ?></textarea>
</div>
</div>
</div>
</div>
</div>
<div class="row mb-3">
<label for="visi" class="col-sm-2 col-form-label">Visi</label>
<div class="col-sm-10">
<div class="card card-outline card-info">
<div class="card-header" style="background:lightgrey">
<h3 class="card-title">
Masukkan Visi
</h3>
</div>
<div class="card-body pad">
<div class="mb-3">
<textarea name="visi" id="visi" class="textarea" style="width: 100%; height: 200px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;"><?= $data->visi; ?></textarea>
</div>
</div>
</div>
</div>
</div>
<div class="row mb-3">
<label for="misi" class="col-sm-2 col-form-label">Misi</label>
<div class="col-sm-10">
<div class="card card-outline card-info">
<div class="card-header" style="background:lightgrey">
<h3 class="card-title">
Masukkan Misi
</h3>
</div>
<div class="card-body pad">
<div class="mb-3">
<textarea name="misi" id="misi" class="textarea" style="width: 100%; height: 200px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;"><?= $data->misi; ?></textarea>
</div>
</div>
</div>
</div>
</div>
<div class="row mb-3">
<label for="sejarah" class="col-sm-2 col-form-label">Sejarah</label>
<div class="col-sm-10">
<div class="card card-outline card-info">
<div class="card-header" style="background:lightgrey">
<h3 class="card-title">
Masukkan Sejarah
</h3>
</div>
<div class="card-body pad">
<div class="mb-3">
<textarea name="sejarah" id="sejarah" class="textarea" style="width: 100%; height: 200px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;"><?= $data->sejarah; ?></textarea>
</div>
</div>
</div>
</div>
</div>
<div class="row mb-3">
<label for="wilayah" class="col-sm-2 col-form-label">Wilayah</label>
<div class="col-sm-10">
<div class="card card-outline card-info">
<div class="card-header" style="background:lightgrey">
<h3 class="card-title">
Masukkan Wilayah
</h3>
</div>
<div class="card-body pad">
<div class="mb-3">
<textarea name="wilayah" id="wilayah" class="textarea" style="width: 100%; height: 200px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;"><?= $data->wilayah; ?></textarea>
</div>
</div>
</div>
</div>
</div>
<div class="row mb-3">
<label for="surat" class="col-sm-2 col-form-label">Persyaratan Surat</label>
<div class="col-sm-10">
<div class="card card-outline card-info">
<div class="card-header" style="background:lightgrey">
<h3 class="card-title">
Masukkan Persyaratan Surat
</h3>
</div>
<div class="card-body pad">
<div class="mb-3">
<textarea name="surat" id="surat" class="textarea" style="width: 100%; height: 200px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;"><?= $data->syarat_surat; ?></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</section>
<!-- /.content -->
<!-- /.content -->
<?= $this->endSection(); ?><file_sep>/app/Controllers/Cadiak.php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\PerangkatModel;
use App\Models\PendudukModel;
use App\Models\AuthModel;
class Cadiak extends Controller
{
protected $model;
public function __construct()
{
helper('form');
$this->model = new PerangkatModel();
$this->penduduk = new PendudukModel();
$this->user = new AuthModel();
}
public function index()
{
$ket = [
'Data Cadiak Pandai', '<li class="breadcrumb-item active"><a href="' . base_url() . '/cadiak/index">Data Cadiak Pandai</a></li>'
];
$perangkat = $this->model->getPerangkat(false, 'Cadiak Pandai');
$p = NULL;
for ($i = 0; $i < count($perangkat); $i++) {
if ($this->penduduk->cari($perangkat[$i]['nik']) != NULL) {
$p[$i] = true;
} else {
$p[$i] = false;
}
}
$data = [
'title' => 'Data Cadiak Pandai',
'ket' => $ket,
'link' => 'cadiak',
'perangkat' => $perangkat,
'p' => $p,
'user' => $this->model->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('perangkat/index', $data);
}
public function view($id_pemerintahan)
{
$data = $this->model->getPerangkat($id_pemerintahan, 'Cadiak Pandai');
$ket = [
'View Data Cadiak Pandai', '<li class="breadcrumb-item active"><a href="' . base_url() . '/cadiak/index">Data Cadiak Pandai</a></li>',
'<li class="breadcrumb-item active">View Data</li>'
];
$data = [
'title' => 'View Data Cadiak Pandai',
'ket' => $ket,
'link' => 'cadiak',
'perangkat' => $this->model->getPerangkat($id_pemerintahan, 'Cadiak Pandai'),
'user' => $this->model->getPerangkat(session()->get('id_datauser'), '<NAME>'),
'isi' => $this->user->getUser(session()->id)
];
return view('perangkat/view', $data);
}
public function input()
{
$jabatan = array(
"Ketua", "Sekretaris", "Anggota"
);
$x = 0;
for ($i = 0; $i < count($jabatan); $i++) {
if ($this->model->jabatan('Cadiak Pandai', $jabatan[$i]) == NULL) {
$rev[$x] = $jabatan[$i];
$x++;
} else {
continue;
}
}
if ($x < count($jabatan)) {
$rev[$x] = 'Anggota';
}
$ket = [
'Tambah Data Cadiak Pandai',
'<li class="breadcrumb-item active"><a href="' . base_url() . '/cadiak/index">Data Cadiak Pandai</a></li>',
'<li class="breadcrumb-item active">Tambah Data</li>'
];
$data = [
'title' => 'Tambah Data Cadiak Pandai',
'ket' => $ket,
'link' => 'cadiak',
'jabatan' => $rev,
'user' => $this->model->getPerangkat(session()->get('id_datauser'), '<NAME>'),
'isi' => $this->user->getUser(session()->id)
];
return view('perangkat/input', $data);
}
public function add()
{
$request = \Config\Services::request();
$file = $request->getFile('foto');
if ($file->getError() == 4) {
$nm = "default.jpg";
} else {
$nm = $file->getRandomName();
$file->move('perangkat', $nm);
}
$data = array(
'no' => date('y', strtotime($request->getPost('tgl_lantik'))) . '-06-' . $request->getPost('jabatan'),
'nik' => $request->getPost('nik'),
'nama' => $request->getPost('nama'),
'jabatan' => $request->getPost('jabatan'),
'status' => 'Cadiak Pandai',
'foto' => $nm,
'tgl_lantik' => $request->getPost('tgl_lantik'),
'telp' => $request->getPost('telp'),
'jekel' => $request->getPost('jekel'),
'tgl_update' => date('Y-m-d')
);
$this->model->savePerangkat($data);
session()->setFlashdata('pesan_perangkat', 'Data cadiak panda berhasi ditambahkan.');
return redirect()->to(base_url() . '/cadiak/index');
}
public function edit($id_pemerintahan)
{
$getperangkat = $this->model->getPerangkat($id_pemerintahan, 'Cadiak Pandai');
if (isset($getperangkat)) {
$jabatan = array(
"Ketua", "Sekretaris", "Anggota"
);
$ket = [
'Edit ' . $getperangkat->nama,
'<li class="breadcrumb-item active"><a href="' . base_url() . '/cadiak/index">Data Cadiak Pandai</a></li>',
'<li class="breadcrumb-item active">Edit Data</li>'
];
$data = [
'title' => 'Edit ' . $getperangkat->nama,
'ket' => $ket,
'link' => 'cadiak',
'perangkat' => $getperangkat,
'jabatan' => $jabatan,
'user' => $this->model->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('perangkat/edit', $data);
} else {
session()->setFlashdata('warning_perangkat', 'Data cadiak pandai tidak ditemukan.');
return redirect()->to(base_url() . '/cadiak/index');
}
}
public function update()
{
$request = \Config\Services::request();
$id_pemerintahan = $request->getPost('id_pemerintahan');
$file = $request->getFile('foto');
if ($file->getError() == 4) {
$nm = $request->getPost('lama');
} else {
$nm = $file->getRandomName();
$file->move('perangkat', $nm);
if ($request->getPost('lama') != 'default.jpg') {
unlink('perangkat/' . $request->getPost('lama'));
}
}
if ($request->getPost('tgl_berhenti') == NULL or $request->getPost('tgl_berhenti') == '0000-00-00') {
$berhenti = '';
} else {
$berhenti = $request->getPost('tgl_berhenti');
}
$data = array(
'no' => date('y', strtotime($request->getPost('tgl_lantik'))) . '-06-' . $request->getPost('jabatan'),
'nik' => $request->getPost('nik'),
'nama' => $request->getPost('nama'),
'jabatan' => $request->getPost('jabatan'),
'status' => 'Cadiak Pandai',
'foto' => $nm,
'tgl_lantik' => $request->getPost('tgl_lantik'),
'tgl_berhenti' => $berhenti,
'telp' => $request->getPost('telp'),
'jekel' => $request->getPost('jekel'),
'tgl_update' => date('Y-m-d')
);
$this->model->editPerangkat($data, $id_pemerintahan);
session()->setFlashdata('pesan_perangkat', 'Data cadiakpandai berhasi diedit.');
return redirect()->to(base_url() . '/cadiak/index');
}
public function delete($id_pemerintahan)
{
$getPerangkat = $this->model->getPerangkat($id_pemerintahan, 'Cadiak Pandai');
if (isset($getPerangkat)) {
$this->model->hapusPerangkat($id_pemerintahan);
session()->setFlashdata('pesan_perangkat', 'Data cadiak pandai : ' . $getPerangkat->nama . ' berhasi dihapus.');
return redirect()->to(base_url() . '/cadiak/index');
} else {
session()->setFlashdata('warning_perangkat', 'Data cadiak pandai tidak ditemukan.');
return redirect()->to(base_url() . '/cadiak/index');
}
}
public function hapusbanyak()
{
$request = \Config\Services::request();
$id_pemerintahan = $request->getPost('id_pemerintahan');
if ($id_pemerintahan == null) {
session()->setFlashdata('warning_perangkat', 'Data cadiak pandai belum dipilih, silahkan pilih data terlebih dahulu.');
return redirect()->to(base_url() . '/cadiak/index');
}
$jmldata = count($id_pemerintahan);
for ($i = 0; $i < $jmldata; $i++) {
$this->model->hapusPerangkat($id_pemerintahan[$i]);
}
session()->setFlashdata('pesan_perangkat', 'Data cadiak pandai berhasil dihapus sebanyak ' . $jmldata . ' data.');
return redirect()->to(base_url() . '/cadiak/index');
}
public function import()
{
$ket = [
'Import Data Cadiak Pandai', '<li class="breadcrumb-item active"><a href="' . base_url() . '/cadiak/index">Data Cadiak Pandai</a></li>',
'<li class="breadcrumb-item active">Import Data</li>'
];
$data = [
'title' => 'Import Data Cadiak Pandai',
'ket' => $ket,
'link' => 'cadiak',
'perangkat' => $this->model->getPerangkat(false, 'Cadiak Pandai'),
'user' => $this->model->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('perangkat/import', $data);
}
public function proses()
{
$request = \Config\Services::request();
$file = $request->getFile('file_excel');
$ext = $file->getClientExtension();
if ($ext == 'xls') {
$render = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
} elseif ($ext == 'xlsx') {
$render = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
} else {
session()->setFlashdata('warning_perangkat', 'Ekstensi file salah, silahkan masukkan file berekstensi .xls atau .xlsx.');
return redirect()->to(base_url() . 'cadiak/import');
}
$spreadsheet = $render->load($file);
$sheet = $spreadsheet->getActiveSheet()->toArray();
foreach ($sheet as $x => $excel) {
if ($x == 0) {
continue;
}
if ($excel[5] == '' or $excel[5] == '0000-00-00' or $excel[5] == '-') {
$berhenti = NULL;
} else {
$berhenti = $excel[5];
}
$jabatan = $this->model->cek('Cadiak Pandai', $excel[3], $excel[4], $berhenti);
if ($jabatan != NULL and $jabatan['jabatan'] != 'Anggota') {
if ($excel[3] == $jabatan['jabatan'] and $excel[2] == $jabatan['nama']) { // Data sama akan di skip
continue;
}
}
if ($excel[7] == 'L') {
$excel[7] = 'Laki - Laki';
} elseif ($excel[7] == 'P') {
$excel[7] = 'Perempuan';
}
if ($excel[1] == '-' or $excel[1] == '0000000000000000') {
$nik = '';
} else {
$nik = $excel[1];
}
$data = array(
'no' => date('y', strtotime($excel[4])) . '-06-' . $excel[3],
'nik' => $nik,
'nama' => $excel[2],
'jabatan' => $excel[3],
'status' => 'Cadiak Pandai',
'foto' => 'default.jpg',
'tgl_lantik' => $excel[4],
'tgl_berhenti' => $berhenti,
'telp' => $excel[6],
'jekel' => $excel[7],
'tgl_update' => date('Y-m-d')
);
$this->model->savePerangkat($data);
}
session()->setFlashdata('pesan_perangkat', 'Data cadiak pandai berhasil diimport.');
return redirect()->to('/cadiak');
}
}
<file_sep>/app/Views/web/chartweb.php
<script>
var ctx = document.getElementById('pc_penduduk').getContext('2d');
var pc_penduduk = new Chart(ctx, {
type: 'pie',
data: {
labels: ['<NAME>', '<NAME> Rajo Utara'],
datasets: [{
data: [<?= $g; ?>, <?= $gru; ?>],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
],
borderWidth: 1
}]
},
options: {
maintainAspectRatio: false,
responsive: true,
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Penduduk Tahun <?= date('Y'); ?>'
},
}
}
});
</script>
<script>
<?php
$y = date('Y');
$l = array($y - 4, $y - 3, $y - 2, $y - 1, $y);
?>
var ctx = document.getElementById('lc_rubah').getContext('2d');
var lc_rubah = new Chart(ctx, {
type: 'line',
data: {
labels: [<?= $l[0]; ?>, <?= $l[1]; ?>, <?= $l[2]; ?>, <?= $l[3]; ?>, <?= $l[4]; ?>],
datasets: [{
label: 'Penduduk per Tahun',
data: <?= JSON_ENCODE($rubah); ?>,
backgroundColor: ['#3c8dbc'],
borderColor: ['#3c8dbc']
},
{
label: '<NAME> Rajo Utara',
data: <?= JSON_ENCODE($rubah_gru); ?>,
backgroundColor: ['#d2d6de'],
borderColor: ['#d2d6de']
},
{
label: '<NAME>',
data: <?= JSON_ENCODE($rubah_g); ?>,
backgroundColor: ['#f39c12'],
borderColor: ['#f39c12']
},
]
},
options: {
maintainAspectRatio: true,
responsive: true,
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Perubahan Penduduk 5 Tahun Terakhir'
},
}
}
});
</script>
<script>
var ctx = document.getElementById('bc_pendidikan').getContext('2d');
var bc_pendidikan = new Chart(ctx, {
type: 'bar',
data: {
labels: <?= JSON_ENCODE($pen); ?>,
datasets: [{
label: 'Pendidikan',
data: <?= JSON_ENCODE($isi_p); ?>,
backgroundColor: ['#3bc43b'],
}]
},
options: {
maintainAspectRatio: true,
responsive: true,
indexAxis: 'y',
plugins: {
legend: {
position: 'bottom',
},
title: {
display: true,
text: 'Jumlah Penduduk Berdasakan Pendidikan Tahun <?= date('Y'); ?>'
},
}
}
});
</script>
<script>
var ctx = document.getElementById('pc_agama').getContext('2d');
var pc_agama = new Chart(ctx, {
type: 'pie',
data: {
labels: <?= JSON_ENCODE($agm); ?>,
datasets: [{
data: <?= JSON_ENCODE($isi_a); ?>,
backgroundColor: [
'#b9deff', '#b9ffda', '#ffdab9',
'#ffb9de', '#dab9ff', '#ffdb9'
],
borderWidth: 1
}]
},
options: {
maintainAspectRatio: false,
responsive: true,
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Penduduk Tahun <?= date('Y'); ?>'
},
}
}
});
</script>
<script>
var ctx = document.getElementById('pc_jekel').getContext('2d');
var pc_jekel = new Chart(ctx, {
type: 'pie',
data: {
labels: ['Laki - Laki', 'Perempuan'],
datasets: [{
data: [<?= $laki; ?>, <?= $perempuan; ?>],
backgroundColor: [
'#b9deff', '#b9ffda'
],
borderWidth: 1
}]
},
options: {
maintainAspectRatio: false,
responsive: true,
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Penduduk Tahun <?= date('Y'); ?>'
},
}
}
});
</script>
<script>
var ctx = document.getElementById('pc_jkg').getContext('2d');
var pc_jkg = new Chart(ctx, {
type: 'pie',
data: {
labels: ['Laki - Laki', 'Perempuan'],
datasets: [{
data: [<?= $laki_g; ?>, <?= $perempuan_g; ?>],
backgroundColor: [
'#ffdab9', '#ffb9de'
],
borderWidth: 1
}]
},
options: {
maintainAspectRatio: false,
responsive: true,
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Penduduk Tahun <?= date('Y'); ?> Jorong Gantiang'
},
}
}
});
</script>
<script>
var ctx = document.getElementById('pc_jkgru').getContext('2d');
var pc_jkgru = new Chart(ctx, {
type: 'pie',
data: {
labels: ['Laki - Laki', 'Perempuan'],
datasets: [{
data: [<?= $laki_gru; ?>, <?= $perempuan_gru; ?>],
backgroundColor: [
'#dab9ff', '#ffdb9'
],
borderWidth: 1
}]
},
options: {
maintainAspectRatio: false,
responsive: true,
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Penduduk Tahun <?= date('Y'); ?> Jorong Gunuang Rajo Utara'
},
}
}
});
</script>
<script>
var ctx = document.getElementById('bc_umur').getContext('2d');
var bc_umur = new Chart(ctx, {
type: 'bar',
data: {
labels: ['0-5', '6-12', '13-16', '17-25', '26-35', '36-45', '46-55', '56-65', '65>'],
datasets: [{
label: 'Umur',
data: <?= JSON_ENCODE($umur); ?>,
backgroundColor: ['#acbdb6'],
}]
},
options: {
maintainAspectRatio: true,
responsive: true,
indexAxis: 'y',
plugins: {
legend: {
position: 'bottom',
},
title: {
display: true,
text: 'Jumlah Penduduk Berdasakan Umur Tahun <?= date('Y'); ?>'
},
}
}
});
</script><file_sep>/app/Views/lahir/view.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-user-friends mr-1"></i>
View Data Kelahiran
</h3>
<div class="card-tools">
<ul class="nav nav-pills ml-auto">
<li class="nav-item">
<button type="button" class="btn btn-success">
<a href="<?php echo base_url('/penduduk/edit/' . $penduduk->id_penduduk); ?>" style="color: white;">
<i class="fas fa-edit"> Edit Data</i>
</a>
</button>
</li>
</ul>
</div>
</div>
<div class="card-body">
<table class="table">
<tr>
<td rowspan="12" style="width: 1px;">
<img src="<?= base_url(); ?>/penduduk/<?php if ($penduduk->foto == NULL or $penduduk->foto == 'default.jpg') {
echo 'default.jpg';
} else {
$penduduk->foto;
} ?>" alt="Foto <?= $penduduk->nama; ?>" height="150px">
</td>
<th>No KK</th>
<td> : <?= $penduduk->no_kk; ?></td>
<th>Nama Ayah</th>
<td> : <?= $penduduk->nm_ayah; ?></a></td>
</tr>
<tr>
<th>Nama</th>
<td> : <?= $penduduk->nama; ?></td>
<th>NIK Ayah</th>
<td> : <a href="<?= base_url(); ?>/penduduk/viewortu/<?= $penduduk->nik_ayah; ?>"><?= $penduduk->nik_ayah; ?></a></td>
</tr>
<tr>
<th>Tempat Lahir</th>
<td> : <?= $penduduk->tpt_lahir; ?></td>
<th>Nama Ibu</th>
<td> : <?= $penduduk->nm_ibu; ?></td>
</tr>
<tr>
<th>Tanggal Lahir</th>
<td> : <?= $penduduk->tgl_lahir; ?></td>
<th>NIK Ibu</th>
<td> : <a href="<?= base_url(); ?>/penduduk/viewortu/<?= $penduduk->nik_ibu; ?>"><?= $penduduk->nik_ibu; ?></a></td>
</tr>
<tr>
<th>Jenis Kelamin</th>
<td> : <?= $penduduk->jekel; ?></td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
<?= $this->endSection(); ?><file_sep>/app/Views/template/link_js.php
<script src="<?= base_url(); ?>/aset/plugins/jquery/jquery.min.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/jquery-ui/jquery-ui.min.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/chart.js/Chart.min.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/sparklines/sparkline.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/jqvmap/jquery.vmap.min.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/jqvmap/maps/jquery.vmap.usa.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/jquery-knob/jquery.knob.min.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/moment/moment.min.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/daterangepicker/daterangepicker.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/tempusdominus-bootstrap-4/js/tempusdominus-bootstrap-4.min.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/summernote/summernote-bs4.min.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="<?= base_url(); ?>/aset/dist/js/adminlte.js"></script>
<script src="<?= base_url(); ?>/aset/dist/js/demo.js"></script>
<script src="<?= base_url(); ?>/aset/dist/js/pages/dashboard.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/datatables-responsive/js/dataTables.responsive.min.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/datatables-responsive/js/responsive.bootstrap4.min.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/datatables-buttons/js/dataTables.buttons.min.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/datatables-buttons/js/buttons.bootstrap4.min.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/jszip/jszip.min.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/pdfmake/pdfmake.min.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/pdfmake/vfs_fonts.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/datatables-buttons/js/buttons.html5.min.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/datatables-buttons/js/buttons.print.min.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/datatables-buttons/js/buttons.colVis.min.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/select2/js/select2.full.min.js"></script>
<script src="<?= base_url(); ?>/aset/plugins/uplot/uPlot.iife.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script>
$(function() {
$('.textarea').summernote()
$('.select2bs4').select2({
theme: 'bootstrap4'
})
$(document).on('shown.lte.pushmenu', handleExpandedEvent)
$('[data-widget="pushmenu"]').PushMenu('toggle')
})
$.widget.bridge('uibutton', $.ui.button)
</script><file_sep>/app/Views/surat/view.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<!-- Main content -->
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-user-friends mr-1"></i>
View Data Surat : <?= $surat->tambahan; ?> -> <?= $surat->nama; ?>
</h3>
<div class="card-tools">
<ul class="nav nav-pills ml-auto">
<li class="nav-item">
<button type="button" style="margin-left: 10px;" class="btn btn-success">
<a href="<?php echo base_url($link . '/edit/' . $surat->id_surat); ?>" style="color: white;">
<i class="far fa-plus-square"> Edit Data</i>
</a>
</button>
</li>
<li class="nav-item">
<button type="button" class="btn" style="background:grey; margin-left:10px">
<a href="<?php echo base_url($link . '/print/' . $surat->id_surat); ?>" style="color: white;">
<i class="fas fa-print"></i>
</a>
</button>
</li>
</ul>
</div>
</div><!-- /.card-header -->
<div class="card-body" align="center">
<?= $this->include('template/tgl'); ?>
<div class="row">
<div class="col-sm-2">
<img src="<?= base_url(); ?>/aset/img/<?= $gal->foto; ?>" alt="" width="100px">
</div>
<div class="col">
<h3><b>PEMERINTAHAN KABUPATEN <?= strtoupper($data->kab); ?></b></h3>
<h3><b>KECAMATAN <?= strtoupper($data->kec); ?></b></h3>
<h3><b>WALI NAGARI <?= strtoupper($data->nagari); ?></b></h3>
</div>
</div>
<div class="row">
<div class="col" style="text-align: left;"><b><?= $data->alm; ?></b></div>
<div class="col" style="text-align: right;"><b>Kode Pos <?= $data->kd_pos; ?></b></div>
</div>
<hr>
<div><b><u><?= $jenis_s; ?></u></b></div>
<div>NO.<?= $surat->no_surat; ?><?= $label_s; ?><?= date('Y', strtotime($surat->tgl_surat)); ?></div>
<br>
<div style="text-align: justify;">
<table class="table">
<tr>
<th>NIK</th>
<td> : </td>
<td><?= $surat->nik ?></td>
</tr>
<tr>
<th>Nama</th>
<td> : </td>
<td><?= $surat->nama ?></td>
</tr>
<tr>
<th>Tujuan</th>
<td> : </td>
<td><?= $surat->tujuan ?></td>
</tr>
<tr>
<th><?= $label; ?></th>
<td> : </td>
<td><?php if ($link != 'sku') {
echo 'Rp' . number_format($surat->tambahan, 2, ',', '.');
} else {
echo $surat->tambahan;
} ?></td>
</tr>
<tr>
<th>Yang Menandatangani</th>
<td> : </td>
<td><?= $ttd->nama; ?> - <?= $ttd->jabatan; ?></td>
</tr>
</table>
</div>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</div>
<!-- /.container-fluid -->
</section>
<!-- /.content -->
<!-- /.content -->
<?= $this->endSection(); ?><file_sep>/app/Views/template/ambil_data.php
<script>
function ambilDataOrtu() {
let nokk = $('#id_keluarga').val();
if (nokk.split('').length > 0) {
$.ajax({
url: "<?= base_url('lahir/ortu') ?>/" + nokk,
method: "POST",
dataType: "JSON",
success: function(response) {
$('#nm_ayah').val(response.nm_ayah);
$('#nm_ibu').val(response.nm_ibu);
$('#nik_ayah').val(response.nik_ayah);
$('#nik_ibu').val(response.nik_ibu);
}
});
}
}
function ambilNama() {
let id = $('#id_penduduk').val();
if (id.split('').length > 0) {
$.ajax({
url: "<?= base_url('mati/nama') ?>/" + id,
method: "POST",
dataType: "JSON",
success: function(response) {
$('#nama').val(response.nama);
}
});
}
}
function surat() {
var id = $('#jenis').val();
if (id === "SKTM" || id === "SKPO") {
document.getElementById("divtambah").style.display = "";
document.getElementById("divjamkes").style.display = "none";
document.getElementById("tambahan").attributes["type"].value = "number";
$('#labeltambahan').text("Penghasilan orang tua");
$('#tambahan').attr("placeholder", "Masukkan penghasilan orang tua").placeholder();
} else if (id === "SKM") {
document.getElementById("divtambah").style.display = "";
document.getElementById("divjamkes").style.display = "";
document.getElementById("tambahan").attributes["type"].value = "number";
$('#labeltambahan').text("Penghasilan orang tua");
$('#tambahan').attr("placeholder", "Masukkan penghasilan orang tua").placeholder();
} else if (id === "SKU") {
document.getElementById("divtambah").style.display = "";
document.getElementById("divjamkes").style.display = "none";
document.getElementById("tambahan").attributes["type"].value = "text";
$('#labeltambahan').text("Jenis usaha");
$('#tambahan').attr("placeholder", "Masukkan jenis usaha").placeholder();
} else {
document.getElementById("divtambah").style.display = "none";
document.getElementById("divjamkes").style.display = "none";
}
}
function nik() {
let id = $('#id_keluarga').val();
if (id.split('').length > 0) {
$.ajax({
url: "<?= base_url('sku/getnik') ?>/" + id,
method: "POST",
data: {
id: id
},
dataType: "JSON",
success: function(response) {
var html = '';
var i;
html += '<option value="">Pilih NIK</option>';
for (i = 0; i < response.length; i++) {
html += '<option value="' + response[i].id_penduduk + '">' + response[i].nik + ' - ' + response[i].nama + '</option>';
}
$('#id_penduduk').html(html);
}
});
}
}
function nikmati() {
let id = $('#id_keluarga').val();
if (id.split('').length > 0) {
$.ajax({
url: "<?= base_url('mati/getnik') ?>/" + id,
method: "POST",
data: {
id: id
},
dataType: "JSON",
success: function(response) {
var html = '';
var i;
html += '<option value="">Pilih NIK</option>';
for (i = 0; i < response.length; i++) {
html += '<option value="' + response[i].id_penduduk + '">' + response[i].nik + ' - ' + response[i].nama + '</option>';
}
$('#id_penduduk').html(html);
}
});
}
}
function ambilnik() {
let id = $('#id_penduduk').val();
if (id.split('').length > 0) {
$.ajax({
url: "<?= base_url('user/nik') ?>/" + id,
method: "POST",
dataType: "JSON",
success: function(response) {
$('#username').val(response.nik);
}
});
}
}
function previewImg() {
const foto = document.querySelector('#fotoo');
const imgPreview = document.querySelector('.img-preview');
const label = document.querySelector('.custom-file-label');
label.textContent = foto.files[0].name;
const file = new FileReader();
file.readAsDataURL(foto.files[0]);
file.onload = function(e) {
imgPreview.src = e.target.result;
}
}
function previewImg1() {
const foto = document.querySelector('#foto1');
const imgPreview = document.querySelector('.img_prev1');
const label = document.querySelector('.img_lab1');
label.textContent = foto.files[0].name;
const file = new FileReader();
file.readAsDataURL(foto.files[0]);
file.onload = function(e) {
imgPreview.src = e.target.result;
}
}
function previewImg2() {
const foto = document.querySelector('#foto2');
const imgPreview = document.querySelector('.img_prev2');
const label = document.querySelector('.img_lab2');
label.textContent = foto.files[0].name;
const file = new FileReader();
file.readAsDataURL(foto.files[0]);
file.onload = function(e) {
imgPreview.src = e.target.result;
}
}
</script><file_sep>/app/Models/AduanModel.php
<?php
namespace App\Models;
use CodeIgniter\Model;
class AduanModel extends Model
{
protected $table = 'aduan';
public function getAduan($id = false, $id_aduan = false, $hasil = false)
{
if ($id != false and $id_aduan == false and $hasil == false) { // Semua data
return $this->where('id_user', $id)->orderBy('id_aduan', 'DESC')->findAll();
} elseif ($id == false and $id_aduan == false and $hasil != false) { // Semua data berdasarkan hasil
return $this->where('ket', $hasil)->orderBy('id_aduan', 'DESC')->findAll();
} elseif ($id == false and $id_aduan != false and $hasil == false) { // Salah satu data
return $this->where('id_aduan', $id_aduan)->get()->getRow();
}
}
public function saveAduan($data)
{
$builder = $this->db->table($this->table);
return $builder->insert($data);
}
public function editAduan($data, $id_aduan)
{
$builder = $this->db->table($this->table);
$builder->where('id_aduan', $id_aduan);
return $builder->update($data);
}
public function hapusAduan($id_aduan)
{
$builder = $this->db->table($this->table);
return $builder->delete(['id_aduan' => $id_aduan]);
}
// Lahir dan Mati
public function count($year, $bulan)
{
return $this->db->table('aduan')->where("year(tgl_aduan)", $year)->where("month(tgl_aduan)", $bulan)->countAllResults();
}
}
<file_sep>/app/Views/template/chart.php
<script>
$(function() {
// Pie Chart untuk Data penduduk per jorong -> Penduduk
var pieChartCanvas = $('#pc_jorong').get(0).getContext('2d')
<?php
?>
var jekel = {
labels: [
'<NAME>',
'<NAME>'
],
datasets: [{
data: [<?= $g; ?>, <?= $gru; ?>],
backgroundColor: ['lightblue', 'lightpink'],
}]
}
var pieOptions = {
maintainAspectRatio: false,
responsive: true,
}
var pc_jekel = new Chart(pieChartCanvas, {
type: 'pie',
data: jekel,
options: pieOptions
})
// Pie Chart untuk Data Jenis Kelamin -> Penduduk
var pieChartCanvas = $('#pc_jekel_g').get(0).getContext('2d')
var jekel = {
labels: [
'Perempuan',
'Laki - Laki'
],
datasets: [{
data: [<?= $perempuan; ?>, <?= $laki; ?>],
backgroundColor: ['#f38630', '#0b486b'],
}]
}
var pieOptions = {
maintainAspectRatio: false,
responsive: true,
}
var pc_jekel = new Chart(pieChartCanvas, {
type: 'pie',
data: jekel,
options: pieOptions
})
var pieChartCanvas = $('#pc_jekel_gru').get(0).getContext('2d')
var jekel_g = {
labels: [
'Perempuan',
'Laki - Laki'
],
datasets: [{
data: [<?= $perempuan_gru; ?>, <?= $laki_gru; ?>],
backgroundColor: ['#f38630', '#0b486b'],
}]
}
var pieOptions = {
maintainAspectRatio: false,
responsive: true,
}
var pc_jekel = new Chart(pieChartCanvas, {
type: 'pie',
data: jekel_g,
options: pieOptions
})
// Bar Chart untuk Data Umur -> Penduduk
var DataBar = {
labels: ['0-5', '6-12', '13-16', '17-25', '26-35', '36-45', '46-55', '56-65', '65>'],
datasets: [{
label: 'Umur',
backgroundColor: ['#f56954', '#00a65a', '#f39c12', '#00c0ef',
'#3c8dbc', '#d2d6de', '#f56954', '#00a65a', '#f39c12',
'#f56954', '#00a65a', '#f39c12', '#00c0ef',
'#3c8dbc', '#d2d6de', '#f56954', '#00a65a', '#f39c12',
'#f56954', '#00a65a', '#f39c12', '#00c0ef',
'#3c8dbc', '#d2d6de', '#f56954', '#00a65a', '#f39c12',
'#f56954', '#00a65a', '#f39c12', '#00c0ef',
'#3c8dbc', '#d2d6de', '#f56954', '#00a65a', '#f39c12'
],
borderColor: 'rgba(60,141,188,0.8)',
pointRadius: false,
pointColor: '#3b8bba',
pointStrokeColor: 'rgba(60,141,188,1)',
pointHighlightFill: '#fff',
pointHighlightStroke: 'rgba(60,141,188,1)',
data: <?= JSON_ENCODE($umur); ?>
}, ]
}
var barChartCanvas = $('#bc_umur').get(0).getContext('2d')
var barChartData = jQuery.extend(true, {}, DataBar)
var barChartOptions = {
responsive: true,
maintainAspectRatio: false,
datasetFill: true
}
var barChart = new Chart(barChartCanvas, {
type: 'bar',
data: barChartData,
options: barChartOptions
})
// Kelahiran dan Kematian
var areaChartData = {
labels: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"],
datasets: [{
label: 'Kelahiran <?= date('Y'); ?>',
backgroundColor: 'rgba(60,141,188,0.9)',
borderColor: 'rgba(60,141,188,0.8)',
pointRadius: false,
pointColor: '#3b8bba',
pointStrokeColor: 'rgba(60,141,188,1)',
pointHighlightFill: '#fff',
pointHighlightStroke: 'rgba(60,141,188,1)',
data: <?= JSON_ENCODE($lahir); ?>
},
{
label: 'Kematian <?= date('Y'); ?>',
backgroundColor: 'rgba(210, 214, 222, 1)',
borderColor: 'rgba(210, 214, 222, 1)',
pointRadius: false,
pointColor: 'rgba(210, 214, 222, 1)',
pointStrokeColor: '#c1c7d1',
pointHighlightFill: '#fff',
pointHighlightStroke: 'rgba(220,220,220,1)',
data: <?= JSON_ENCODE($mati); ?>
},
]
};
var barChartCanvas = $('#bc_banding').get(0).getContext('2d')
var barChartData = jQuery.extend(true, {}, areaChartData)
var temp0 = areaChartData.datasets[0]
var temp1 = areaChartData.datasets[1]
barChartData.datasets[0] = temp1
barChartData.datasets[1] = temp0
var barChartOptions = {
responsive: true,
maintainAspectRatio: false,
datasetFill: false
}
var barChart = new Chart(barChartCanvas, {
type: 'bar',
data: barChartData,
options: barChartOptions
})
// Perubahan
<?php
$y = date('Y');
$l = array($y - 4, $y - 3, $y - 2, $y - 1, $y);
?>
var perubahan = {
labels: [<?= $l[0]; ?>, <?= $l[1]; ?>, <?= $l[2]; ?>, <?= $l[3]; ?>, <?= $l[4]; ?>],
datasets: [{
label: 'Penduduk per Tahun',
backgroundColor: [
'#3c8dbc', '#d2d6de', '#f56954', '#00a65a', '#f39c12'
],
borderColor: 'rgba(60,141,188,0.8)',
pointRadius: true,
fill: false,
lineTension: 0.1,
pointColor: '#3b8bba',
pointStrokeColor: 'rgba(60,141,188,1)',
pointHighlightFill: '#fff',
pointHighlightStroke: 'rgba(60,141,188,1)',
data: <?= JSON_ENCODE($rubah); ?>
}, ]
};
var areaChartOptions = {
maintainAspectRatio: false,
responsive: true,
legend: {
display: false
},
scales: {
xAxes: [{
gridLines: {
display: true,
}
}],
yAxes: [{
gridLines: {
display: true,
}
}]
}
}
var lineChartCanvas = $('#bc_rubah').get(0).getContext('2d')
var lineChartOptions = $.extend(true, {}, areaChartOptions)
var lineChartData = $.extend(true, {}, perubahan)
var lineChart = new Chart(lineChartCanvas, {
type: 'line',
data: lineChartData,
options: lineChartOptions
})
// Bar Chart Permohonan Surat
var pieChartCanvas = $('#bc_mohon').get(0).getContext('2d')
<?php
?>
var mohon = {
labels: [
'SKU', 'SKTM', 'SKM', 'SKPO'
],
datasets: [{
data: <?= JSON_ENCODE($mohon); ?>,
backgroundColor: ['lightblue', 'lightpink', 'lightgrey', 'lightgreen'],
}]
}
var pieOptions = {
maintainAspectRatio: false,
responsive: true,
}
var pc_mohon = new Chart(pieChartCanvas, {
type: 'pie',
data: mohon,
options: pieOptions
})
// Bar Chart Aduan
var aduan = {
labels: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"],
datasets: [{
label: 'Penduduk per Tahun',
borderColor: 'rgba(60,141,188,0.8)',
pointRadius: true,
fill: false,
lineTension: 0.1,
pointColor: '#3b8bba',
pointStrokeColor: 'rgba(60,141,188,1)',
pointHighlightFill: '#fff',
pointHighlightStroke: 'rgba(60,141,188,1)',
data: <?= JSON_ENCODE($aduan); ?>
}, ]
};
var areaChartOptions = {
maintainAspectRatio: false,
responsive: true,
legend: {
display: false
},
scales: {
xAxes: [{
gridLines: {
display: true,
}
}],
yAxes: [{
gridLines: {
display: true,
}
}]
}
}
var lineChartCanvas = $('#bc_aduan').get(0).getContext('2d')
var lineChartOptions = $.extend(true, {}, areaChartOptions)
var lineChartData = $.extend(true, {}, aduan)
var lineChart = new Chart(lineChartCanvas, {
type: 'line',
data: lineChartData,
options: lineChartOptions
})
})
</script><file_sep>/app/Views/galeri/edit.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<section class="content">
<?php if (session()->getFlashdata('error')) { ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?= session()->getFlashdata('error'); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php } ?>
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-balance-scale mr-1"></i>
<?= $ket[0]; ?>
</h3>
</div>
<div class="container-fluid card-body">
<form method="post" action="<?= base_url('galeri/update'); ?>" enctype="multipart/form-data">
<?= csrf_field(); ?>
<div class="row mb-3">
<label for="jenis" class="col-sm-2 col-form-label">Jenis Foto / Judul</label>
<div class="col-sm-10">
<input <?php if ($galeri->id_galeri <= 15) {
echo 'readonly';
} ?> value="<?= $galeri->jenis; ?>" autocomplete="off" autofocus placeholder="Masukkan Jenis Foto / Judul" required type="text" class="form-control" id="jenis" name="jenis">
</div>
</div>
<div class="row mb-3">
<label for="foto" class="col-sm-2 col-form-label label">Foto</label>
<div class="col-sm-1">
<img class="img-thumbnail img-preview" src="<?= base_url(); ?>/aset/img/<?= $galeri->foto; ?>" alt="">
</div>
<div class="col-sm-9">
<div class="custom-file">
<input type="file" class="custom-file-input" id="fotoo" name="foto" onchange="previewImg()">
<input type="hidden" name="lama" value="<?= $galeri->foto; ?>">
<p style="color: red">Ekstensi yang diperbolehkan .png | .jpg | .jpeg (Ukuran Max 10 MB dan Nama File Sesuai Nama)</p>
<label for="foto" class="custom-file-label"><?= $galeri->foto; ?></label>
</div>
</div>
</div>
<input type="hidden" value="<?= $galeri->id_galeri; ?>" name="id_galeri" id="id_galeri">
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</section>
<?= $this->endSection(); ?><file_sep>/app/Views/perangkat/edit.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<section class="content">
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-balance-scale mr-1"></i>
<?= $ket[0]; ?>
</h3>
</div>
<div class="container-fluid card-body">
<form method="post" action="<?= base_url($link . '/update'); ?>" enctype="multipart/form-data">
<?= csrf_field(); ?>
<div class="row mb-3">
<label for="nik" class="col-sm-2 col-form-label">NIK</label>
<div class="col-sm-10">
<input value="<?= $perangkat->nik; ?>" numeric autocomplete="off" type="text" placeholder="0000000000000000" maxlength="16" minlength="16" class="form-control" id="nik" name="nik" required>
</div>
</div>
<div class="row mb-3">
<label for="nama" class="col-sm-2 col-form-label">Nama</label>
<div class="col-sm-10">
<input value="<?= $perangkat->nama; ?>" autocomplete="off" type="text" placeholder="Masukkan Nama" class="form-control" id="nama" name="nama" required>
</div>
</div>
<div class="row mb-3">
<label for="jabatan" class="col-sm-2 col-form-label">Jabatan</label>
<div class="col-sm-10">
<select class="form-control select2bs4" name="jabatan" id="jabatan" required autocomplete="off">
<option value="">Pilih Jabatan </option>
<?php
for ($i = 0; $i < count($jabatan); $i++) {
?>
<option <?php if ($perangkat->jabatan == $jabatan[$i]) echo 'selected' ?> value="<?php echo $jabatan[$i] ?>"><?php echo $jabatan[$i] ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row mb-3">
<label for="jekel" class="col-sm-2 col-form-label">Jenis Kelamin</label>
<div class="col-sm-10">
<input type="radio" name="jekel" value="Laki - Laki" <?php if ($perangkat->jekel == 'Laki - Laki') echo 'checked' ?>> Laki-laki
<input type="radio" name="jekel" value="Perempuan" <?php if ($perangkat->jekel == 'Perempuan') echo 'checked' ?>> Perempuan
</div>
</div>
<div class="row mb-3">
<label for="tgl_lantik" class="col-sm-2 col-form-label">Tanggal Dilantik</label>
<div class="col-sm-10">
<input value="<?= $perangkat->tgl_lantik; ?>" autocomplete="off" type="date" placeholder="Masukkan Tanggal Dilantik" class="form-control" id="tgl_lantik" name="tgl_lantik" required>
</div>
</div>
<div class="row mb-3">
<label for="tgl_berhenti" class="col-sm-2 col-form-label">Tanggal Berhenti</label>
<div class="col-sm-10">
<input autocomplete="off" type="date" placeholder="Masukkan Tanggal Dilantik" class="form-control" id="tgl_berhenti" name="tgl_berhenti">
</div>
</div>
<div class="row mb-3">
<label for="telp" class="col-sm-2 col-form-label">Nomor Telepon</label>
<div class="col-sm-10">
<input value="<?= $perangkat->telp; ?>" autocomplete="off" type="text" placeholder="Masukkan Nomor Telepon" class="form-control" id="telp" name="telp" required>
</div>
</div>
<div class="row mb-3">
<label for="foto" class="col-sm-2 col-form-label label">Foto</label>
<div class="col-sm-1">
<img class="img-thumbnail img-preview" src="<?= base_url(); ?>/perangkat/<?= $perangkat->foto; ?>" alt="">
</div>
<div class="col-sm-9">
<div class="custom-file">
<input type="file" class="custom-file-input" id="fotoo" name="foto" onchange="previewImg()">
<input type="hidden" name="lama" value="<?= $perangkat->foto; ?>">
<p style="color: red">Ekstensi yang diperbolehkan .png | .jpg | .jpeg (Ukuran Max 10 MB dan Nama File Sesuai Nama)</p>
<label for="foto" class="custom-file-label"><?= $perangkat->foto; ?></label>
</div>
</div>
</div>
<input type="hidden" name="id_pemerintahan" id="id_pemerintahan" value="<?= $perangkat->id_pemerintahan; ?>">
<button type="submit" class="btn btn-primary">Save</button>
</form>
</div>
</div>
</section>
<?= $this->endSection(); ?><file_sep>/app/Views/mohon/viewadmin.php
<?= $this->extend('template/index'); ?>
<?= $this->section('content'); ?>
<?= $this->include('template/tgl'); ?>
<!-- Main content -->
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-eye mr-1"></i>
View Data : <?= $mohon->jenis; ?> ~ <?= tgl_indo($mohon->tgl_masuk); ?>
</h3>
</div><!-- /.card-header -->
<div class="card-body">
<table class="table">
<tr>
<th>Jenis Surat</th>
<td> : <?= $mohon->jenis; ?></td>
</tr>
<tr>
<th>Tanggal Permohoanan Surat</th>
<td> : <?= tgl_indo($mohon->tgl_masuk); ?></td>
</tr>
<tr>
<th>Tujuan Surat</th>
<td> : <?= $mohon->tujuan; ?></td>
</tr>
<tr>
<th>Keterangan Tambahan</th>
<td> : <?= $mohon->tambahan; ?></td>
</tr>
</table>
</div>
</div>
</div>
<div class="col-6">
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-eye mr-1"></i>
Kelengkapan Syarat
</h3>
</div><!-- /.card-header -->
<div class="card-body">
<form method="post" action="<?= base_url('/permohonan/update'); ?>" enctype="multipart/form-data">
<table class="table">
<tr>
<th>Lampiran Scan KTP : </th>
<td>
<input class="form-check-input" value="KTP Tidak Sesuai" type="radio" name="ktp" id="ktp" checked> Tidak Sesuai
</td>
<td>
<input class="form-check-input" value="KTP Sesuai" type="radio" name="ktp" id="ktp"> Sesuai
</td>
</tr>
<tr>
<td colspan="3"><img src="<?= base_url(); ?>/permohonan/<?= $mohon->scan_ktp; ?>" alt="Scan KTP" width="100%"></td>
</tr>
<tr>
<th>Lampiran Scan KK : </th>
<td>
<input class="form-check-input" value="KK Tidak Sesuai" type="radio" name="kk" id="kk" checked> Tidak Sesuai
</td>
<td>
<input class="form-check-input" value="KK Sesuai" type="radio" name="kk" id="kk"> Sesuai
</td>
</tr>
<tr>
<td colspan="3"><img src="<?= base_url(); ?>/permohonan/<?= $mohon->scan_jamkes; ?>" alt="Scan Jamkesmas" width="100%"></td>
</tr>
<?php if ($mohon->jenis == 'SKM') { ?>
<tr>
<th>Lampiran Scan Jamkesmas: </th>
<td>
<input class="form-check-input" value="Jamkes Tidak Sesuai" type="radio" name="jamkes" id="jamkes" checked> Tidak Sesuai
</td>
<td>
<input class="form-check-input" value="Jamkes Sesuai" type="radio" name="jamkes" id="jamkes"> Sesuai
</td>
</tr>
<tr>
<td colspan="3"><img src="<?= base_url(); ?>/permohonan/<?= $mohon->scan_kk; ?>" alt="Scan KK" width="100%"></td>
</tr>
<?php } ?>
<input type="hidden" name="jenis" value="<?= $mohon->jenis; ?>">
</table>
<input type="hidden" name="id_permohonan" value="<?= $mohon->id_permohonan; ?>">
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
<div class="col-6">
<div class="card">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-eye mr-1"></i>
Data Penduduk
</h3>
</div><!-- /.card-header -->
<div class="card-body">
<table class="table">
<tr>
<th>Nama</th>
<td> : <?= $penduduk->nama; ?></td>
</tr>
<tr>
<th>NIK</th>
<td> : <?= $penduduk->nik; ?></td>
</tr>
<tr>
<th>No KK</th>
<td> : <?= $penduduk->no_kk; ?></td>
</tr>
<tr>
<th>Tempat / Tanggal Lahir</th>
<td> : <?= $penduduk->tpt_lahir; ?> / <?= tgl_indo($penduduk->tgl_lahir); ?></td>
</tr>
<tr>
<th>Jenis Kelamin</th>
<td> : <?= $penduduk->jekel; ?></td>
</tr>
<tr>
<th>Agama</th>
<td> : <?= $penduduk->agama; ?></td>
</tr>
<tr>
<th>Pekerjaan</th>
<td> : <?= $penduduk->kerja; ?></td>
</tr>
<tr>
<th>Status Perkawinan</th>
<td> : <?= $penduduk->status_kawin; ?></td>
</tr>
<tr>
<th>Status Hubungan</th>
<td> : <?= $penduduk->status_hub; ?></td>
</tr>
<tr>
<th>Pendidikan</th>
<td> : <?= $penduduk->pendidikan; ?></td>
</tr>
<tr>
<th>Nama Ayah</th>
<td> : <?= $penduduk->nm_ayah; ?></td>
</tr>
<tr>
<th>Nama Ibu</th>
<td> : <?= $penduduk->nm_ibu; ?></td>
</tr>
</table>
</div>
</div>
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</div>
<!-- /.container-fluid -->
</section>
<!-- /.content -->
<!-- /.content -->
<?= $this->endSection(); ?><file_sep>/app/Models/PerangkatModel.php
<?php
namespace App\Models;
use CodeIgniter\Model;
class PerangkatModel extends Model
{
protected $table = 'pemerintahan';
// Menampilkan data perangkat nagari
public function getPerangkat($id_pemerintahan = false, $status)
{
if ($id_pemerintahan === false) {
return $this->where('status', $status)->orderBy('id_pemerintahan', 'DESC')->findAll();
} else {
return $this->where(['status' => $status])->getWhere(['id_pemerintahan' => $id_pemerintahan])->getRow();
}
}
// Save data
public function savePerangkat($data)
{
$builder = $this->db->table($this->table);
return $builder->insert($data);
}
// Edit data
public function editPerangkat($data, $id_pemerintahan)
{
$builder = $this->db->table($this->table);
$builder->where('id_pemerintahan', $id_pemerintahan);
return $builder->update($data);
}
// Hapus data
public function hapusPerangkat($id_pemerintahan)
{
$builder = $this->db->table($this->table);
return $builder->delete(['id_pemerintahan' => $id_pemerintahan]);
}
// Melihat list jabatan taken
public function jabatan($status, $jabatan)
{
return $this->where(['status' => $status])->where('jabatan', $jabatan)->where('tgl_berhenti', NULL)->orLike('tgl_berhenti', '0000-00-00')->findAll();
}
// Cek data
public function cek($status, $jabatan, $tgl_a, $tgl_e)
{
return $this->where(['status' => $status])->where('jabatan', $jabatan)->where(['tgl_lantik' => $tgl_a])->where('tgl_berhenti', $tgl_e)->get()->getRowArray();
}
// Melihat yang ttd
public function ttd()
{
return $this->where(['status' => 'Perangkat Nagari'])->whereIN('jabatan', ['Wali Nagari', 'Sekretaris Nagari'])->where('tgl_berhenti', NULL)->orLike('tgl_berhenti', '0000-00-00')->findAll();
}
// Mencari wali nagari
public function wali()
{
return $this->where(['status' => 'Perangkat Nagari'])->where('jabatan', 'Wali Nagari')->where('tgl_berhenti', NULL)->orLike('tgl_berhenti', '0000-00-00')->get()->getRow();
}
public function sejarah()
{
return $this->where(['status' => 'Perangkat Nagari'])->where('jabatan', 'Wali Nagari')->orderBy('tgl_lantik', 'ASC')->findAll();
}
public function data($status)
{
return $this->where(['status' => $status])->where('tgl_berhenti', NULL)->orLike('tgl_berhenti', '0000-00-00')->findAll();
}
}
<file_sep>/app/Models/BeritaModel.php
<?php
namespace App\Models;
use CodeIgniter\Model;
class BeritaModel extends Model
{
protected $table = 'berita';
public function getBerita($id_berita = false, $limit = false)
{
if ($id_berita == false and $limit == false) {
return $this->orderBy('id_berita', 'DESC')->findAll();
} elseif ($id_berita != false and $limit == false) {
return $this->getWhere(['id_berita' => $id_berita])->getRow();
} elseif ($id_berita == false and $limit != false) {
return $this->orderBy('id_berita', 'DESC')->limit($limit)->find();
}
}
public function saveBerita($data)
{
$builder = $this->db->table($this->table);
return $builder->insert($data);
}
public function editBerita($data, $id_berita)
{
$builder = $this->db->table($this->table);
$builder->where('id_berita', $id_berita);
return $builder->update($data);
}
public function hapusBerita($id_berita)
{
$builder = $this->db->table($this->table);
return $builder->delete(['id_berita' => $id_berita]);
}
public function search($input)
{
return $this->like('judul', $input)->orLike('penulis', $input)->orLike('tgl_update', $input);
}
}
<file_sep>/app/Controllers/Penduduk.php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\KeluargaModel;
use App\Models\IsiModel;
use App\Models\PendudukModel;
use App\Models\PerangkatModel;
use App\Models\AuthModel;
use App\Models\AlamatModel;
use App\Models\MohonModel;
use App\Models\AduanModel;
use TCPDF;
class pdf extends TCPDF
{
public function Header()
{
$this->data = new AlamatModel();
$x = $this->data->getAlamat();
$kab = strtoupper($x->kab);
$kec = strtoupper($x->kec);
$nag = strtoupper($x->nagari);
$image_file = @FCPATH . 'aset\img\logo.png';
$this->SetY(10);
$this->SetFont('times', 'B', 12);
$isi_header = "
<table>
<tr>
<td width=\"70\"><img src=\"" . $image_file . "\" width=\"80\" height=\"80\"></td>
<td align=\"center\" style=\"font-size:17px\" width=\"90%\">
PEMERINTAHAN KABUPATEN " . $kab . "<br>
KECAMATAN " . $kec . "<br>
WALI NAGARI " . $nag . "
</td>
</tr>
<tr>
<td width=\"50%\">" . $x->alm . "</td>
<td width=\"50%\" align=\"right\">Kode Pos : " . $x->kd_pos . "</td>
</tr>
</table>
<hr>
";
$this->writeHTML($isi_header, true, false, false, false, '');
}
}
class Penduduk extends Controller
{
protected $model, $isi, $keluarga, $data;
public function __construct()
{
helper('form');
$this->model = new PendudukModel();
$this->keluarga = new KeluargaModel();
$this->isi = new IsiModel();
$this->perangkat = new PerangkatModel();
$this->user = new AuthModel();
$this->alm = new AlamatModel();
$this->mohon = new MohonModel();
$this->aduan = new AduanModel();
}
public function index()
{
$request = \Config\Services::request();
$key = $request->getPost('key');
if ($key) {
$datapen = $this->model->join('keluarga', 'keluarga.id_keluarga = penduduk.id_keluarga')->search($key);
} else {
$datapen = $this->model->join('keluarga', 'keluarga.id_keluarga = penduduk.id_keluarga')->orderBy('id_penduduk', 'DESC');
}
$currentPage = $request->getVar('page_data') ? $request->getVar('page_data') : 1;
$ket = [
'Data Penduduk', '<li class="breadcrumb-item active"><a href="/penduduk/index">Data Penduduk</a></li>'
];
$data = [
'title' => 'Data Penduduk',
'ket' => $ket,
'penduduk' => $datapen->paginate(10, 'data'),
'pager' => $this->model->pager,
'currentPage' => $currentPage,
'jml' => $this->model->countAllResults(),
'link' => 'home',
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id),
];
return view('penduduk/index', $data);
}
public function getdata($input)
{
$data = $this->model->search($input);
for ($i = 0; $i < count($data); $i++) {
$json[$i]['nik'] = $data[$i]['nik'];
$json[$i]['nama'] = $data[$i]['nama'];
$json[$i]['no_kk'] = $data[$i]['no_kk'];
}
return $this->response->setJson($json);
}
public function input()
{
$ket = [
'Tambah Data Penduduk',
'<li class="breadcrumb-item active"><a href="/penduduk/index">Data Penduduk</a></li>',
'<li class="breadcrumb-item active">Tambah Data</li>'
];
$data = [
'title' => 'Tambah Data Penduduk',
'ket' => $ket,
'no_kk' => $this->keluarga->getKeluarga(),
'agama' => $this->isi->getIsi(false, 'agama'),
'pendidikan' => $this->isi->getIsi(false, 'pendidikan'),
'pekerjaan' => $this->isi->getIsi(false, 'pekerjaan'),
'status_kawin' => $this->isi->getIsi(false, 'status_kawin'),
'status_hub' => $this->isi->getIsi(false, 'status_hub'),
'link' => 'home',
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('penduduk/input', $data);
}
public function view($id_penduduk)
{
$getpenduduk = $this->model->getpenduduk($id_penduduk);
$ket = [
'View Data Penduduk : ' . $getpenduduk->nik, '<li class="breadcrumb-item active"><a href="/penduduk/index">Data Penduduk</a></li>',
'<li class="breadcrumb-item active">View Data</li>'
];
$data = [
'title' => 'View Data Penduduk : ' . $getpenduduk->nik,
'ket' => $ket,
'penduduk' => $getpenduduk,
'link' => 'home',
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id),
'alm' => $this->alm->getAlamat(),
];
return view('penduduk/view', $data);
}
public function laporan()
{
$ket = [
'Laporan Data Penduduk', '<li class="breadcrumb-item active"><a href="/penduduk/index">Data Penduduk</a></li>',
'<li class="breadcrumb-item active">Laporan Data Penduduk</li>'
];
$data = [
'title' => 'Laporan Data Penduduk',
'ket' => $ket,
'link' => 'home',
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('penduduk/laporan', $data);
}
public function print()
{
$request = \Config\Services::request();
$tahun = $request->getPost('tahun');
$bulan = $request->getPost('bulan');
$data = array(
'title' => 'View Surat',
'p' => $this->model->tot('penduduk', $tahun, $bulan),
'lk' => $this->model->totjekel('penduduk', 'Laki - Laki', $tahun, $bulan),
'pr' => $this->model->totjekel('penduduk', 'Perempuan', $tahun, $bulan),
'p_g' => $this->model->tot('penduduk', $tahun, $bulan, 'Jorong Gantiang'),
'lk_g' => $this->model->totjekel('penduduk', 'Laki - Laki', $tahun, $bulan, 'Jorong Gantiang'),
'pr_g' => $this->model->totjekel('penduduk', 'Perempuan', $tahun, $bulan, 'Jorong Gantiang'),
'p_gru' => $this->model->tot('penduduk', $tahun, $bulan, 'Jorong Gunuang Rajo Utara'),
'lk_gru' => $this->model->totjekel('penduduk', 'Laki - Laki', $tahun, $bulan, 'Jorong Gunuang Rajo Utara'),
'pr_gru' => $this->model->totjekel('penduduk', 'Perempuan', $tahun, $bulan, 'Jorong Gunuang Rajo Utara'),
'data' => $this->alm->getAlamat()
);
$html = view('penduduk/rekap', $data);
$pdf = new pdf(PDF_PAGE_ORIENTATION, PDF_UNIT, 'A4', true, 'UTF-8', false);
$pdf->SetFont('times', '', 12);
$pdf->setHeaderMargin(20);
$pdf->setPrintHeader(true);
$pdf->setPrintFooter(true);
$pdf->SetMargins(20, 40, 20, true);
$pdf->AddPage();
$pdf->writeHTML($html);
$this->response->setContentType('application/pdf');
$pdf->Output('penduduk.pdf', 'I');
}
public function viewnik($nik)
{
$id = $this->model->id($nik, 'nik');
$getpenduduk = $this->model->getpenduduk($id->id_penduduk);
$ket = [
'View Data Penduduk : ' . $getpenduduk->nik, '<li class="breadcrumb-item active"><a href="/penduduk/index">Data Penduduk</a></li>',
'<li class="breadcrumb-item active">View Data</li>'
];
$data = [
'title' => 'View Data Penduduk : ' . $getpenduduk->nik,
'ket' => $ket,
'penduduk' => $getpenduduk,
'link' => 'home',
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id),
'alm' => $this->alm->getAlamat(),
];
return view('penduduk/view', $data);
}
public function add()
{
$request = \Config\Services::request();
$validation = \Config\Services::validation();
$validation->setRules([
'nik' => [
'label' => 'nik',
'rules' => 'is_unique[penduduk.nik]|required|numeric',
'errors' => [
'is_unique' => 'NIK sudah terdaftar',
'required' => 'NIK harus diisi',
'numeric' => 'NIK harus angka'
]
],
]);
if (!$validation->withRequest($request)->run()) {
session()->setFlashdata('error', $validation->listErrors());
return redirect()->to('/penduduk/input');
}
$data = array(
'id_keluarga' => $request->getPost('id_keluarga'),
'nik' => $request->getPost('nik'),
'nama' => $request->getPost('nama'),
'tpt_lahir' => $request->getPost('tpt_lahir'),
'tgl_lahir' => $request->getPost('tgl_lahir'),
'jekel' => $request->getPost('jekel'),
'agama' => $request->getPost('agama'),
'kerja' => $request->getPost('kerja'),
'kwn' => $request->getPost('kwn'),
'goldar' => $request->getPost('goldar'),
'status_kawin' => $request->getPost('status_kawin'),
'status_hub' => $request->getPost('status_hub'),
'pendidikan' => $request->getPost('pendidikan'),
'nm_ayah' => $request->getPost('nm_ayah'),
'nik_ayah' => $request->getPost('nik_ayah'),
'nm_ibu' => $request->getPost('nm_ibu'),
'nik_ibu' => $request->getPost('nik_ibu'),
'paspor' => $request->getPost('paspor'),
'kitap' => $request->getPost('kitap'),
'ket' => 'Hidup',
'tgl_update' => date('Y-m-d')
);
$this->model->savePenduduk($data);
return redirect()->to('/penduduk/index');
}
public function edit($id_penduduk)
{
$getpenduduk = $this->model->getpenduduk($id_penduduk);
if (isset($getpenduduk)) {
$ket = [
'Edit Data : ' . $getpenduduk->no_kk,
'<li class="breadcrumb-item active"><a href="/penduduk/index">Data Penduduk</a></li>',
'<li class="breadcrumb-item active">Edit Data</li>'
];
$data = [
'title' => 'Edit Data : ' . $getpenduduk->no_kk,
'ket' => $ket,
'penduduk' => $getpenduduk,
'no_kk' => $this->keluarga->getKeluarga(),
'agama' => $this->isi->getIsi(false, 'agama'),
'pendidikan' => $this->isi->getIsi(false, 'pendidikan'),
'pekerjaan' => $this->isi->getIsi(false, 'pekerjaan'),
'status_kawin' => $this->isi->getIsi(false, 'status_kawin'),
'status_hub' => $this->isi->getIsi(false, 'status_hub'),
'link' => 'home',
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('penduduk/edit', $data);
} else {
session()->setFlashdata('warning_penduduk', 'No KK ' . $getpenduduk->no_kk . ' Tidak Ditemukan.');
return redirect()->to('/penduduk/index');
}
}
public function update()
{
$request = \Config\Services::request();
$validation = \Config\Services::validation();
$id_penduduk = $request->getPost('id_penduduk');
$m = $this->model->getpenduduk($id_penduduk);
if ($id_penduduk != $m->id_penduduk) {
$validation = \Config\Services::validation();
$validation->setRules([
'nik' => [
'label' => 'nik_kepala',
'rules' => 'is_unique[penduduk.nik_kepala]|required|numeric',
'errors' => [
'is_unique' => 'NIK sudah terdaftar',
'required' => 'NIK harus diisi',
'numeric' => 'NIK harus angka'
]
],
]);
if (!$validation->withRequest($request)->run()) {
session()->setFlashdata('error', $validation->listErrors());
return redirect()->to('/penduduk/edit/' . $id_penduduk);
}
}
$data = array(
'id_keluarga' => $request->getPost('id_keluarga'),
'nik' => $request->getPost('nik'),
'nama' => $request->getPost('nama'),
'tpt_lahir' => $request->getPost('tpt_lahir'),
'tgl_lahir' => $request->getPost('tgl_lahir'),
'jekel' => $request->getPost('jekel'),
'agama' => $request->getPost('agama'),
'kerja' => $request->getPost('kerja'),
'kwn' => $request->getPost('kwn'),
'goldar' => $request->getPost('goldar'),
'status_kawin' => $request->getPost('status_kawin'),
'status_hub' => $request->getPost('status_hub'),
'pendidikan' => $request->getPost('pendidikan'),
'nm_ayah' => $request->getPost('nm_ayah'),
'nik_ayah' => $request->getPost('nik_ayah'),
'nm_ibu' => $request->getPost('nm_ibu'),
'nik_ibu' => $request->getPost('nik_ibu'),
'paspor' => $request->getPost('paspor'),
'kitap' => $request->getPost('kitap'),
'ket' => 'Hidup',
'tgl_update' => date('Y-m-d')
);
$this->model->editPenduduk($data, $id_penduduk);
session()->setFlashdata('pesan_penduduk', 'Data Penduduk Berhasi Diedit.');
return redirect()->to('penduduk/index');
}
public function delete($id_penduduk)
{
$getpenduduk = $this->model->getpenduduk($id_penduduk);
if (isset($getpenduduk)) {
if ($getpenduduk->status_hub != 'Kepala Keluarga') {
$this->model->hapusPenduduk($id_penduduk);
session()->setFlashdata('danger_penduduk', 'Data penduduk ' . $id_penduduk . ' berhasi dihapus.');
return redirect()->to('/penduduk/index');
} elseif ($getpenduduk->status_hub == 'Kepala Keluarga') {
session()->setFlashdata('warning_penduduk', 'Data penduduk tidak bisa dihapus karena kepala keluarga.');
return redirect()->to('/penduduk/index');
}
} else {
session()->setFlashdata('warning_penduduk', 'Data Penduduk ' . $id_penduduk . ' Tidak Ditemukan.');
return redirect()->to('/penduduk/index');
}
}
public function hapusbanyak()
{
$request = \Config\Services::request();
$id_penduduk = $request->getPost('id_penduduk');
if ($id_penduduk == null) {
session()->setFlashdata('warning_penduduk', 'Data Penduduk Belum Dipilih, Silahkan Pilih Data Terlebih Dahulu.');
return redirect()->to('penduduk/index');
}
$jmldata = count($id_penduduk);
$x = 0;
$y = 0;
for ($i = 0; $i < $jmldata; $i++) {
$n = $this->model->getPenduduk($id_penduduk[$i]);
if ($n->status_hub != 'Kepala Keluarga') {
$this->model->hapusPenduduk($id_penduduk[$i]);
$x++;
} else {
$y++;
}
}
if ($x != 0 and $y == 0) {
session()->setFlashdata('pesan_penduduk', $x . ' Data berhasi dihapus.');
return redirect()->to('/penduduk/index');
} elseif ($x == 0 and $y != 0) {
session()->setFlashdata('warning_penduduk', $y . ' Data tidak bisa dihapus karena kepala keluarga.');
return redirect()->to('/penduduk/index');
} elseif ($x != 0 and $y != 0) {
session()->setFlashdata('warning_penduduk', $x . ' Data berhasi dihapus dan ' . $y . ' data tidak bisa dihapus karena kepala keluarga.');
return redirect()->to('/penduduk/index');
} else {
session()->setFlashdata('warning_penduduk', 'Data Penduduk tidak bisa dihapus karena kepala keluarga.');
return redirect()->to('/penduduk/index');
}
}
public function import()
{
$ket = [
'Import Data Penduduk', '<li class="breadcrumb-item active"><a href="/penduduk/index">Data Penduduk</a></li>',
'<li class="breadcrumb-item active">Import Data</li>'
];
$data = [
'title' => 'Import Data Penduduk',
'ket' => $ket,
'link' => 'home',
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('penduduk/import', $data);
}
public function proses()
{
$request = \Config\Services::request();
$file = $request->getFile('file_excel');
$ext = $file->getClientExtension();
if ($ext == 'xls') {
$render = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
} elseif ($ext == 'xlsx') {
$render = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
} else {
session()->setFlashdata('warning_penduduk', 'Ekstensi File Salah, Silahkan Pilih File Ber-ekstensi Excel.');
return redirect()->to('bprn/import');
}
$spreadsheet = $render->load($file);
$sheet = $spreadsheet->getActiveSheet()->toArray();
foreach ($sheet as $x => $excel) {
if ($x == 0) {
continue;
}
$cek = $this->model->id($excel[2], 'nik');
if ($cek != NULL) {
if ($excel[2] == $cek->nik) {
continue;
}
}
if ($excel[6] == 'L' or $excel[6] == 'LAKI-LAKI') {
$excel[6] = 'Laki - Laki';
} elseif ($excel[6] == 'P' or $excel[6] == 'PEREMPUAN') {
$excel[6] = 'Perempuan';
}
if ($excel[13] == 'Kepala Keluarga') {
$datakep = array(
'no_kk' => $excel[1],
'nik_kepala' => $excel[2],
'alamat' => $excel[8],
'tgl_update' => date('Y-m-d')
);
$this->keluarga->saveKeluarga($datakep);
}
if ($excel[2] == '-' or $excel[2] == '0000000000000000') {
$nik = '';
} else {
$nik = $excel[2];
}
$id = $this->keluarga->id($excel[1], 'no_kk');
$data = array(
'id_keluarga' => $id->id_keluarga,
'nik' => $nik,
'nama' => $excel[3],
'tpt_lahir' => $excel[4],
'tgl_lahir' => $excel[5],
'jekel' => $excel[6],
'agama' => $excel[7],
'kerja' => $excel[9],
'kwn' => $excel[10],
'goldar' => $excel[11],
'status_kawin' => $excel[12],
'status_hub' => $excel[13],
'pendidikan' => $excel[14],
'nm_ayah' => $excel[15],
'nik_ayah' => $excel[16],
'nm_ibu' => $excel[17],
'nik_ibu' => $excel[18],
'paspor' => $excel[19],
'kitap' => $excel[20],
'ket' => 'Hidup',
'tgl_update' => date('Y-m-d')
);
$this->model->savePenduduk($data);
}
session()->setFlashdata('pesan_penduduk', 'Data Penduduk Berhasi Diimport.');
return redirect()->to('/penduduk/index');
}
}
<file_sep>/app/Controllers/Galeri.php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\GaleriModel;
use App\Models\AuthModel;
use App\Models\PerangkatModel;
class Galeri extends Controller
{
protected $model;
public function __construct()
{
helper('form');
// Deklarasi model
$this->model = new GaleriModel();
$this->user = new AuthModel();
$this->perangkat = new PerangkatModel();
}
// Menampilkan list data Galeri
public function index()
{
$ket = [
'Data Galeri', '<li class="breadcrumb-item active"><a href="/galeri/index">Data Galeri</a></li>'
];
$data = [
'title' => 'Data Galeri',
'ket' => $ket,
'galeri' => $this->model->getGaleri(),
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('galeri/index', $data);
}
// View detail data
public function view($id_galeri)
{
$data = $this->model->getGaleri($id_galeri);
$ket = [
'View Data Galeri', '<li class="breadcrumb-item active"><a href="/galeri/index">Data Galeri</a></li>',
'<li class="breadcrumb-item active">View Data</li>'
];
$data = [
'title' => 'View Data Galeri',
'ket' => $ket,
'galeri' => $this->model->getGaleri($id_galeri),
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('galeri/view', $data);
}
// Menampilkan form input
public function input()
{
$ket = [
'Tambah Data Galeri',
'<li class="breadcrumb-item active"><a href="/galeri/index">Data Galeri</a></li>',
'<li class="breadcrumb-item active">Tambah Data</li>'
];
$data = [
'title' => 'Tambah Data Galeri',
'ket' => $ket,
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('galeri/input', $data);
}
public function add()
{
$request = \Config\Services::request();
$file = $request->getFile('foto');
if ($file->getError() == 4) {
$nm = "default.jpg";
} else {
$nm = $file->getRandomName();
$file->move('aset/img', $nm);
}
$data = array(
'jenis' => $request->getPost('jenis'),
'foto' => $nm,
);
$this->model->saveGaleri($data);
return redirect()->to(base_url() . '/galeri/index');
}
///edit data
public function edit($id_galeri)
{
$getGaleri = $this->model->getGaleri($id_galeri);
if (isset($getGaleri)) {
$ket = [
'Edit ' . $getGaleri->jenis,
'<li class="breadcrumb-item active"><a href="/galeri/index">Data Galeri</a></li>',
'<li class="breadcrumb-item active">Edit Data</li>'
];
$data = [
'title' => 'Edit ' . $getGaleri->jenis,
'ket' => $ket,
'galeri' => $getGaleri,
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('galeri/edit', $data);
} else {
session()->setFlashdata('warning_galeri', 'galeri dengan Nama : ' . $getGaleri->jenis . ' Tidak Ditemukan.');
return redirect()->to(base_url() . '/galeri/index');
}
}
public function update()
{
$request = \Config\Services::request();
$id_galeri = $request->getPost('id_galeri');
$file = $request->getFile('foto');
if ($file->getError() == 4) {
$nm = $request->getPost('lama');
} else {
$nm = $file->getRandomName();
$file->move('aset/img', $nm);
if ($request->getPost('lama') != 'default.jpg') {
unlink('aset/img/' . $request->getPost('lama'));
}
}
$data = array(
'jenis' => $request->getPost('jenis'),
'foto' => $nm,
);
$this->model->editGaleri($data, $id_galeri);
session()->setFlashdata('pesan_galeri', 'Data Galeri Berhasi Diedit.');
return redirect()->to(base_url() . '/galeri/index');
}
// Menghapus data
public function delete($id_galeri)
{
$getGaleri = $this->model->getGaleri($id_galeri);
if (isset($getGaleri)) {
if ($id_galeri > 15) {
$this->model->hapusGaleri($id_galeri);
session()->setFlashdata('danger_galeri', 'Data Galeri : ' . $getGaleri->jenis . ' Berhasi Dihapus.');
} else {
session()->setFlashdata('warning_galeri', 'Data Galeri : tidak dapat dihapus.');
}
return redirect()->to(base_url() . '/galeri/index');
} else {
session()->setFlashdata('warning_galeri', 'Data Galeri : ' . $getGaleri->jenis . ' Tidak Ditemukan.');
return redirect()->to(base_url() . '/galeri/index');
}
}
// Menghapus data pilihan
public function hapusbanyak()
{
$request = \Config\Services::request();
$id_galeri = $request->getPost('id_galeri');
if ($id_galeri == null) {
session()->setFlashdata('warning', 'Data foto Belum Dipilih, Silahkan Pilih Data Terlebih Dahulu.');
$data['title'] = 'Data Galeri dan Pejabat Desa';
return redirect()->to(base_url() . '/galeri/index');
}
$jmldata = count($id_galeri);
$hps = 0;
$tdk = 0;
for ($i = 0; $i < $jmldata; $i++) {
if ($id_galeri[$i] > 15) {
$this->model->hapusGaleri($id_galeri[$i]);
$hps++;
} else {
$tdk++;
}
}
if ($hps != 0 and $tdk == 0) {
session()->setFlashdata('pesan_galeri', 'Data foto berhasi dihapus sebanyak ' . $hps . ' data');
} elseif ($hps != 0 and $tdk != 0) {
session()->setFlashdata('pesan_galeri', 'Data fto berhasi dihapus sebanyak ' . $hps . ' data dan ' . $tdk . ' data tidak terhapus');
} else {
session()->setFlashdata('warning_galeri', 'Data foto tidak berhasi dihapus sebanyak ' . $tdk . ' data');
}
return redirect()->to(base_url() . '/galeri/index');
}
}
<file_sep>/app/Controllers/Mati.php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\KeluargaModel;
use App\Models\KematianModel;
use App\Models\PendudukModel;
use App\Models\PerangkatModel;
use App\Models\AuthModel;
class Mati extends Controller
{
protected $model, $id_kematian, $keluarga;
public function __construct()
{
helper('form');
$this->keluarga = new KeluargaModel();
$this->penduduk = new PendudukModel();
$this->model = new KematianModel();
$this->perangkat = new PerangkatModel();
$this->user = new AuthModel();
}
public function index()
{
$ket = [
'Data Kematian', '<li class="breadcrumb-item active"><a href="/mati/index">Data Kematian</a></li>'
];
$data = [
'title' => 'Data Kematian',
'ket' => $ket,
'kematian' => $this->model->getKematian(),
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('mati/index', $data);
}
public function input()
{
$ket = [
'Tambah Data Kematian',
'<li class="breadcrumb-item active"><a href="/mati/index">Data Kematian</a></li>',
'<li class="breadcrumb-item active">Tambah Data</li>'
];
$data = [
'title' => 'Tambah Data Kematian',
'ket' => $ket,
'keluarga' => $this->keluarga->getKeluarga(),
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('mati/input', $data);
}
public function getnik($id_keluarga)
{
$data = $this->penduduk->mati($id_keluarga, 'id_keluarga', 'Hidup');
for ($i = 0; $i < count($data); $i++) {
$json[$i]['nik'] = $data[$i]['nik'];
$json[$i]['id_penduduk'] = $data[$i]['id_penduduk'];
$json[$i]['nama'] = $data[$i]['nama'];
}
return $this->response->setJson($json);
}
public function nama($id_penduduk)
{
$data = $this->penduduk->id($id_penduduk, 'id_penduduk');
$json = array();
$json['nama'] = $data->nama;
return $this->response->setJson($json);
}
public function view($id_kematian)
{
$kematian = $this->model->getKematian($id_kematian);
$ket = [
'View Data Kematian : ' . $kematian->nik, '<li class="breadcrumb-item active"><a href="/mati/index">Data Kematian</a></li>',
'<li class="breadcrumb-item active">View Data</li>'
];
$data = [
'title' => 'View Data Kematian : ' . $kematian->nik,
'ket' => $ket,
'mati' => $kematian,
'umur' => $this->penduduk->umur($kematian->id_penduduk)[0]['x'],
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('mati/view', $data);
}
public function add()
{
$request = \Config\Services::request();
$validation = \Config\Services::validation();
$validation->setRules([
'id_penduduk' => [
'label' => 'id_penduduk',
'rules' => 'is_unique[kematian.id_penduduk]|required|numeric',
'errors' => [
'is_unique' => 'NIK sudah terdaftar',
'required' => 'NIK harus diisi',
'numeric' => 'NIK harus angka'
]
],
]);
if (!$validation->withRequest($request)->run()) {
session()->setFlashdata('error', $validation->listErrors());
return redirect()->to('/mati/input');
}
$data = array(
'id_penduduk' => $request->getPost('id_penduduk'),
'tpt_kematian' => $request->getPost('tpt_kematian'),
'tgl_kematian' => $request->getPost('tgl_kematian'),
'sebab' => $request->getPost('sebab'),
'tgl_update' => date('Y-m-d')
);
$this->model->saveKematian($data);
$ubah = [
'ket' => 'Wafat'
];
$this->penduduk->editPenduduk($ubah, $request->getPost('id_penduduk'));
return redirect()->to('/mati/index');
}
public function edit($id_kematian)
{
$getkematian = $this->model->getKematian($id_kematian);
if (isset($getkematian)) {
$ket = [
'Edit Data : ' . $getkematian->nik,
'<li class="breadcrumb-item active"><a href="/mati/index">Data Kematian</a></li>',
'<li class="breadcrumb-item active">Edit Data</li>'
];
$data = [
'title' => 'Edit Data : ' . $getkematian->nik,
'ket' => $ket,
'mati' => $getkematian,
'penduduk' => $this->penduduk->id_array($getkematian->id_keluarga, 'id_keluarga'),
'keluarga' => $this->keluarga->getKeluarga(),
'user' => $this->perangkat->getPerangkat(session()->get('id_datauser'), 'Perangkat Nagari'),
'isi' => $this->user->getUser(session()->id)
];
return view('mati/edit', $data);
} else {
session()->setFlashdata('warning_kematian', 'No KK ' . $getkematian->nik . ' Tidak Ditemukan.');
return redirect()->to('/mati/index');
}
}
public function update()
{
$request = \Config\Services::request();
$id_kematian = $request->getPost('id_kematian');
$m = $this->model->getKematian($id_kematian);
if ($id_kematian != $m->id_kematian) {
$validation = \Config\Services::validation();
$validation->setRules([
'id_penduduk' => [
'label' => 'id_penduduk',
'rules' => 'is_unique[kematian.id_penduduk]|required|numeric',
'errors' => [
'is_unique' => 'NIK sudah terdaftar',
'required' => 'NIK harus diisi',
'numeric' => 'NIK harus angka'
]
],
]);
if (!$validation->withRequest($request)->run()) {
session()->setFlashdata('error', $validation->listErrors());
return redirect()->to('/mati/edit/' . $id_kematian);
}
}
$data = array(
'id_penduduk' => $request->getPost('id_penduduk'),
'tpt_kematian' => $request->getPost('tpt_kematian'),
'tgl_kematian' => $request->getPost('tgl_kematian'),
'sebab' => $request->getPost('sebab'),
'tgl_update' => date('Y-m-d')
);
$this->model->editKematian($data, $id_kematian);
$ubah = [
'ket' => 'Wafat'
];
$this->penduduk->editPenduduk($ubah, $request->getPost('id_penduduk'));
$ubah2 = [
'ket' => 'Hidup'
];
$this->penduduk->editPenduduk($ubah2, $request->getPost('lama'));
session()->setFlashdata('pesan_kematian', 'Data Kematian Berhasi Diedit.');
return redirect()->to('mati/index');
}
public function delete($id_kematian)
{
$kematian = $this->model->getKematian($id_kematian);
if (isset($kematian)) {
$this->model->hapusKematian($id_kematian);
$ubah = [
'ket' => 'Hidup'
];
$this->penduduk->editPenduduk($ubah, $kematian->id_penduduk);
session()->setFlashdata('danger_kematian', 'Data Kematian ' . $id_kematian . ' berhasi dihapus.');
return redirect()->to('/mati/index');
} else {
session()->setFlashdata('warning_kematian', 'Data Kematian ' . $id_kematian . ' Tidak Ditemukan.');
return redirect()->to('/mati/index');
}
}
public function hapusbanyak()
{
$request = \Config\Services::request();
$id_kematian = $request->getPost('id_kematian');
if ($id_kematian == null) {
session()->setFlashdata('warning_kematian', 'Data Kematian Belum Dipilih, Silahkan Pilih Data Terlebih Dahulu.');
return redirect()->to('penduduk/index');
}
$jmldata = count($id_kematian);
$x = 0;
for ($i = 0; $i < $jmldata; $i++) {
$n = $this->model->getKematian($id_kematian[$i]);
$this->model->hapusKematian($id_kematian[$i]);
$ubah = [
'ket' => 'Hidup'
];
$this->penduduk->editPenduduk($ubah, $id_kematian[$i]);
$x++;
}
if ($x != 0) {
session()->setFlashdata('pesan_kematian', $x . ' Data berhasi dihapus.');
return redirect()->to('/mati/index');
} else {
session()->setFlashdata('warning_kematian', 'Data Kematian tidak bisa dihapus karena kepala keluarga.');
return redirect()->to('/mati/index');
}
}
}
<file_sep>/app/Views/surat/printskm.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<?= $this->include('template/tgl'); ?>
<div align="center">
<b><u>SURAT KETERANGAN <?= strtoupper($jenis); ?></u></b><br>
NO.<?= $surat->no_surat; ?>/<?= $link; ?>/KESRA/<?= date('Y', strtotime($surat->tgl_surat)); ?>
</div>
<div style="text-align: justify;">
Yang bertanda tangan dibawah ini adalah Wali Nagari <?= $data->nagari; ?> Kecamatan <?= $data->kec; ?> Kabupaten <?= $data->kab; ?> menerangkan bahwa :
<br>
<table>
<tr>
<td style="width: 110px;">Nama</td>
<td style="width: 10px;"> : </td>
<td style="width: 75%;"><b><?= $surat->nama; ?></b></td>
</tr>
<tr>
<td>Tempat/Tanggal Lahir</td>
<td> : </td>
<td><?= $surat->tpt_lahir; ?> / <?= tgl_indo($surat->tgl_lahir); ?></td>
</tr>
<tr>
<td>Jenis Kelamin</td>
<td> : </td>
<td><?= $surat->jekel; ?></td>
</tr>
<tr>
<td>Pekerjaan</td>
<td> : </td>
<td><?= $surat->kerja; ?></td>
</tr>
<tr>
<td>Agama</td>
<td> : </td>
<td><?= $surat->agama; ?></td>
</tr>
<tr>
<td>Alamat</td>
<td> : </td>
<td><?= $kk->alamat; ?> Nagari <?= $data->nagari; ?> Kecamatan <?= $data->kec; ?> Kabupaten <?= $data->kab; ?></td>
</tr>
</table>
<br><br>
<?php if ($surat->status_hub == 'Anak') { ?>
Nama tersebut di atas adalah anak dari :
<br>
<table>
<tr>
<td style="width: 110px;">Nama Ayah</td>
<td style="width: 10px;"> : </td>
<td style="width: 75%;"><b><?= $surat->nm_ayah; ?></b></td>
</tr>
<?php if ($surat->nik_ayah != NULL or $surat->nik_ayah != '-') { ?>
<tr>
<td>Tempat/Tanggal Lahir</td>
<td> : </td>
<td><?= $ayah->tpt_lahir; ?> / <?= tgl_indo($ayah->tgl_lahir); ?></td>
</tr>
<tr>
<td>Jenis Kelamin</td>
<td> : </td>
<td><?= $ayah->jekel; ?></td>
</tr>
<tr>
<td>Pekerjaan</td>
<td> : </td>
<td><?= $ayah->kerja; ?></td>
</tr>
<tr>
<td>Agama</td>
<td> : </td>
<td><?= $ayah->agama; ?></td>
</tr>
<tr>
<td>Alamat</td>
<td> : </td>
<td><?= $kk->alamat; ?> Nagari <?= $data->nagari; ?> Kecamatan <?= $data->kec; ?> Kabupaten <?= $data->kab; ?></td>
</tr>
<?php } ?>
</table>
<br><br>
<table>
<tr>
<td style="width: 110px;">Nama Ibu</td>
<td style="width: 10px;"> : </td>
<td style="width: 75%;"><b><?= $surat->nm_ibu; ?></b></td>
</tr>
<?php if ($surat->nik_ibu != NULL or $surat->nik_ibu != '-') { ?>
<tr>
<td>Tempat/Tanggal Lahir</td>
<td> : </td>
<td><?= $ibu->tpt_lahir; ?> / <?= tgl_indo($ibu->tgl_lahir); ?></td>
</tr>
<tr>
<td>Jenis Kelamin</td>
<td> : </td>
<td><?= $ibu->jekel; ?></td>
</tr>
<tr>
<td>Pekerjaan</td>
<td> : </td>
<td><?= $ibu->kerja; ?></td>
</tr>
<tr>
<td>Agama</td>
<td> : </td>
<td><?= $ibu->agama; ?></td>
</tr>
<tr>
<td>Alamat</td>
<td> : </td>
<td><?= $kk->alamat; ?> Nagari <?= $data->nagari; ?> Kecamatan <?= $data->kec; ?> Kabupaten <?= $data->kab; ?></td>
</tr>
<?php } ?>
</table>
<br><br>
<?php } ?>
Nama yang tersebut di atas adalah benar Penduduk Nagari <?= $data->nagari; ?> Kecamatan <?= $data->kec; ?> Kabupaten <?= $data->kab; ?>. Dimana sepengetahuan kami keluarga
tersebut memang termasuk kelurga <?= strtolower($jenis); ?> dengan penghasilan <b>Rp<?= number_format($surat->tambahan, 2, ',', '.') ?></b>/bulan.
<br>
Surat Keterangan <?= $jenis; ?> ini kami berikan untuk keperluan <?= $surat->tujuan; ?>.
<br>
<table border="1" align="center">
<tr>
<td style="width: 20px;"><b>No</b></td>
<td style="width: 100px;"><b>Nama</b></td>
<td style="width: 100px;"><b>Jenis Kelamin</b></td>
<td style="width: 45px;"><b>Umur</b></td>
<td style="width: 140px;"><b>Pekerjaan</b></td>
<td><b>Hubungan</b></td>
</tr>
<?php $no = 1;
foreach ($kel as $kel) { ?>
<tr>
<td><?= $no; ?></td>
<td> <?= $kel['nama']; ?></td>
<td> <?= $kel['jekel']; ?></td>
<td> <?= $kel['umur']; ?> Th</td>
<td> <?= $kel['kerja']; ?></td>
<td> <?= $kel['status_hub']; ?></td>
</tr>
<?php $no++;
} ?>
</table>
<br>
Demikianlah Surat Keterangan <?= $jenis; ?> ini kami buat agar dapat dipergunakan seperlunya oleh yang bersangkutan.
<br>
<table align="center">
<tr>
<td>Diketahui <br><NAME></td>
<td><?= $data->nagari; ?>, <?= tgl_indo($surat->tgl_surat); ?><br>
Wali Nagari <?= $data->nagari; ?>
<?php if ($ttd->jabatan == 'Sekretaris Nagari')
echo '<br> a/n Sekretaris Nagari'
?></td>
</tr>
<tr>
<td>
<br><br><br><br>
<hr>
</td>
<td><br><br><br><br><?= $ttd->nama; ?></td>
</tr>
</table>
</div>
</body>
</html>
|
e8bd7c6bd28bf5ae3a04d84f92d5eee2817146d9
|
[
"PHP"
] | 97 |
PHP
|
xvd112/nagari_lama
|
bdc663e777930f31eef75b537eee7025b38dda10
|
5b206bf9dbf47c0320142591a66f1e471e159305
|
refs/heads/master
|
<repo_name>andyb/CrypyoTest<file_sep>/imagecrypt_test.go
package imagecrypt
import (
"log"
"testing"
)
func TestEncyptImage(t *testing.T) {
msg := "This is the message to be encrypted"
key := "1234567890123456"
encrypted := make([]byte, len(msg))
err := Encrypt(encrypted, []byte(msg), []byte(key))
if err != nil {
panic(err)
}
log.Printf("Encrypted value is %s", encrypted)
decrypted := make([]byte, len(msg))
err = Decrypt(decrypted, encrypted, []byte(key))
if err != nil {
panic(err)
}
log.Printf("Decrypted value is %s", decrypted)
}
<file_sep>/README.md
CrypyoTest
==========
<file_sep>/imagecrypt.go
package imagecrypt
import (
"crypto/aes"
"crypto/cipher"
"log"
)
//1. Encrypt an image
//2. Decrypt an image
//3. Encrypt some text
//4. Decrypt some text
func Encrypt(dst, src, key []byte) error {
log.Println("Encrypt started")
iv := []byte(key)[:aes.BlockSize]
aesBlockEncrypter, err := aes.NewCipher([]byte(key))
if err != nil {
return err
}
aesEncrypter := cipher.NewCFBEncrypter(aesBlockEncrypter, iv)
aesEncrypter.XORKeyStream(dst, src)
log.Println("Encrypt ended")
return nil
}
func Decrypt(dst, src, key []byte) error {
iv := []byte(key)[:aes.BlockSize]
aesBlockDecrypter, err := aes.NewCipher([]byte(key))
if err != nil {
return nil
}
aesDecrypter := cipher.NewCFBDecrypter(aesBlockDecrypter, iv)
aesDecrypter.XORKeyStream(dst, src)
return nil
}
|
54a00ae505a29b0dbe9a160f14474aeea471513f
|
[
"Markdown",
"Go"
] | 3 |
Go
|
andyb/CrypyoTest
|
479d6c64c209eb15f37ba7ee143593e140dfa196
|
5ee8e16172d8c2133b77c2dac6595ebfb8210a4b
|
refs/heads/master
|
<file_sep>import pygame
from pygame.sprite import Sprite
from random import randint
class Star(Sprite):
def __init__(self, screen):
"""Initialize the ship and set its starting position."""
super().__init__()
self.screen = screen
# Load the star image and get its rect
self.image = pygame.image.load('images/star.bmp')
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
def blitme(self):
"""Draw the star at its current location."""
self.screen.blit(self.image, self.rect)
def update(self):
"""Randomly position the star"""
self.rect.centerx = randint(self.screen_rect.left, self.screen_rect.right)
self.rect.centery = randint(self.screen_rect.top, self.screen_rect.bottom)
<file_sep># alien_invasion
An interactive game in python 3 written by following the "Python Crash Course" Book.
|
d44ee0ff6840a7aa8155335cb21420227df6d0b3
|
[
"Markdown",
"Python"
] | 2 |
Python
|
rebinsilva/alien_invasion
|
8a3fede1e75074715857342ac30daa55ceaf416a
|
505ee1dd87bbf0af65c23b808119361488f0a2ec
|
refs/heads/master
|
<file_sep>using OdeToFood.Core;
using System.Collections.Generic;
using System.Linq;
namespace OdeToFood.Data
{
public interface IRestaurantData
{
IEnumerable<Restaurant> GetRestaurantsByName(string name);
}
public class InMemoryRestaurantData : IRestaurantData
{
readonly List<Restaurant> restaurants;
public InMemoryRestaurantData()
{
restaurants = new List<Restaurant>()
{
new Restaurant { Id = 1, Name = "<NAME>", Location = "London", Cuisine=CuisineType.Italian},
new Restaurant { Id = 2, Name = "<NAME>", Location = "Manchester", Cuisine=CuisineType.Indian},
new Restaurant { Id = 3, Name = "Pedros", Location = "Norwich", Cuisine = CuisineType.Mexican}
};
}
public IEnumerable<Restaurant> GetRestaurantsByName(string name = null)
{
return from r in restaurants
where string.IsNullOrEmpty(name) || r.Name.StartsWith(name)
orderby r.Name
select r;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Shuffle
{
public static class Extensions
{
// this modifier means you can call this method as if it were a member of the first argument.
public static IEnumerable<T> InterleaveSequenceWith<T>(this IEnumerable<T> first, IEnumerable<T> second)
{
var firstIter = first.GetEnumerator();
var secondIter = second.GetEnumerator();
while (firstIter.MoveNext() && secondIter.MoveNext())
{
yield return firstIter.Current;
yield return secondIter.Current;
}
}
public static bool SequenceEquals<T>(this IEnumerable<T> first, IEnumerable<T> second)
{
var firstIter = first.GetEnumerator();
var secondIter = second.GetEnumerator();
while (firstIter.MoveNext() && secondIter.MoveNext())
{
if (!firstIter.Current.Equals(secondIter.Current))
{
return false;
}
}
return true;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Attributes
{
[MySpecial]
class SomeOtherClass
{
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
namespace Shuffle
{
class Program
{
static void Main(string[] args)
{
//var startingDeck = from s in Suits()
// from r in Ranks()
// select new { Suit = s, Rank = r };
var startingDeck = Suits().SelectMany(
suit => Ranks().Select(
rank => new { Suit = suit, Rank = rank }));
// display each card we've generated
foreach (var card in startingDeck)
{
Console.WriteLine(card);
}
var shuffledDeck = startingDeck;
var times = 0;
do
{
// shuffle cards by interleaving top 26 cards with bottom 26 cards
shuffledDeck = shuffledDeck.Take(26).InterleaveSequenceWith(shuffledDeck.Skip(26));
times++;
} while (!startingDeck.SequenceEquals(shuffledDeck));
Console.WriteLine("Shuffled!");
Console.WriteLine(times);
}
static IEnumerable<string> Suits()
{
yield return "clubs";
yield return "diamonds";
yield return "hearts";
yield return "spades";
}
static IEnumerable<string> Ranks()
{
yield return "two";
yield return "three";
yield return "four";
yield return "five";
yield return "six";
yield return "seven";
yield return "eight";
yield return "nine";
yield return "ten";
yield return "jack";
yield return "queen";
yield return "king";
yield return "ace";
}
}
}
<file_sep># dot-net-test
.NET Test Projects
|
070450ed09f8ecd5f4d89e35811f600fc6c06764
|
[
"Markdown",
"C#"
] | 5 |
C#
|
DannyNicholas/dot-net-test
|
709fa792b3dd56e74e3d460d8ff472565c2cd73f
|
ab43cac28a57ef5e772318c88c6d7254a52c1ac7
|
refs/heads/master
|
<file_sep>"""
Package for DjangoDoc1.
"""
<file_sep>"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
import django
from django.test import TestCase
from django.utils import timezone
import datetime
from .models import Question
# TODO: Configure your database in settings.py and sync before running tests.
#class SimpleTest(TestCase):
# """Tests for the application views."""
# if django.VERSION[:2] >= (1, 7):
# # Django 1.7 requires an explicit setup() when running tests in PTVS
# @classmethod
# def setUpClass(cls):
# django.setup()
# def test_basic_addition(self):
# """
# Tests that 1 + 1 always equals 2.
# """
# self.assertEqual(1 + 1, 2)
class QuestionMethodTests(TestCase):
def test_was_published_recently_with_future_question(self):
"""
was_published_recently() should return False for questions whose pub_date is in the future.
"""
time = timezone.now() + datetime.timedelta(days=30)
future_question = Question(pub_date=time)
self.assertEqual(future_question.was_published_recently(), False)
def test_was_published_recently_with_old_question(self):
"""
was_published_recently() should return False for questions whose
pub_date is older than 1 day.
"""
time = timezone.now() - datetime.timedelta(days=30)
old_question = Question(pub_date=time)
self.assertEqual(old_question.was_published_recently(), False)
def test_was_published_recently_with_recent_question(self):
"""
was_published_recently() should return True for questions whose
pub_date is within the last day.
"""
time = timezone.now() - datetime.timedelta(hours=1)
recent_question = Question(pub_date=time)
self.assertEqual(recent_question.was_published_recently(), True)
|
28c2ea310bbcb8da3a666164a8505159a43ad0cd
|
[
"Python"
] | 2 |
Python
|
LJTDiSZ/DjangoDoc1
|
3ae0497425e315ccd191752653c899e09398c583
|
cc8d69a0e7db0e76f61ccba26be989f4575bb5b9
|
refs/heads/master
|
<file_sep>fuzzel = os.require('/lib/fuzzel.lua')
registration = {}
screenText = ""
client = {}
function client.command(cmd, fn, autoCompleteFn, help)
registration[cmd] = {
cmd=cmd,
fn=fn,
autoCompleteFn=autoCompleteFn,
help=help
}
end
function client.autoComplete(args, opt)
strargs = table.concat(args, " ")
--Remove spaces and quotes, since we don't want to match them
strargs = string.gsub(strargs,"[\" ]","")
--Find the options that most closely resemble our command so far
local results = fuzzel.FuzzyAutocompleteDistance(strargs, opt)
local values = {}
for k, v in pairs(results) do
if v:sub(0, #strargs) == strargs then
table.insert(values, v)
end
end
if #values == 1 then
input = getCmd(input).." "..values[1]
elseif #values > 0 then
client.write(" "..table.concat(values, ", "))
end
end
function client.resetDisplay()
-- Remove trailing newline
screenText = string.sub(screenText, 0, -2)
term.clear()
term.setOutput(screenText)
term.setInput(input)
end
function client.start(name)
inputEnable = true
input = "> "
screenText = "Welcome to "..name.." "
function getUserInput(input)
return string.sub(input, 3, -2)
end
function splitInput(input)
local res = {}
for word in input:gmatch("%w+") do
table.insert(res, word)
end
return res
end
function getCmd(input)
return table.remove(splitInput(input), 1)
end
function getArgs(input)
local args = splitInput(input)
table.remove(args, 1)
return args
end
function getArgsAndCmd(input)
local args = splitInput(input)
local cmd = table.remove(args, 1)
if cmd == nil then
cmd = ""
end
return {cmd, args}
end
term.addInputListener(function(event)
if not inputEnable then
return term.setInput(input)
end
input = event.userInput
if #input < 2 then
input = "> "
term.setInput(input)
end
if #term.getOutput() < #screenText then
inputEnable = false
client.resetDisplay()
inputEnable = true
return
end
client.saveScreen()
character = input:sub(#input)
if character == "\n" then
-- Remove the newline from the input
input = getUserInput(input)
term.write("> "..input)
local info = getArgsAndCmd(input)
if registration[info[1]] ~= nil then
local reg = registration[info[1]]
local success, err = os.pcall(reg["fn"], info[2])
if success == false then
term.write('Error: '..err)
end
else
if #info[1] > 0 then
term.write("Error: Unknown command '"..info[1].."'")
end
end
client.saveScreen()
-- Reset the input
input = "> "
client.resetDisplay()
elseif character == "`" then
-- Autocomplete input
inputEnable = false
input = getUserInput(input)
local info = getArgsAndCmd(input)
if registration[info[1]] == nil then
local function keys(tab)
local keyset = {}
local n = 0
for k,v in pairs(tab) do
n=n+1
keyset[n]=k
end
return keyset
end
local results = fuzzel.FuzzyAutocompleteDistance(info[1], keys(registration))
local values = {}
for k, v in pairs(results) do
if v:sub(0, #info[1]) == info[1] then
table.insert(values, v)
end
end
if #values == 1 then
input = values[1].." "
elseif #values > 0 then
client.write(" "..table.concat(values, ", "))
end
elseif registration[info[1]] ~= nil then
local reg = registration[info[1]]
if type(reg["autoCompleteFn"]) == "function" then
local success, err = os.pcall(reg["autoCompleteFn"], info[2])
if success == false then
term.write('Error: '..err)
end
end
end
client.saveScreen()
input = "> "..input
client.resetDisplay()
inputEnable = true
end
end)
wlan.on('term.write', function(...)
client.write('event: ['..from_label..'] ('..event..') '..table.concat({...}, ' '))
if event == "term.write" then
for k, v in pairs({...}) do
client.write('['..from_label..'] '..v)
end
end
end)
term.clear()
os.wait(client.resetDisplay, 0.1)
end
function client.write(text)
term.write(text)
client.saveScreen()
end
function client.saveScreen()
screenText = term.getOutput()
end
function client.clearScreen()
term.clear()
client.saveScreen()
end
client.command("help", function(args)
for k,v in pairs(registration) do
term.write(k..": "..v["help"])
end
end, function(args)
input = "help"
end, "display this help message")
return client
<file_sep>local server = os.require('/lib/server.lua')
server.start()
local client = os.require('/lib/client.lua')
client.start("mine client 1.0")
<file_sep>client = os.require('/lib/client.lua')
client.command("status", function(args)
if #args > 0 then
local cmd = args[1]
if cmd == "battery" then
-- TODO: handle battery status
term.write('Battery status: Unknown')
elseif cmd == "logistics" then
-- TODO: handle logisitics status
term.write('Logistics network status: Unknown')
else
term.write("Error: Unknown subcommand '"..cmd.."'")
end
else
term.write("Error: Missing subcommand")
end
end, function(args) client.autoComplete(args, {"battery", "logistics"}) end, "Get the status of things")
client.start("wrist client 1.0")
<file_sep>term.write("Install finished.")
local json = os.require('/lib/json.lua')
os.require('/compat/base/init.lua')
local label = os.getComputerLabel()
if car ~= nil then
term.write('Detected car server...')
os.require('/servers/car.lua')
elseif lan == nil then
term.write('Detected wrist client...')
os.require('/clients/wrist.lua')
elseif label:sub(0, 4) == "mine" then
term.write('Detected mine server...')
os.require('/servers/mine.lua')
elseif label:sub(0, 7) == "factory" then
term.write('Detected factory server...')
os.require('/servers/factory.lua')
else
term.write('Unknown computer type...')
end
<file_sep>from __future__ import print_function
import subprocess
import json
import sys
import os
def addFiles(dirPath, ignore=[]):
lines = []
for name in os.listdir(dirPath):
path = '{0}/{1}'.format(dirPath, name)
if path in ignore:
pass
elif os.path.isfile(path):
print("Adding {}...".format(path), end='')
try:
if sys.argv[-1] == '--prod':
lua = subprocess.check_output([
r'C:\Users\Eeems\AppData\Roaming\npm\luamin', '-f', path],
shell=True)
else:
subprocess.check_output([
r'C:\Users\Eeems\AppData\Roaming\npm\luaparse', '-f', path],
shell=True)
with open(path, 'r') as f:
lua = f.read()
except subprocess.CalledProcessError as e:
print('FAIL')
raise Exception(e.output)
lines.append(
"disk.writeFile('/{0}', {1})\n".format(path[4:], json.dumps(lua)))
print('OK')
else:
lines += addFiles(path, ignore)
return lines
def Main():
if not os.path.exists('src/install.lua'):
raise Exception("src/install.lua missing")
if not os.path.exists('dist'):
os.makedirs('dist')
if not os.path.exists('build'):
os.makedirs('build')
lines = ["term.write('Installing...')\n"] + \
addFiles('src', ['src/install.lua', 'src/lib/shim.lua'])
print('Adding src/install.lua...', end='')
try:
subprocess.check_output([
r'C:\Users\Eeems\AppData\Roaming\npm\luaparse', '-f', 'src/install.lua'],
shell=True)
except subprocess.CalledProcessError as e:
print('FAIL')
raise Exception(e.output)
with open('src/install.lua', 'r') as f:
lines = lines + list(f)
print('OK')
print("Building...", end='')
with open('build/install.lua', 'w') as f:
f.writelines(lines)
with open('dist/install.lua', 'w') as f:
try:
lua = subprocess.check_output([
r'C:\Users\Eeems\AppData\Roaming\npm\luamin', '-f',
'build/install.lua'], shell=True)
f.write(lua)
except subprocess.CalledProcessError as e:
print('FAIL')
raise Exception(e.output)
print('OK')
if __name__ == "__main__":
Main()
<file_sep>os.require('/lib/events.lua')
events = EventManager()
function ServerEvent(name, from_label, args)
local _ServerEvent = Event(name, args)
_ServerEvent.from = from_label
function _ServerEvent:reply(event, ...)
if wlan ~= nil then
wlan.emit(_ServerEvent.from, 'event', ServerEvent(event, os.getComputerLabel(), {...}))
end
end
end
local server = {}
function server.on(event, fn)
events:on(event, fn)
end
function server.un(event, fn)
events:un(event, fn)
end
function server.start()
if wlan ~= nil then
wlan.on('event', function(event, e)
events:emit(event, e)
end)
end
end
function server.emit(to, event, ...)
if wlan ~= nil then
wlan.emit(to, 'event', ServerEvent(event, os.getComputerLabel(), {...}))
end
end
function server.broadcast(event, ...)
if wlan ~= nil then
wlan.broadcast('event', ServerEvent(event, os.getComputerLabel(), {...}))
end
end
return server
<file_sep>if error == nil then
function error(msg)
assert(false, msg)
end
end
<file_sep>server = os.require('/lib/server.lua')
client = os.require('/lib/client.lua')
server.on('error', function(e)
for k, v in pairs(e.args) do
client.write(v)
end
end)
server.on('echo', function(e)
wlan.emit(e.from, 'term.write', unpack(e.args))
end)
server.start()
client.command("echo", function(args)
table.insert(args, 1, 'echo')
server.broadcast(unpack(args))
end, nil, "Get the status of things")
client.start("factory client 1.0")
<file_sep>function Event(name, args)
local _Event = {}
_Event.name = name
_Event.args = args
return _Event
end
function EventManager()
local _EventManager = {}
_EventManager._handles = {}
function _EventManager:on(event, fn)
if _EventManager._handles[event] == nil then
_EventManager._handles[event] = {}
end
table.insert(_EventManager._handles[event], fn)
end
function _EventManager:un(me, event, fn)
if _EventManager._handles[event] ~= nil then
for k, v in pairs(_EventManager._handles[event]) do
if v == fn then
table.remove(_EventManager._handles[event], k)
end
end
end
end
function _EventManager:emit(me, event, ...)
local args = {...}
if _EventManager._handles[event] ~= nil then
for k, fn in pairs(_EventManager._handles[event]) do
local success, err = os.pcall(fn, Event(event, args))
if success == false then
if event == "error" then
term.write('Error: '..err)
else
self:emit('error', err)
end
end
end
end
end
return _EventManager
end
|
1e1e0f1e7ace7da419010ecb882d127a8d3032df
|
[
"Python",
"Lua"
] | 9 |
Lua
|
Eeems/factorio_computer_scripts
|
fa0029c9b376cfb3c8fbe69ea8d7a9507db382b7
|
6109bc2374dea78e9373e62dcda3d112018af602
|
refs/heads/master
|
<file_sep>import webapp2
from webapp2_extras import sessions
from google.appengine.ext import ndb
import time
import datetime
# student_user_name='null'
head='''
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<center><h1><p style="color:#6699FF">Welcome to the Jobstore</p></h1></center></head>
<body bgcolor="#E6E6FA">
'''
select="""
<center>
Looking for a dream job or a reliable employee?<br>
You are a:
<table>
<form action="/student" method="post">
<tr><input type="submit" value="student"> or
</form>
<form action="/recruiter" method="post">
<tr><input type="submit" value="recruiter"></tr>
</form>
</table>
</center>
"""
LoginForm_stu="""
<center>
<form action="/login_stu" method="post">
Login Form for Students:
<table>
<tr><td>username:</td><td><input type='text' name="username_stu"></td></tr>
<tr><td>password:</td><td><input type='<PASSWORD>' name="password_stu" ></td></tr>
<tr><td><input type="submit" value="Submit"><input type="reset" value="Reset">
</form>
<form action="/register_stu" method="post">
<input type="submit" value="Register"></td></tr>
</form>
</table>
</center>
"""
LoginForm_rec="""
<center>
<form action="/login_rec" method="post">
Login Form for Recruiter:
<table>
<tr><td>username:</td><td><input type='text' name="username_rec"></td></tr>
<tr><td>password:</td><td><input type='password' name="password_rec" ></td></tr>
<tr><td><input type="submit" value="Submit"><input type="reset" value="Reset">
</form>
<form action="/register_rec" method="post">
<input type="submit" value="Register"></td></tr>
</form>
</table>
</center>
"""
SignupForm_stu="""
<center>
<form action="/signup_stu" method="post" >
Add Details for Students:
<table>
<tr><td>First Name:</td><td><input type='text' name="firstname_stu" ></td></tr>
<tr><td>Last Name:</td><td><input type='text' name="lastname_stu"></td></tr>
<tr><td>Salary:</td><td><input type='text' name="salary_stu"></td></tr>
<tr><td>Skills:</td><td><input type='text' name="skills_stu"></td></tr>
<tr><td>Location:</td><td><input type='text' name="location_stu"></td></tr>
<tr><td>Experience:</td><td><input type='text' name="exp_stu"></td></tr>
<tr><td>Email id:</td><td><input type='text' name="email_stu"></td></tr>
<tr><td>User Name:</td><td><input type='text' name="username_stu"></td></tr>
<tr><td>Password:</td><td><input type='password' name="password_stu" ></td></tr>
<tr><td></td><td><input type="submit" value="Submit"><input type="reset" value="Reset">
</form></center>
"""
SignupForm_rec="""
<center>
<form action="/signup_rec" method="post" >
Add Details for Job:
<table>
<tr><td>Company Name:</td><td><input type='text' name="companyname_rec" ></td></tr>
<tr><td>Salary Provided:</td><td><input type='text' name="salary_rec"></td></tr>
<tr><td>Skills Needed:</td><td><input type='text' name="skills_rec"></td></tr>
<tr><td>Location:</td><td><input type='text' name="location_rec"></td></tr>
<tr><td>Link to apply:</td><td><input type='text' name="link_rec"></td></tr>
<tr><td>Experience:</td><td><input type='text' name="exp_rec"></td></tr>
<tr><td>User Name:</td><td><input type='text' name="username_rec"></td></tr>
<tr><td>Password:</td><td><input type='password' name="password_rec" ></td></tr>
<tr><td></td><td><input type="submit" value="Submit"><input type="reset" value="Reset">
</form></center>
"""
class LoginDB_stu(ndb.Model):
first_name=ndb.StringProperty()
last_name=ndb.StringProperty()
stu_salary=ndb.StringProperty()
stu_skills=ndb.StringProperty()
stu_location=ndb.StringProperty()
stu_exp=ndb.StringProperty()
stu_email=ndb.StringProperty()
stu_password=ndb.String<PASSWORD>()
stu_username=ndb.StringProperty()
class LoginDB_rec(ndb.Model):
company_name=ndb.StringProperty()
# last_name=ndb.StringProperty()
rec_salary=ndb.StringProperty()
rec_skills=ndb.StringProperty()
rec_location=ndb.StringProperty()
rec_link=ndb.StringProperty()
rec_exp=ndb.StringProperty()
rec_password=ndb.String<PASSWORD>()
rec_username=ndb.StringProperty()
class MainStu(webapp2.RequestHandler):
def post(self):
self.response.write('<html>'+head+'<body>'+LoginForm_stu+'</body></html>')
class MainRec(webapp2.RequestHandler):
def post(self):
self.response.write('<html>'+head+'<body>'+LoginForm_rec+'</body></html>')
class LoginHandler_stu(webapp2.RequestHandler):
c=100
def post(self):
global student_user_name
global student_password
#self.response.write("list of companies")
student_user_name=self.request.get('username_stu')
student_password=self.request.get('<PASSWORD>stu')
q=LoginDB_stu.query(LoginDB_stu.stu_username==student_user_name)
self.response.write('<br>')
self.response.write('<br>')
x=q.fetch()
if len(x)==0:
self.response.write(head+'please sign up')
else:
for i in x:
#z=dict(x)
#print (json.dumps({x}))
pwd_stu=i.stu_password
fn_stu=i.first_name
ln_stu=i.last_name
sal_stu=i.stu_salary
skill_stu=i.stu_skills
loc_stu=i.stu_location
exp_stu=i.stu_exp
email_stu=i.stu_email
LoginHandler_stu.c=200
#print (json.dumps(pwd_stu))
#self.response.write(json.dumps(fn_stu))
#self.response.write(json.dumps(pwd_stu))
# self.response.write(' ')
# self.response.write('<br>')
# q1=ndb.gql("Select * from LoginDB_rec")
# for h in q1:
# com_name=h.company_name
# com_location=h.rec_location
# # com_pwd=h.rec_password
# com_sal=h.rec_salary
# com_skills=h.rec_skills
# com_link=h.rec_link
# # self.response.write(h)
# self.response.write('<br>')
# self.response.write('<br>')
# self.response.write('<br><html><body><b>Company Profile:</b><br>Company name is: '+com_name+'<br>Location:'+com_location+'<br>salary: '+com_sal+
# '<br>skills needed are:'+com_skills+'<br><a href="'+com_link+'">Apply</a>')
if pwd_stu==student_password:
self.response.write('<br><html><body><b>Your Profile:</b><br>your name is: '+fn_stu+' '+ln_stu+'<br>salary needed is: '+sal_stu+
'<br>skills are:'+skill_stu+'<br>locations is: '+loc_stu+'<br>'+'experience is'+exp_stu+'<br>'+'Email is '+email_stu+'<br>')
self.response.write('''<form action="/search_stu" method="post">
<input type='text' name="search_skills" placeholder="Skills">
<input type='text' name="search_sal" placeholder="Salary"><br>
<input type='text' name="search_loc" placeholder="Location">
<input type='text' name="search_exp" placeholder="Experience">
<input type="submit" value="Search">
</form><br>
<form action ="/update_stu" method = "post">
<input type="submit" value="Update Profile">
</form>
''')
# student_user_name=self.request.get('username_stu')
# student_password=self.request.get('<PASSWORD>')
# self.response.write('<br>')
self.response.write('<br>')
# self.response.write('<b>Company Profile:</b>')
# q=LoginDB_stu.query(LoginDB_stu.stu_username==student_user_name)
# x=q.fetch()
# if len(x)==0:
# self.response.write(head+'please sign up')
# else:
# for i in x:
# q1=ndb.gql("Select * from LoginDB_rec")
# for h in q1:
# com_name=h.company_name
# com_location=h.rec_location
# # com_pwd=h.rec_password
# com_sal=h.rec_salary
# com_skills=h.rec_skills
# com_link=h.rec_link
# # self.response.write(h)
# # self.response.write('<br>')
# self.response.write('<br><html><body><br><b>'+com_name+'</b><br>Location:'+com_location+'<br>salary: '+com_sal+
# '<br>skills needed are:'+com_skills+'<br><a href="'+com_link+'">Apply</a>')
# return abc
else:
self.response.write('password does not match')
# def disp(self):
# # self.response.write('the value of c is')
# print("the username is ", LoginHandler_stu.un)
# return LoginHandler_stu.un
# self.response.write(LoginHandler_stu.c)
# print('the value of c is:',LoginHandler_stu.c)
class SearchHandler_stu(webapp2.RequestHandler):
def post(self):
self.response.write('<b>Company Profile:</b>')
# q=LoginDB_stu.query(LoginDB_stu.stu_username==student_user_name)
# x=q.fetch()
# if len(x)==0:
# else:
# for i in x:
key_skill=self.request.get('search_skills')
key_sal=self.request.get('search_sal')
key_loc=self.request.get('search_loc')
key_exp=self.request.get('search_exp')
# if key_skill=="":
# self.response.write("skill is None<br>")
# else:
# self.response.write("skill is "+key_skill+"<br>")
# self.response.write("Key is "+key_skill+"<br>")
# if key_sal=="":
# self.response.write("sal is None<br>")
# else:
# self.response.write("salary is "+key_sal+"<br>")
# if key_loc=="":
# self.response.write("loc is None<br>")
# else:
# self.response.write("location is "+key_loc+"<br>")
# if key_exp=="":
# self.response.write("exp is None<br>")
# else:
# self.response.write("exp is "+key_exp+"<br>")
if key_skill==key_sal==key_exp==key_loc=="":
self.response.write("Give atleast one entry<br>")
else:
# self.response.write("Key is "+key_skill)
q1=ndb.gql("Select * from LoginDB_rec")
# y=q1.fetch()
# if len(y)==0:
# self.response.write(head+'No Records')
# else:
for h in q1:
com_name=h.company_name
com_location=h.rec_location
# com_pwd=h.rec_password
com_sal=h.rec_salary
com_skills=h.rec_skills
com_link=h.rec_link
com_exp=h.rec_exp
f=0
# self.response.write(h)
if key_skill==com_skills and f<>1:
self.response.write('<br><html><body><br><b>'+com_name+'</b><br>Location:'+com_location+'<br>salary: '+com_sal+
'<br>skills needed are:'+com_skills+'<br><a href="'+com_link+'">Apply</a><br>'+'Experience:'+com_exp)
f=1
if key_sal==com_sal and f<>1:
self.response.write('<br><html><body><br><b>'+com_name+'</b><br>Location:'+com_location+'<br>salary: '+com_sal+
'<br>skills needed are:'+com_skills+'<br><a href="'+com_link+'">Apply</a><br>'+'Experience:'+com_exp)
f=1
if key_loc==com_location and f<>1:
self.response.write('<br><html><body><br><b>'+com_name+'</b><br>Location:'+com_location+'<br>salary: '+com_sal+
'<br>skills needed are:'+com_skills+'<br><a href="'+com_link+'">Apply</a><br>'+'Experience:'+com_exp)
f=1
if key_exp==com_exp and f<>1:
self.response.write('<br><html><body><br><b>'+com_name+'</b><br>Location:'+com_location+'<br>salary: '+com_sal+
'<br>skills needed are:'+com_skills+'<br><a href="'+com_link+'">Apply</a><br>'+'Experience:'+com_exp)
f=1
# else:
# self.response.write(head+'No Records')
# self.response.write(h)
# self.response.write('<br>')
# self.response.write('<br><html><body><br><b>'+com_name+'</b><br>Location:'+com_location+'<br>salary: '+com_sal+
# '<br>skills needed are:'+com_skills+'<br><a href="'+com_link+'">Apply</a>')
class UpdateHandler_stu(LoginHandler_stu):
def post(self):
self.response.write("update")
# obj=LoginHandler_stu()
# obj.post()
# update_username=obj.disp()
# print("update calling username",update_username)
# self.response.write('update calling username')
# self.response.write(update_username)
# obj=LoginHandler_stu(webapp2)
# xyz=obj.post()
# p=LoginDB_stu.query(LoginDB_stu.stu_username==student_user_name)
# a=p.fetch()
# self.response.write(a)
self.response.write("""
<center>
<form action="/updated_stu" method="post" >
Update Details for Students:
<table>
<tr><td>First Name:</td><td><input type='text' name="firstname_stu" ></td></tr>
<tr><td>Last Name:</td><td><input type='text' name="lastname_stu"></td></tr>
<tr><td>Salary:</td><td><input type='text' name="salary_stu"></td></tr>
<tr><td>Skills:</td><td><input type='text' name="skills_stu"></td></tr>
<tr><td>Location:</td><td><input type='text' name="location_stu"></td></tr>
<tr><td>Experience:</td><td><input type='text' name="exp_stu"></td></tr>
<tr><td>Email id:</td><td><input type='text' name="email_stu"></td></tr>
<tr><td>User Name:</td><td><input type='text' name="username_stu"></td></tr>
<tr><td>Password:</td><td><input type='password' name="password_stu" ></td></tr>
<tr><td></td><td><input type="submit" value="Submit"><input type="reset" value="Reset">
</form></center>
""")
# obj=LoginHandler_stu()
# test=obj.disp()
# self.response.write(test)
class LoginHandler_rec(webapp2.RequestHandler):
def post(self):
global company_user_name
global company_password
#self.response.write("list of companies")
company_user_name=self.request.get('username_rec')
company_password=self.request.get('password_rec')
r=LoginDB_rec.query(LoginDB_rec.rec_username==company_user_name)
self.response.write('<br>')
self.response.write('<br>')
y=r.fetch()
if len(y)==0:
self.response.write(head+'please sign up')
else:
for i in y:
#z=dict(x)
#print (json.dumps({x}))
pwd_rec=i.rec_password
c_name=i.company_name
#ln_stu=i.last_name
sal_rec=i.rec_salary
skill_rec=i.rec_skills
loc_rec=i.rec_location
#print (json.dumps(pwd_stu))
#self.response.write(json.dumps(fn_stu))
#self.response.write(json.dumps(pwd_stu))
self.response.write(' ')
self.response.write('<br>')
if pwd_rec==company_password:
self.response.write('<br><html><body>Company name is: '+c_name+'<br>Salary to be given is: '+sal_rec+
'<br>skills needed are:'+skill_rec+'<br>locations is: '+loc_rec)
self.response.write('</body></html>')
else:
self.response.write('password does not match')
class RegistrationForm_stu(webapp2.RequestHandler):
def post(self):
self.response.write('<html><body>'+SignupForm_stu+'</body></html>')
class RegistrationForm_rec(webapp2.RequestHandler):
def post(self):
self.response.write('<html><body>'+SignupForm_rec+'</body></html>')
class SignupHandler_stu(webapp2.RequestHandler):
def post(self):
login_details_stu=LoginDB_stu(first_name=self.request.get('firstname_stu'),
last_name=self.request.get('lastname_stu'),
stu_salary=self.request.get('salary_stu'),
stu_skills=self.request.get('skills_stu'),
stu_location=self.request.get('location_stu'),
stu_exp=self.request.get('exp_stu'),
stu_email=self.request.get('email_stu'),
stu_password=self.request.get('password_stu'),
stu_username=self.request.get('username_stu'))
#apply_date =datetime.datetime.now().strftime("%d-%m-%y"))
login_details_stu.put()
self.response.write('database updated')
class SignupHandler_rec(webapp2.RequestHandler):
def post(self):
login_details_rec=LoginDB_rec(company_name=self.request.get('companyname_rec'),
#last_name=self.request.get('lastname_stu'),
rec_salary=self.request.get('salary_rec'),
rec_skills=self.request.get('skills_rec'),
rec_location=self.request.get('location_rec'),
rec_exp=self.request.get('exp_rec'),
rec_password=self.request.get('password_rec'),
rec_username=self.request.get('username_rec'),
rec_link=self.request.get('link_rec'))
#apply_date =datetime.datetime.now().strftime("%d-%m-%y"))
login_details_rec.put()
self.response.write('database updated')
class Welcome(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/html'
self.response.write('<html>'+head+'<body>'+select+'</body></html>')
app = webapp2.WSGIApplication([
('/', Welcome),('/student',MainStu),('/login_stu',LoginHandler_stu),('/register_stu',RegistrationForm_stu),('/signup_stu',SignupHandler_stu),('/recruiter',MainRec),('/login_rec',LoginHandler_rec),('/register_rec',RegistrationForm_rec),('/signup_rec',SignupHandler_rec),('/search_stu',SearchHandler_stu),('/update_stu',UpdateHandler_stu)], debug=True)
|
a9a777e709a458f6296776a3ea5c85ba72a0c934
|
[
"Python"
] | 1 |
Python
|
ashmeetchhabra/JobStore
|
8fa9f6081ad383b9baa9ce299cb1ab7ba62dce6e
|
0999f2f355f8c2c573d8027229597ff9f813bb94
|
refs/heads/main
|
<file_sep># Friends list app
codemy.com tutorial<file_sep>class FriendPdf < Prawn::Document
def initialize(friend)
super()
@friend =friend
text "here #{@friend&.first_name}" if @friend.nil?
end
end
|
16fe1b26335c5c348cb2e7b1abb836b8f88773ab
|
[
"Markdown",
"Ruby"
] | 2 |
Markdown
|
justyna98/railsfriends
|
5025dbb145dd8e0d99eac5ac209c79af68eeb9cd
|
64e5801cbaf095ef4db5daf15da2499d322f6728
|
refs/heads/master
|
<file_sep>import React from "react";
import TourBox from "./TourBox";
const Tours = () => {
return (
<section className="section-tours">
<div className="section-tours__wrapper">
<div className="u-text-center u-margin-bottom-big">
<h2 className="heading-secondary">Most popular tours</h2>
</div>
<div className="row">
<TourBox />
</div>
<div className="u-text-center u-margin-top-huge">
<a href="" className="btn btn--green">
Discover all tours
</a>
</div>
</div>
</section>
);
};
export default Tours;
<file_sep>import React from 'react';
import { Field, reduxForm } from 'redux-form';
import PropTypes from 'prop-types';
import { renderField } from './FormFields';
import {
minLength2, maxLength15, aol, required, email,
} from './validation';
const BookingForm = ({ handleSubmit, submitting }) => (
<form onSubmit={handleSubmit} className="form">
<div className="u-margin-bottom-medium">
<h2 className="heading-secondary">
Start booking now!
</h2>
</div>
<Field
name="username"
type="text"
component={renderField}
label="Full name"
validate={[required, maxLength15, minLength2]}
/>
<Field
name="email"
type="email"
component={renderField}
label="Email address"
validate={[required, email]}
warn={aol}
/>
<div>
<button type="submit" disabled={submitting}>
Submit
</button>
</div>
</form>
);
BookingForm.propTypes = {
submitting: PropTypes.bool.isRequired,
handleSubmit: PropTypes.func.isRequired,
};
export default reduxForm({
form: 'BookingForm',
})(BookingForm);
<file_sep>import toursData from '../../components/Tours/tourdata';
const tours = (state = toursData, action) => {
switch (action.type) {
case 'ACTION_TYPE':
return;
default:
// eslint-disable-next-line
return state;
}
};
export default tours;
<file_sep>import React from 'react';
import BookingForm from './BookingForm';
const Booking = () => (
<section className="section-booking">
<div className="row">
<div className="book">
<div className="book__form">
<BookingForm />
</div>
</div>
</div>
</section>
);
export default Booking;
<file_sep>import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
const Story = ({ storyData }) => (
<div>
{storyData.map(s => (
<div key={s.name} className="row">
<div className="story">
<figure className="story__shape">
<img src={s.image} alt="story_photo" className="story__img" />
<figcaption className="story__caption">
{s.name}
</figcaption>
</figure>
<div className="story__text">
<h3 className="heading-tertiary u-margin-bottom-small">
{s.review}
</h3>
<p>
{s.text}
</p>
</div>
</div>
</div>
))}
</div>
);
Story.propTypes = {
storyData: PropTypes.array.isRequired,
};
export default connect(state => ({ storyData: state.stories }))(Story);
<file_sep>const toursData = [
{
backStyle: 'card__side--back-1',
pictureStyle: 'card__picture-1',
heading: 'The Sea Explorer',
headingSpan: 'card__heading-span-1',
details: {
days: 3,
people: 30,
guides: 2,
feature: 'cozy hotels',
difficulty: 'easy',
},
price: 295,
},
{
backStyle: 'card__side--back-2',
pictureStyle: 'card__picture-2',
heading: 'The Forest Hiker',
headingSpan: 'card__heading-span-2',
details: {
days: 7,
people: 40,
guides: 7,
feature: 'provided tents',
difficulty: 'medium',
},
price: 495,
},
{
backStyle: 'card__side--back-3',
pictureStyle: 'card__picture-3',
heading: 'the snow adventurer',
headingSpan: 'card__heading-span-3',
details: {
days: 5,
people: 15,
guides: 3,
feature: 'provided tents',
difficulty: 'hard',
},
price: 895,
},
];
export default toursData;
<file_sep>import React, { Fragment } from 'react';
import { Provider } from 'react-redux';
import { ConnectedRouter as Router } from 'react-router-redux';
import { Route, Switch } from 'react-router-dom';
import Header from './Header';
import About from './About';
import Features from './Features';
import Tours from './Tours';
import Stories from './Stories';
import Booking from './Booking';
import { history, store } from '../redux/store/store';
const App = () => (
<Provider store={store}>
<Router history={history}>
<Switch>
<Route
path="/"
render={() => (
<Fragment>
<Header />
<About />
<Features />
<Tours />
<Stories />
<Booking />
</Fragment>
)}
/>
</Switch>
</Router>
</Provider>
);
export default App;
<file_sep>import React from 'react';
import logoWhite from '../../styles/img/logo-white.png';
const Header = () => (
<header className="header">
<div className="header__logo-box">
<img className="header__logo" src={logoWhite} alt="logo" />
</div>
<div className="header__text">
<h1 className="heading-primary">
<span className="heading-primary--main">
Outdoors
</span>
<span className="heading-primary--sub">
is where life happens
</span>
</h1>
<a href="/" className="btn btn--white btn--animated">
Discover our tours
</a>
</div>
</header>
);
export default Header;
|
6f40f1b3275b10ab06c232ca2aef96cd755263d5
|
[
"JavaScript"
] | 8 |
JavaScript
|
Glebfedchenko/outdoors
|
aa5d97769437ae67b5ea0f61d5408baa80912a80
|
1e4c1644f5932675dfd95a966703ad957babebd5
|
refs/heads/master
|
<repo_name>worminator123/Warteliste<file_sep>/src/Start.java
/**
* Created by Markus-PC on 16.01.2017.
*/
public class Start {
public static void main(String[] args) {
System.out.println("Hi");
System.out.println("Welt");
}
}
<file_sep>/README.md
"# Warteliste"
Hier gibts nichts zu sehen...
|
bfccb8fae6095b32ef9f0a1f18fe67018261517b
|
[
"Markdown",
"Java"
] | 2 |
Java
|
worminator123/Warteliste
|
bd8e04821c97b0808b4f65baa0cc508d6f8ebe38
|
4d65bbee0b018129c21aba10301dc2f00cd00b9d
|
refs/heads/master
|
<repo_name>mason0510/revealrobot<file_sep>/robot/revealRobot.go
package revealrobot
import (
cf "../config"
"../utils/stringhandler"
"context"
"encoding/json"
"fmt"
"github.com/eoscanada/eos-go"
"github.com/eoscanada/eos-go/ecc"
"io/ioutil"
"net/http"
"time"
)
// =========================== 设置信息 ========================================
const IS_TEST = true
var (
roundBasedGames [6]string
diceGameName string
scratchGameName string
blackjackGameName string
slotsGameName string
serverConfig ServerConfig
)
type Timestamp struct {
API string `json:"api"`
V string `json:"v"`
Ret []string `json:"ret"`
Data struct {
T string `json:"t"`
} `json:"data"`
}
func Init() {
if IS_TEST {
roundBasedGames = [6]string{"godappbaccar", "godappcbacca", "godapproulet", "godappredbla", "godappbullfi", "godappquick3"}
diceGameName = "godappdice12"
scratchGameName = "godappscratc"
blackjackGameName = "godappblackj"
slotsGameName = "godappslots1"
serverConfig = ServerConfig{
"https://api-kylin.eoslaomao.com",
"<KEY>",
"codemonkeyte",
"<KEY>"}
} else {
serverConfig = ServerConfig{}
serverConfig.node = cf.C.Node
serverConfig.revealKey = cf.C.RevealKey
serverConfig.actorAccountName = cf.C.ActorAccountName
serverConfig.actorAccountKey = cf.C.ActorAccountKey
roundBasedGames = [6]string{"baccarat.e", "dappbaccarat", "roulette.e", "warofstar.e", "bairenniuniu", ""}
diceGameName = "godice.e"
scratchGameName = "scratchers55"
slotsGameName = ""
blackjackGameName = "blackjack.e"
}
}
func RevealRobot() {
services := createServices(serverConfig)
fmt.Println("RevealRobot", serverConfig)
networkOffset := GetNetWorkOffset()
//fmt.Println("networkOffset:",networkOffset)
for i := range roundBasedGames {
fmt.Println("qqqq")
robot := RoundBasedRobot{roundBasedGames[i], 0, networkOffset,
RoundStatus{0, 0, 0, ""},
&serverConfig,
&services,
}
//start
robot.run()
}
// dice := DiceRobot{diceGameName, &serverConfig, &services}
// dice.run()
// scratch := ScratchRobot{scratchGameName, &serverConfig, &services}
// scratch.run()
// blackjack := BlackjackRobot{blackjackGameName, &serverConfig, &services}
// blackjack.run()
// slots := SlotsRobot{slotsGameName, &serverConfig, &services}
// slots.run()
select {}
}
func GetNetWorkOffset() int64 {
timeResp, err := http.Get(cf.C.TimeUrl)
if err != nil {
fmt.Println("err", err)
}
s, err := ioutil.ReadAll(timeResp.Body)
if err != nil {
fmt.Println(err)
}
var data Timestamp
if err != nil {
fmt.Println(err)
}
err = json.Unmarshal([]byte(s), &data)
var value = (stringhandler.StringToInt(data.Data.T) / 1000) - time.Now().UTC().Unix()
fmt.Println("===========网络延时===========", value)
return value
}
func createServices(config ServerConfig) Services {
digestSigner := *eos.NewKeyBag()
_ = digestSigner.ImportPrivateKey(context.Background(), config.revealKey)
api := eos.New(config.node)
bag := eos.NewKeyBag()
_ = bag.Add(config.actorAccountKey)
key, _ := bag.AvailableKeys(context.Background())
api.SetCustomGetRequiredKeys(func(ctx context.Context, tx *eos.Transaction) (keys []ecc.PublicKey, e error) {
return key, nil
})
api.SetSigner(bag)
txOps, _ := getTxOps(api)
return Services{*api, txOps, digestSigner, 0}
}
func getTxOps(api *eos.API) (eos.TxOptions, error) {
opts := *&eos.TxOptions{}
err := opts.FillFromChain(context.Background(), api)
return opts, err
}
<file_sep>/main.go
package main
import (
"./config"
"./robot"
"./utils/env"
"./utils/log"
"flag"
"fmt"
"io/ioutil"
)
var err error
func main() {
//init log
logger, err := log.NewLogger(env.LogPath, "debug")
env.ErrExit(err)
log.SetDefault(logger)
// init config
filename := flag.String("f", "config.json", "[file name] default: config.json")
flag.Parse()
fmt.Println("config filename:", *filename)
data, err := ioutil.ReadFile(*filename)
if err != nil {
fmt.Println("initconfig failed! %v", err)
}
//set data
env.ErrExit(config.InitConfig(data))
revealrobot.Init()
//robot run
revealrobot.RevealRobot()
}
<file_sep>/utils/bet/bet.go
package bet
type Playtable struct {
Rows []struct {
ID int `json:"id"`
EndTime int `json:"end_time"`
PlayerCards []int `json:"player_cards"`
BankerCards []int `json:"banker_cards"`
Symbol string `json:"symbol"`
Status int `json:"status"`
LargestWinner string `json:"largest_winner"`
LargestWinAmount string `json:"largest_win_amount"`
Seed string `json:"seed"`
} `json:"rows"`
More bool `json:"more"`
}
type Bets struct {
Rows []struct {
ID int `json:"id"`
GameID int `json:"game_id"`
Player string `json:"player"`
Referer string `json:"referer"`
Bet string `json:"bet"`
BetType int `json:"bet_type"`
} `json:"rows"`
More bool `json:"more"`
}
type PlayerBet struct {
ID int `json:"id"`
GameID int `json:"game_id"`
Player string `json:"player"`
Referer string `json:"referer"`
Bet string `json:"bet"`
BetType int `json:"bet_type"`
}
type PlayerAmount struct {
Player string `json:"player"`
Bet string `json:"bet"`
}
type BetsAmount struct {
Rows []struct {
Player string `json:"player"`
Bet string `json:"bet"`
} `json:"rows"`
More bool `json:"more"`
}
<file_sep>/utils/log/log.go
package log
import (
"fmt"
"log"
"os"
"path"
"time"
"../env"
"runtime"
"github.com/natefinch/lumberjack"
)
const (
EMERG = iota
ALERT
CRIT
ERR
WARN
NOTICE
INFO
DEBUG
)
var LEVELS = map[string]uint{
"emerg": EMERG,
"alert": ALERT,
"crit": CRIT,
"err": ERR,
"warn": WARN,
"notice": NOTICE,
"info": INFO,
"debug": DEBUG,
}
type Logger struct {
path string
log *log.Logger
rlog lumberjack.Logger
rollingFile bool
lastRotateTime time.Time
level uint
pid []interface{}
}
func NewLogger(path string, level string) (*Logger, error) {
tlog := new(Logger)
tlog.path = path
tlog.lastRotateTime = time.Now()
tlog.level = LEVELS[level]
tlog.pid = []interface{}{env.Pid}
tlog.rlog.Filename = path
tlog.rlog.MaxSize = 0x1000 * 2 // automatic rolling file on it increment than 2GB
tlog.rlog.LocalTime = true
l := log.New(&tlog.rlog, "", log.LstdFlags|log.Lshortfile)
tlog.log = l
return tlog, nil
}
func (tlog *Logger) checkRotate() {
if !tlog.rollingFile {
return
}
n := time.Now()
if tlog.lastRotateTime.Year() != n.Year() ||
tlog.lastRotateTime.Month() != n.Month() ||
tlog.lastRotateTime.Day() != n.Day() {
tlog.rlog.Rotate()
tlog.lastRotateTime = n
}
}
func (tlog *Logger) SetDailyFile() {
tlog.rollingFile = true
}
func (tlog *Logger) Emerg(format string, v ...interface{}) {
tlog.checkRotate()
if tlog.level < EMERG {
return
}
tlog.log.Printf("[EMERG] #%d "+format, append(tlog.pid, v...)...)
}
func (tlog *Logger) Alert(format string, v ...interface{}) {
tlog.checkRotate()
if tlog.level < ALERT {
return
}
tlog.log.Printf("[ALERT] #%d "+format, append(tlog.pid, v...)...)
}
func (tlog *Logger) Crit(format string, v ...interface{}) {
tlog.checkRotate()
if tlog.level < CRIT {
return
}
tlog.log.Printf("[CRIT] #%d "+format, append(tlog.pid, v...)...)
}
func (tlog *Logger) Err(format string, v ...interface{}) {
tlog.checkRotate()
if tlog.level < ERR {
return
}
tlog.log.Printf("[ERROR] #%d "+format, append(tlog.pid, v...)...)
}
func (tlog *Logger) Warn(format string, v ...interface{}) {
tlog.checkRotate()
if tlog.level < WARN {
return
}
tlog.log.Printf("[WARN] #%d "+format, append(tlog.pid, v...)...)
}
func (tlog *Logger) Notice(format string, v ...interface{}) {
tlog.checkRotate()
if tlog.level < NOTICE {
return
}
tlog.log.Printf("[NOTICE] #%d "+format, append(tlog.pid, v...)...)
}
func (tlog *Logger) Info(format string, v ...interface{}) {
tlog.checkRotate()
if tlog.level < INFO {
return
}
tlog.log.Printf("[INFO] #%d "+format, append(tlog.pid, v...)...)
}
func (tlog *Logger) Debug(format string, v ...interface{}) {
tlog.checkRotate()
if tlog.level < DEBUG {
return
}
funcName, file, line, ok := runtime.Caller(2)
if ok {
//fmt.Println("func name: " + runtime.FuncForPC(funcName).Name())
//fmt.Printf("file: %s, line: %d\n", file, line)
_, filename := path.Split(file)
_, funcshort := path.Split(runtime.FuncForPC(funcName).Name())
sline := fmt.Sprintf("%s:%s %d", filename, funcshort, line)
tlog.log.Printf("[DEBUG] "+sline+" #%d "+format, append(tlog.pid, v...)...)
} else {
tlog.log.Printf("[DEBUG] #%d "+format, append(tlog.pid, v...)...)
}
}
var _logger *Logger
func GetDefault() *Logger {
return _logger
}
func SetDefault(l *Logger) {
_logger = l
}
func Stdout() {
l := log.New(os.Stdout, "", log.LstdFlags)
tlog := new(Logger)
tlog.log = l
tlog.level = DEBUG
tlog.pid = []interface{}{env.Pid}
SetDefault(tlog)
}
func Emerg(format string, v ...interface{}) {
_logger.Emerg(format, v...)
}
func Alert(format string, v ...interface{}) {
_logger.Alert(format, v...)
}
func Crit(format string, v ...interface{}) {
_logger.Crit(format, v...)
}
func Err(format string, v ...interface{}) {
_logger.Err(format, v...)
}
func Warn(format string, v ...interface{}) {
_logger.Warn(format, v...)
}
func Notice(format string, v ...interface{}) {
_logger.Notice(format, v...)
}
func Info(format string, v ...interface{}) {
_logger.Info(format, v...)
}
func Debug(format string, v ...interface{}) {
_logger.Debug(format, v...)
}
func RawLogger() *log.Logger {
return _logger.log
}
<file_sep>/config/config.go
package config
import (
"encoding/json"
)
//固定地址保存在数据库中
type Config struct {
Debug bool `json:"debug"`
RemoteAddress string `json:"remote_address"`
RedisHost string `json:"redis_host"`
RedisPass string `json:"redis_pass"`
Crypto string `json:"crypto"`
Use string `json:"Use"`
Port string `json:"port"`
Allow string `json:"allow"`
RobotAccount string `json:"robot_account"`
RobotOpenAccount string `json:"robot_open_account"`
RobotPrivate string `json:"robot_private"`
RobotOpenPrivate string `json:"robot_open_private"`
ContracAccount string `json:"contrac_account"`
MysqlConn string `json:"mysql_conn"`
Arena int `json:"arena"`
Tablename string `json:"tablename"`
EosPermission string `json:"eos_permission"`
EosTablename string `json:"eos_tablename"`
Testnode string `json:"testnode"`
TestrevealKey string `json:"testrevealKey"`
TestactorAccountName string `json:"testactorAccountName"`
TestactorAccountKey string `json:"testactorAccountKey"`
Node string `json:"node"`
RevealKey string `json:"revealKey"`
ActorAccountName string `json:"actorAccountName"`
ActorAccountKey string `json:"actorAccountKey"`
TimeUrl string `json:timeUrl`
}
var (
C *Config
)
func InitConfig(data []byte) error {
C = new(Config)
return json.Unmarshal(data, &C)
}
func Port() string {
if C.Port == "" {
return ":9879"
} else {
return C.Port
}
}
func Allow() string {
if C.Allow == "" {
return "*"
} else {
return C.Allow
}
}
<file_sep>/robot/revealRobotBase.go
package revealrobot
import (
"fmt"
"github.com/eoscanada/eos-go"
"io/ioutil"
"net/http"
"strings"
)
type ServerConfig struct {
node string
revealKey string
actorAccountName string
actorAccountKey string
}
type Services struct {
api eos.API
txOpts eos.TxOptions
digestSigner eos.KeyBag
lastRefresh int64
}
func getTableRows(node string, game string, table string) ([]byte, error) {
url := node + "/v1/chain/get_table_rows"
payload := strings.NewReader("{\n \"scope\": \"" + game + "\",\n \"code\": \"" + game + "\",\n " +
"\"table\": \"" + table + "\",\n \"json\": \"true\",\n \"limit\": 1000\n}")
req, err := http.NewRequest("POST", url, payload)
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("cache-control", "no-cache")
req.Header.Add("Postman-Token", "<PASSWORD>")
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
return ioutil.ReadAll(res.Body)
}
func (s *Services) refresh(currentTime int64) {
if currentTime-s.lastRefresh > 60 {
s.lastRefresh = currentTime
fmt.Println("==========================================更新网络配置==================================================")
opts, err := getTxOps(&s.api)
if err == nil {
s.txOpts = opts
}
}
}
<file_sep>/utils/stringhandler/stringhandler.go
package stringhandler
import (
"fmt"
"io/ioutil"
"math"
"net/http"
"strconv"
)
func StringToInt(str string) (int64) {
int64, err := strconv.ParseInt(str, 10, 64)
if err==nil {
fmt.Println(err)
}
return int64
}
func Round(x float64)(int64){
return int64(math.Floor(x + 0/5))
}
//fmt.Println(math.Ceil(x)) // 2 向上取整
//fmt.Println(math.Floor(x)) // 1 向下取整
func FloatToInt(x float64)(int64) {
return int64(math.Floor(x))
}
func GetNetWorkTime() (string, error) {
timeresp, err := http.Get("http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp")
fmt.Println("err:", err)
if err != nil {
return "false", err
}
if timeresp == nil {
return "false", err
}
s, err := ioutil.ReadAll(timeresp.Body)
if err != nil {
fmt.Println(err)
}
defer timeresp.Body.Close()
return string(s), nil
}
<file_sep>/utils/crontool/crontool.go
package crontool
import "github.com/robfig/cron"
func NewWithSecond() *cron.Cron {
secondParser := cron.NewParser(cron.Second | cron.Minute |
cron.Hour | cron.Dom | cron.Month | cron.DowOptional | cron.Descriptor)
return cron.New(cron.WithParser(secondParser), cron.WithChain())
}
<file_sep>/robot/slotsRobot.go
package revealrobot
import (
"context"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/eoscanada/eos-go"
"github.com/eoscanada/eos-go/ecc"
"strconv"
)
type SlotsActiveGameTable struct {
Rows []struct {
Id eos.Uint64 `json:"id"`
Player eos.Name `json:"player"`
Referer eos.Name `json:"referer"`
Price eos.Asset `json:"price"`
Result eos.Uint64 `json:"result"`
Seed eos.Checksum256 `json:"seed"`
Time string `json:"time"`
} `json:"rows"`
More bool `json:"more"`
}
type SlotsRevealData struct {
BetId eos.Uint64 `json:"game_id"`
Signature ecc.Signature `json:"signature"`
}
type SlotsRobot struct {
name string
config *ServerConfig
services *Services
}
func (r *SlotsRobot) run() {
c := NewWithSecond()
spec := "*/1 * * * * ?"
_, _ = c.AddFunc(spec, func() {
body, err := getTableRows(r.config.node, r.name, "activegame")
fmt.Println("取得赌注数据: ", "body")
if err == nil {
var list SlotsActiveGameTable
err = json.Unmarshal(body, &list)
if err == nil {
for _, row := range list.Rows {
if row.Result == 65535 {
fmt.Println("=======================老虎机开奖 " + strconv.Itoa(int(row.Id)) + "=============================")
r.pushAction(row.Id, row.Seed)
}
}
}
}
})
c.Start()
}
func (r *SlotsRobot) pushAction(gameId eos.Uint64, seed eos.Checksum256) {
keys, err := r.services.digestSigner.AvailableKeys(context.Background())
digest, err := hex.DecodeString(seed.String())
sig, err := r.services.digestSigner.SignDigest(digest, keys[0])
data := SlotsRevealData{gameId, sig}
action := eos.Action{
Account: eos.AccountName(r.name),
Name: "reveal",
Authorization: []eos.PermissionLevel{
{Actor: eos.AccountName(r.config.actorAccountName), Permission: eos.PN("active")}, //owner active
},
ActionData: eos.NewActionData(&data),
}
tx := eos.NewTransaction([]*eos.Action{&action}, &r.services.txOpts)
signedTx, packedTx, err := r.services.api.SignTransaction(context.Background(), tx, r.services.txOpts.ChainID, eos.CompressionNone)
if err == nil {
_, err = json.MarshalIndent(signedTx, "", "")
if err == nil {
_, err = json.Marshal(packedTx)
if err == nil {
response, err := r.services.api.PushTransaction(context.Background(), packedTx)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(response)
}
}
}
}
}
func (r *SlotsRobot) run1() {
fmt.Println(r.config.node)
body, err := getTableRows(r.config.node, r.name, "activegame")
if err == nil {
var list SlotsActiveGameTable
err = json.Unmarshal(body, &list)
if err == nil {
for _, row := range list.Rows {
if row.Result == 65535 {
fmt.Println("=======================老虎机开奖 " + strconv.Itoa(int(row.Id)) + "=============================")
r.pushAction(row.Id, row.Seed)
}
}
}
}
}
<file_sep>/robot/roundBasedRobot.go
package revealrobot
import (
"../utils/bet"
"context"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/eoscanada/eos-go"
"github.com/eoscanada/eos-go/ecc"
"github.com/robfig/cron"
"time"
)
type RoundStatus struct {
roundId int
status int
endTime int64
seed string
}
type RevealData struct {
GameId eos.Uint64 `json:"game_id"`
Signature ecc.Signature `json:"signature"`
}
type RoundBasedRobot struct {
name string
count int
networkOffset int64
status RoundStatus
config *ServerConfig
services *Services
}
func (r *RoundBasedRobot) run() {
c := NewWithSecond()
spec := "*/1 * * * * ?"
_, err := c.AddFunc(spec, func() {
var currentTime = time.Now().UTC().Unix() + r.networkOffset
if currentTime >= r.status.endTime {
r.status = r.getStatus()
}
fmt.Println("status", r.status)
//下注
if r.status.status == 1 {
//获取下注时间
return
}
if r.status.status == 2 {
//获取下注时间
r.bettime(currentTime)
}
r.services.refresh(currentTime)
})
if err != nil {
fmt.Println(err)
}
c.Start()
}
func (r *RoundBasedRobot) bettime(currentTime int64) {
r.count++
var openTime = r.status.endTime - currentTime
//网路赌注
if openTime != 0 && openTime%10 == 0 {
fmt.Println("===== ", r.name, " 本轮游戏结束剩余 ", openTime, ",网络时间:", currentTime, ",结束时间", r.status.endTime, "======")
}
if openTime <= 0 && openTime%2 == 0 {
fmt.Println("==========================================", r.name, " 游戏开奖=======================================================", r.count)
r.makeActions()
}
}
func (r *RoundBasedRobot) makeActions() {
res, err := r.pushAction()
if err != nil {
fmt.Println(err)
// 有时候开奖, 重试一次
res, err = r.pushAction()
}
if err != nil {
fmt.Println(err)
} else {
fmt.Println(res)
}
}
func (r *RoundBasedRobot) pushAction() (string, error) {
keys, err := r.services.digestSigner.AvailableKeys(context.Background())
digest, err := hex.DecodeString(r.status.seed)
sig, err := r.services.digestSigner.SignDigest(digest, keys[0])
data := RevealData{eos.Uint64(r.status.roundId), sig}
action := eos.Action{
Account: eos.AccountName(r.name),
Name: "reveal",
Authorization: []eos.PermissionLevel{
{Actor: eos.AccountName(r.config.actorAccountName), Permission: eos.PN("active")}, //owner active
},
ActionData: eos.NewActionData(&data),
}
tx := eos.NewTransaction([]*eos.Action{&action}, &r.services.txOpts)
fmt.Println(tx)
signedTx, packedTx, err := r.services.api.SignTransaction(context.Background(), tx, r.services.txOpts.ChainID, eos.CompressionNone)
if err != nil {
return "", err
}
_, err = json.MarshalIndent(signedTx, "", "")
if err != nil {
return "", err
}
_, err = json.Marshal(packedTx)
response, err := r.services.api.PushTransaction(context.Background(), packedTx)
if err != nil {
fmt.Println(err)
return "", err
}
fmt.Println("response", response)
return "", nil
}
func (r *RoundBasedRobot) getStatus() RoundStatus {
body, err := getTableRows(r.config.node, r.name, "activegame")
if err == nil {
var list bet.Playtable
err = json.Unmarshal(body, &list)
if err == nil {
for _, row := range list.Rows {
return RoundStatus{row.ID, row.Status, int64(row.EndTime), row.Seed}
}
}
}
return RoundStatus{0, 0, 0, ""}
}
func NewWithSecond() *cron.Cron {
secondParser := cron.NewParser(cron.Second | cron.Minute |
cron.Hour | cron.Dom | cron.Month | cron.DowOptional | cron.Descriptor)
return cron.New(cron.WithParser(secondParser), cron.WithChain())
}
<file_sep>/README.md
# revealrobot
开奖机器人 用于所有机器人的开奖
<file_sep>/robot/diceRobot.go
package revealrobot
import (
"context"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/eoscanada/eos-go"
"github.com/eoscanada/eos-go/ecc"
)
type ActiveBetsTable struct {
Rows []struct {
Id eos.Uint64 `json:"id"`
Player eos.Name `json:"player"`
Referer eos.Name `json:"referer"`
BetAmount eos.Uint64 `json:"bet_number"`
Asset eos.Asset `json:"bet_asset"`
Seed eos.Checksum256 `json:"seed"`
Time string `json:"time"`
} `json:"rows"`
More bool `json:"more"`
}
type DiceRevealData struct {
BetId eos.Uint64 `json:"bet_id"`
Signature ecc.Signature `json:"signature"`
}
type DiceRobot struct {
name string
config *ServerConfig
services *Services
}
func (r *DiceRobot) run() {
c := NewWithSecond()
spec := "*/2 * * * * ?"
_, err := c.AddFunc(spec, func() {
fmt.Println("本轮")
body, err := getTableRows(r.config.node, r.name, "activebets")
if err == nil {
var list ActiveBetsTable
err = json.Unmarshal(body, &list)
if err == nil {
for _, row := range list.Rows {
fmt.Println("=======================骰子开奖 " + string(row.Id) + "=============================")
r.pushAction(row.Id, row.Seed)
}
}
}
})
if err != nil {
fmt.Println(err)
}
c.Start()
select {}
}
func (r *DiceRobot) pushAction(betId eos.Uint64, seed eos.Checksum256) {
keys, err := r.services.digestSigner.AvailableKeys(context.Background())
digest, err := hex.DecodeString(seed.String())
sig, err := r.services.digestSigner.SignDigest(digest, keys[0])
data := DiceRevealData{betId, sig}
action := eos.Action{
Account: eos.AccountName(r.name),
Name: "reveal",
Authorization: []eos.PermissionLevel{
{Actor: eos.AccountName(r.config.actorAccountName), Permission: eos.PN("active")}, //owner active
},
ActionData: eos.NewActionData(&data),
}
tx := eos.NewTransaction([]*eos.Action{&action}, &r.services.txOpts)
signedTx, packedTx, err := r.services.api.SignTransaction(context.Background(), tx, r.services.txOpts.ChainID, eos.CompressionNone)
if err == nil {
_, err = json.MarshalIndent(signedTx, "", "")
if err == nil {
_, err = json.Marshal(packedTx)
if err == nil {
response, err := r.services.api.PushTransaction(context.Background(), packedTx)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(response)
}
}
}
}
}
|
1f87a922350205d072c5e586d92751bc2e011e58
|
[
"Markdown",
"Go"
] | 12 |
Go
|
mason0510/revealrobot
|
9ab2c491158f6ec8a6232c46532e692848d34e5d
|
cfc3796270fdf3d544d9ce17d6351529ab491b49
|
refs/heads/master
|
<repo_name>ArturKp/volleyball-2017-points<file_sep>/app/Events/ScoresUpdated.php
<?php
namespace App\Events;
use App\Models\Team;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;
class ScoresUpdated implements ShouldBroadcast
{
use InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct()
{
//
}
public function broadcastWith()
{
return Team::all()->toArray();
}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn()
{
return ['scores'];
}
}
<file_sep>/app/Http/Controllers/TeamController.php
<?php
namespace App\Http\Controllers;
use DB;
use App\Models\Team;
use Illuminate\Http\Request;
class TeamController extends Controller
{
public function __construct()
{
$this->middleware('admin', ['except' => ['index', 'indexCsv']]);
}
public function index()
{
return response()->json(Team::all());
}
public function indexCsv()
{
$teams = Team::all();
$first = $teams->first();
$second = $teams[1];
return response()->csv([
['team1_name', 'team1_score', 'team1_minimatch_score', 'team1_wins', 'team2_name', 'team2_score', 'team2_minimatch_score', 'team2_wins'],
[$first->name, $first->score, $first->minimatch_score, $first->wins, $second->name, $second->score, $second->minimatch_score, $second->wins],
]);
return response()->csv(Team::all());
}
public function add($teamId)
{
$updated = DB::table('team')
->where('id', '=', $teamId)
->where('score', '<', '2017')
->update([
'score' => DB::raw('score + 1'),
'minimatch_score' => DB::raw('minimatch_score + 1')
]);
if($updated === 0) { throw new \Exception("Nothing updated!"); }
event(new \App\Events\ScoresUpdated());
return response()->json(Team::all());
}
// Only remove, if some minimatch is active
public function remove($teamId)
{
$updated = DB::table('team')
->where('id', '=', $teamId)
->where('minimatch_score', '>', '0')
->update([
'score' => DB::raw('GREATEST(score - 1, 0)'),
'minimatch_score' => DB::raw('GREATEST(minimatch_score - 1, 0)')
]);
if($updated === 0) { throw new \Exception("Nothing updated!"); }
event(new \App\Events\ScoresUpdated());
return response()->json(Team::all());
}
public function win($teamId)
{
DB::transaction(function() use ($teamId) {
$updated = DB::table('team')
->where('id', '=', $teamId)
->where('minimatch_score', '>', '0')
->update([
'wins' => DB::raw('wins+1'),
'minimatch_score' => 0
]);
if($updated === 0) { throw new \Exception("Nothing updated!"); }
DB::table('team')
->where('id', '!=', $teamId)
->where('minimatch_score', '>', '0')
->update([
'minimatch_score' => 0
]);
});
event(new \App\Events\ScoresUpdated());
return response()->json(Team::all());
}
// Make changes to all fields
public function update($teamId, Request $request)
{
Team::findOrFail($teamId)->update($request->all());
event(new \App\Events\ScoresUpdated());
return response()->json(Team::all());
}
}
<file_sep>/resources/assets/js/bootstrap.js
window._ = require('lodash');
/**
* We'll load jQuery and the Bootstrap jQuery plugin which provides support
* for JavaScript based Bootstrap features such as modals and tabs. This
* code may be modified to fit the specific needs of your application.
*/
window.$ = window.jQuery = require('jquery');
require('bootstrap-sass');
/**
* Vue is a modern JavaScript library for building interactive web interfaces
* using reactive data binding and reusable components. Vue's API is clean
* and simple, leaving you to focus on building your next great project.
*/
window.Vue = require('vue');
require('vue-resource');
Vue.config.devtools = false;
require('jquery-textfill/source/jquery.textfill.min.js');
// Toastr
window.toastr = require('toastr/build/toastr.min.js');
window.toastr.options = {
"closeButton": false,
"debug": false,
"newestOnTop": false,
"progressBar": false,
"positionClass": "toast-bottom-center",
"onclick": null,
"showDuration": "100",
"hideDuration": "100",
"timeOut": "1000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
}
window.io = require('socket.io-client');
/**
* We'll register a HTTP interceptor to attach the "CSRF" header to each of
* the outgoing requests issued by this application. The CSRF middleware
* included with Laravel will automatically verify the header's value.
*/
Vue.http.interceptors.push((request, next) => {
request.headers.set('X-CSRF-TOKEN', Laravel.csrfToken);
next();
});
<file_sep>/resources/assets/js/edit.js
(function(window){
'use strict';
jQuery(window).ready(onReady);
function onReady() {
getInitialData();
}
function getInitialData() {
Vue.http.get('/team').then(function(response) { return response.body; }).then(setInitialValues);
}
function setInitialValues(data) {
for (var i = 0; i < data.length; i++) {
var team = data[i]
jQuery('#team' + team.id + '-name').val(team.name)
jQuery('#team' + team.id + '-score').val(team.score)
jQuery('#team' + team.id + '-minimatch-score').val(team.minimatch_score)
jQuery('#team' + team.id + '-wins').val(team.wins)
}
}
function update() {
Vue.http.put('/team/1', {
name: jQuery('#team1-name').val(),
score: jQuery('#team1-score').val(),
minimatch_score: jQuery('#team1-minimatch-score').val(),
wins: jQuery('#team1-wins').val(),
}).then(onUpdateSuccess, onUpdateFailure);
Vue.http.put('/team/2', {
name: jQuery('#team2-name').val(),
score: jQuery('#team2-score').val(),
minimatch_score: jQuery('#team2-minimatch-score').val(),
wins: jQuery('#team2-wins').val(),
}).then(onUpdateSuccess, onUpdateFailure);
}
function onUpdateSuccess() {
toastr.success('Updated');
location.href = location.href;
}
function onUpdateFailure() { toastr.error('Failed!'); }
window.edit = {
update: update
};
})(window);<file_sep>/app/Models/BaseModel.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class BaseModel extends Model {
public function csvSerialize()
{
return $this->toArray();
}
}<file_sep>/app/Models/Team.php
<?php
namespace App\Models;
use App\Models\BaseModel;
class Team extends BaseModel
{
protected $table = 'team';
public $timestamps = false;
// Everything is fillable
protected $guarded = [null];
}
<file_sep>/app/Facades/Auth.php
<?php
namespace App\Facades;
use Illuminate\Support\Facades\Auth as LaravelAuth;
class Auth extends LaravelAuth {
public static function isAdmin()
{
return parent::user()->isAdmin();
}
}<file_sep>/routes/web.php
<?php
use Illuminate\Support\Facades\Redis;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/
header("Access-Control-Allow-Origin: http://volley.localhost");
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
Auth::routes();
Route::group(['middleware' => 'auth'], function() {
Route::get('/', function() { return view('home'); });
Route::get('/edit', function() { return view('edit'); });
Route::get('/dashboard', function() { return view('dashboard'); });
});
Route::get('/scoreboard', function() { return view('scoreboard'); });
Route::get('team.csv', 'TeamController@indexCsv');
Route::resource('team', 'TeamController', ['only' => ['update', 'index']]);
Route::post('team/{team_id}/add', 'TeamController@add');
Route::post('team/{team_id}/remove', 'TeamController@remove');
Route::post('team/{team_id}/win', 'TeamController@win');
<file_sep>/resources/assets/js/scoreboard.js
(function(window) {
'use strict';
jQuery(window).ready(onReady);
jQuery(window).resize(adjustFontSizes);
function onReady() {
adjustFontSizes();
getInitialData();
openSocket();
}
function adjustFontSizes() {
// https://github.com/jquery-textfill/jquery-textfill
jQuery('body[route^="scoreboard"] .score-total').textfill({
maxFontPixels: 180,
widthOnly: true
});
jQuery('body[route^="scoreboard"] .team-name').textfill({
maxFontPixels: 120,
widthOnly: true
});
}
function openSocket() {
var socket = io(':3000', {
'reconnection': true,
'reconnectionDelay': 500,
'reconnectionDelayMax' : 10 * 1000,
'reconnectionAttempts': Infinity
});
socket.on("scores:App\\Events\\ScoresUpdated", setScores);
}
function getInitialData() {
Vue.http.get('/team').then(function(response) { return response.body; }).then(setScores);
}
function setScores(data) {
for (var i = 0; i < data.length; i++) {
setTeamScores(data[i]);
}
}
function getNameEl(id) { return jQuery('#team' + id + '-name'); }
function getScoreEl(id) { return jQuery('#team' + id + '-score'); }
function getMinimatchScoreEl(id) { return jQuery('#team' + id + '-minimatch-score'); }
function getWinsEl(id) { return jQuery('#team' + id + '-wins'); }
function setTeamScores(team) {
updateElementContent(getNameEl(team.id), team.name);
updateElementContent(getScoreEl(team.id), team.score);
updateElementContent(getMinimatchScoreEl(team.id), team.minimatch_score);
updateElementContent(getWinsEl(team.id), team.wins);
}
function updateElementContent(element, data) {
if (element && element.html() != data) {
element.fadeOut(100, function onComplete() {
element.html(data).fadeIn(100, function onComplete() {
adjustFontSizes();
});
});
}
}
function add(id) {
Vue.http.post('/team/' + id + '/add').then(onAddSuccess, onAddFailure);
}
function onAddSuccess(data) {
toastr.success('+1');
setScores(data.body);
}
function onAddFailure() { toastr.error('Failed!'); }
function remove(id) {
Vue.http.post('/team/' + id + '/remove').then(onRemoveSuccess, onRemoveFailure);
}
function onRemoveSuccess(data) {
toastr.success('-1');
setScores(data.body);
}
function onRemoveFailure() { toastr.error('Failed!'); }
function win(id) {
var team_name = jQuery('#team' + id + "-name").html();
if( ! confirm('Confirm that winner is ' + team_name.toUpperCase() + " and finish this minimatch?")) {
return;
}
Vue.http.post('/team/' + id + '/win').then(onWinSuccess, onWinFailure);
}
function onWinSuccess(data) {
toastr.success('Saved');
setScores(data.body);
}
function onWinFailure() { toastr.error('Failed!'); }
function changeTeams() {
jQuery('#team-1-wrapper').toggleClass('pull-right');
}
window.scoreboard = {
add: add,
remove: remove,
win: win,
changeTeams: changeTeams
};
})(window);
|
95af70297799ebbaf6ed6317f88014093a04d22d
|
[
"JavaScript",
"PHP"
] | 9 |
PHP
|
ArturKp/volleyball-2017-points
|
50c80b1dad9482f3a76e89344edd25546e76f40e
|
9b7f897d62f18dc7636cfe9ba54e85fdb8902508
|
refs/heads/master
|
<repo_name>gkawamoto/floconil<file_sep>/index.js
var fs = require('fs');
var path = require('path');
var util = require('util');
var vm = require('vm');
var flogger = require('flogger');
var package_json = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json')).toString());
var ERR_NOT_FOUND = 'ERR_NOT_FOUND';
var ERR_FORBIDDEN = 'ERR_FORBIDDEN';
function now ()
{
return new Date().getTime();
};
function tick ()
{
return now() - start;
};
function build_error (err)
{
return new Error(err);
}
module.exports = function (options)
{
options = options||{};
options.path = options.path || 'services';
if (!path.isAbsolute(options.path))
options.path = path.resolve(path.dirname(require.main.filename), options.path);
var scripts = {};
var resolved_paths = {};
var global_context = null;
function report_error (req, res, next, err)
{
flogger.error(err.stack);
if (impl.debug)
res.status(500).send(err.stack);
else
res.status(500).send(err.message);
}
function resolve (filepath)
{
if (resolved_paths[filepath])
return resolved_paths[filepath];
var result = null;
//if (index)
//result = path.resolve(path.join(options.path, path.dirname(filepath), 'index.js'));
//else
result = path.resolve(path.join(options.path, filepath)) + '.js';
//if (result.substr(-3) != '.js')
//result += '.js';
return resolved_paths[filepath] = result;
};
function compile (req_path, req, res, next, callback)
{
var original_path = req_path;
req_path = req_path.split('/');
var is_global = req_path[req_path.length-1] == 'global';
if (!is_global)
var method = req_path.pop();
else
var method = '__global__';
flogger.trace('Compiling %s', original_path);
var file = resolve(req_path.join('/'));
var script = scripts[req_path] = {};
flogger.trace('Checking whether %s exists', file);
fs.exists(file, function fs_exists (exists)
{
flogger.trace('Exists? %s', exists ? 'yes' : 'no');
if (!exists)
{
if (is_global)
return callback();
else
return callback(ERR_NOT_FOUND); /*compile(req_path, req, res, next, function (err)
{
if (err)
return report_error(req, res, next, err);
callback(req_path, req, res, next, callback);
});*/
}
flogger.trace('Getting file attributes for %s', file);
fs.stat(file, function fs_stat (err, stats)
{
if (err)
return error(req, res, next, new Error(err));
var source = fs.readFileSync(file).toString();
if (is_global) source = util.format('public.__global__ = function __global__ () { %s \n};', source);
source = util.format(
[
'function ___execute___ (method)',
'{',
'var public = {};',
'(function () { %s \n})();',
'if (public[method] === undefined)',
'throw new Error("No such method as " + method);',
'return public[method]();',
'};'
].join(''),
source
);
flogger.trace('Compiling for %s:\n%s', req_path, source);
if (impl.save_compiled)
fs.writeFileSync(util.format('%s.built', file), source);
script['source'] = util.format('(function(){ %s return ___execute___("%s");})()', source, method);
script['ctime'] = stats.ctime.getTime();
script['filename'] = file;
try
{
script.compiled = new vm.Script(script.source, {filename:script.filename, displayErrors:true});
}
catch (e)
{
report_error(req, res, next, e);
return;
}
scripts[original_path] = script;
callback();
});
});
};
function check_updates (req, res, next, req_path, file, callback)
{
if (options.trust_compiled)
return callback();
if (file.substr(0, options.path.length) != options.path)
return callback(ERR_FORBIDDEN);
fs.stat(file, function (err, stats)
{
if (err)
return callback(err);
///return internal_server_error(req, res, next, err);
if (scripts[req_path].ctime < stats.ctime.getTime() || options.always_compile)
return compile(req_path, req, res, next, callback);
callback();
});
};
function run_global (req, res, next, callback)
{
var global_path = req.path.split('/');
global_path.pop(); global_path.pop();
global_path = global_path.join('/');
if (scripts[global_path])
return run_script(req, res, next, global_path, callback);
global_path = path.join(path.dirname(path.dirname(req.path)), 'global');
fs.exists(resolve(global_path), function (exists)
{
if (!exists)
return callback();
if (!scripts[global_path])
{
return compile(global_path, req, res, next, function (err)
{
if (err == null || err == ERR_NOT_FOUND)
return run_global(req, res, next, callback);
report_error(req, res, next, build_error(err));
});
};
run_script(req, res, next, global_path, callback);
});
};
function create_context ()
{
var context = {
log:flogger.info.bind(flogger),
setTimeout:setTimeout,
setInterval:setInterval,
console:console,
process:process,
__application:global,
require:require,
external:impl.external
};
for (var k = 0; k < impl.includes.length; k++)
context[impl.includes[k].name] = impl.includes[k].ref;
return vm.createContext(context);
}
function run_script (req, res, next, script_path, callback)
{
var script = scripts[script_path];
check_updates(req, res, next, script_path, script.filename, function (err)
{
if (err)
return report_error(req, res, next, new Error(err));
function end (err, result)
{
callback(err, result);
}
function __error (e)
{
callback(e);
}
function __done (data)
{
end(null, data);//done_callback = callback;
}
function __result (result)
{
data = result;
}
var script = scripts[script_path];
var done_callback = null;
try
{
if (!global_context)
global_context = create_context();
global_context.result = __result;
global_context.error = __error;
global_context.done = __done;
global_context.request = req;
global_context.response = res;
global_context.script = script;
//begin();
var data = script.compiled.runInContext(global_context);
if (data !== undefined)
end(null, data);
}
catch (e)
{
__error(e);
};
});
};
function impl (req, res, next)
{
flogger.trace('Do we need to compile %s? %s', req.path, !scripts[req.path])
if (!scripts[req.path])
{
return compile(req.path, req, res, next, function (err)
{
if (err != null)
return report_error(req, res, next, build_error(err));
impl(req, res, next);
});
};
flogger.trace('running global.js first if it exists.');
run_global(req, res, next, function (err, result)
{
if (err)
{
return report_error(req, res, next, err);
};
flogger.trace('running %s now', req.path);
run_script(req, res, next, req.path, function (err, result)
{
if (err)
{
return report_error(req, res, next, err);
}
flogger.trace('everything seems good, parse the data');
var data = JSON.stringify(result);
flogger.trace('and we\'re done!');
res.send(data);
//next();
});
});
};
impl.debug = true;
impl.external = {};
impl.includes = [];
impl.setLogLevel = function (level)
{
flogger.set_level(level);
};
impl.include = function (name, ref)
{
impl.includes.push({name:name, ref:ref})
global_context = null;
};
return impl;
}
var start = now();<file_sep>/README.md
# floconil
simplest webservices
``npm install git://github.com/gkawamoto/floconil.git``
then just plug in your express
```javascript
var app = require('express')();
var floconil = require('floconil');
app.use('/', floconil({path:'webservices'}));
app.listen(5000);
```
and start coding
webservices/make/person.js
```javascript
var util = require('util');
var person = {};
person.name = request.query.name;
person.age = request.query.age;
if (!person.age)
{
error('inform age');
}
else
{
person.greeting = util.format('hello %s, how are you?', person.name);
result(person);
}
```
then test your webservice
```bash
wget 'http://localhost:5000/make/person?name=John&age=32'
```
<file_sep>/test.js
var http = require('http');
var util = require('util');
//var child_process = require('child_process');
var app = require('express')();
var floconil = require('./index.js');
var console2 = {
error: function () { console.error(util.format('[test %d] %s', tick()), util.format.apply(util, arguments)); },
log: function () { console.log(util.format('[test %d] %s', tick()), util.format.apply(util, arguments)); },
};
function now ()
{
return new Date().getTime();
};
function tick ()
{
return now() - start;
}
function main ()
{
var services = floconil({path:'examples'})
services.debug = true;
services.save_compiled = true;
//services.setLogLevel('off');
app.use('/marco', function (req, res) { res.send('POLO'); });
app.use('/die', function (req, res) { res.send('OK'); setTimeout(function () { process.exit(0); }, 50); });
app.use('/', services);
app.listen(5000, function ()
{
console2.log('listening 5000');
//return;
test([
{'url':'/hello_world/say_hello'},
{'url':'/hello_world/say_hello'},
{'url':'/hello_world/say_hello'},
{'url':'/hello_world/say_hello'},
{'url':'/hello_world/say_hello'},
{'url':'/hello_world/say_hello'},
{'url':'/timeout/teste'}
], function (err)
{
if (err)
{
console2.error(err.stack);
//process.exit(1);
return;
}
console2.log('everything seems ok!')
process.exit(0);
});
});
};
function test (urls, callback)
{
if (urls.length === 0)
return callback();
var u = urls.shift();
console2.log(util.format('testing "%s"', u.url));
var postData = '';
var options = {
hostname: 'localhost',
port: 5000,
path: u.url,
method: 'POST',
headers: {
'Connection': 'keep-alive',
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var req = http.request(options, function (res)
{
if (res.statusCode != 200)
return callback(new Error(util.format('Error %s: %s', res.statusCode, data)));
var data = '';
res.setEncoding('utf8');
res.on('data', function (chunk)
{
data += chunk;
});
res.on('end', function (err)
{
if (err)
return callback(err);
console2.log('result (%sms): %s', now() - start, data);
console2.log('----\n\n');
test(urls, callback);
});
});
req.on('error', function (err)
{
callback(err);
});
var start = now();
// write data to request body
req.end(postData);
};
var start = now();
main();<file_sep>/examples/timeout.js
public.teste = function ()
{
log('waiting 5s...');
setTimeout(function setTimeout_handler ()
{
log('ok!');
done('ok!');
}, 5000);
}<file_sep>/examples/hello_world.js
var util = require('util');
public.say_hello = function ()
{
log(1);
log(2);
return util.format('Hello, I am %s!', script.filename);
}
|
2b5c36c58d24aef7658516790ca0944c09a62699
|
[
"JavaScript",
"Markdown"
] | 5 |
JavaScript
|
gkawamoto/floconil
|
0adcb73abaa62fd938f8339f28f3f792bbe16eda
|
5cbdb9279ab75116c6faf8f61c2388d42d057fd7
|
refs/heads/master
|
<repo_name>cdecampli/SteamVR-Testing<file_sep>/EnemySpawnController.cs
using UnityEngine;
using System.Collections;
public class EnemySpawnController : MonoBehaviour {
public GameObject enemy;
public float respawnRate;
// Use this for initialization
void Start () {
InvokeRepeating("ScheduleSpawn", 1f, respawnRate);
}
// Update is called once per frame
void Update () {
}
void ScheduleSpawn()
{
Invoke("SpawnEnemy", respawnRate);
}
void SpawnEnemy()
{
GameObject newEnemy = Instantiate(enemy);
newEnemy.transform.position = this.transform.position;
newEnemy.transform.rotation = this.transform.rotation;
newEnemy.GetComponent<Rigidbody>().AddForce(newEnemy.transform.forward * 100);
}
}
<file_sep>/EnemyController.cs
using UnityEngine;
using System.Collections;
public class EnemyController : MonoBehaviour {
// Use this for initialization
void Start () {
DelayedKill();
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter(Collision col)
{
if (col.gameObject.tag == "PlayerProjectile")
{
//Destroy(this.gameObject);
}
}
void DelayedKill() { StartCoroutine(Begin()); }
IEnumerator Begin()
{
yield return new WaitForSeconds(20);
// Code here will be executed after 20 secs
Destroy(this.gameObject);
}
}
<file_sep>/HandgunProjectileSpawner.cs
using UnityEngine;
using System.Collections;
public class HandgunProjectileSpawner : MonoBehaviour {
public GameObject projectile;
public GameObject right_controller;
private SteamVR_TrackedObject right_controller_o;
private SteamVR_Controller.Device controller_right;
// Use this for initialization
void Start () {
//set up controllers for input
right_controller_o = right_controller.GetComponent<SteamVR_TrackedObject>();
}
// Update is called once per frame
void Update () {
//get input from right controller
controller_right = SteamVR_Controller.Input((int)right_controller_o.index);
//if right trigger pulled spawn projectile
if (controller_right.GetHairTriggerDown())
{
GameObject new_projectile = projectile;
Transform gun_info = right_controller.GetComponent<Transform>();
new_projectile.transform.rotation = this.transform.rotation;
new_projectile.transform.position = this.transform.position;
GameObject newest_projectile = Instantiate(new_projectile);
newest_projectile.GetComponent<Rigidbody>().AddForce(newest_projectile.transform.forward * 2000);
}
}
}
<file_sep>/VRSpaceController.cs
using UnityEngine;
using System.Collections;
public class VRSpaceController : MonoBehaviour {
//declarations for getting controller input
public float speed;
public GameObject left_controller;
public GameObject right_controller;
private SteamVR_TrackedObject left_controller_o;
private SteamVR_TrackedObject right_controller_o;
private SteamVR_Controller.Device controller_right;
private SteamVR_Controller.Device controller_left;
// Use this for initialization
void Start () {
//set up controllers for input
right_controller_o = right_controller.GetComponent<SteamVR_TrackedObject>();
left_controller_o = left_controller.GetComponent<SteamVR_TrackedObject>();
}
// Update is called once per frame
void Update () {
//get input from right controller
controller_right = SteamVR_Controller.Input((int)right_controller_o.index);
//get input from left controller
controller_left = SteamVR_Controller.Input((int)left_controller_o.index);
//fly up if right menu button held down
if (controller_right.GetPress(SteamVR_Controller.ButtonMask.ApplicationMenu))
{
this.transform.position = new Vector3(this.transform.position.x, this.transform.position.y - speed, this.transform.position.z);
}
//fly down if left menu buttonis held down
if (controller_left.GetPress(SteamVR_Controller.ButtonMask.ApplicationMenu))
{
this.transform.position = new Vector3(this.transform.position.x, this.transform.position.y + speed, this.transform.position.z);
}
//fly to the right if right controller touch pad is touched
if (controller_right.GetPress(SteamVR_Controller.ButtonMask.Touchpad))
{
this.transform.position = new Vector3(this.transform.position.x + speed, this.transform.position.y, this.transform.position.z);
}
//fly to the left if left controller touch pad is touched
if (controller_left.GetPress(SteamVR_Controller.ButtonMask.Touchpad))
{
this.transform.position = new Vector3(this.transform.position.x - speed, this.transform.position.y, this.transform.position.z);
}
//fly forward if right controller is gripped
if (controller_right.GetPress(SteamVR_Controller.ButtonMask.Grip))
{
this.transform.position = new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z + speed);
}
//fly backif left controller is gripped
if (controller_left.GetPress(SteamVR_Controller.ButtonMask.Grip))
{
this.transform.position = new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z - speed);
}
}
}
|
044750bba207724060f0cf5f72a2919f2ea5631e
|
[
"C#"
] | 4 |
C#
|
cdecampli/SteamVR-Testing
|
6d237c73ad49815cfcd1ff9a4a057b46c571b5d7
|
a59b89f9ff6f0d0296db4256014d06f009f50555
|
refs/heads/master
|
<repo_name>Sirpyerre/weather_app<file_sep>/src/store/index.js
import {createStore, applyMiddleware, compose} from "redux";
import thunk from 'redux-thunk';
import reducers from './../reducers';
const initialState = {
city: 'Washington, us'
};
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__|| compose;
export const store = createStore(reducers,initialState, composeEnhancers(applyMiddleware(thunk)));
|
f4e816093045e761e7c66eac49cef029bde7c9ef
|
[
"JavaScript"
] | 1 |
JavaScript
|
Sirpyerre/weather_app
|
2d1976e8998ae75861eb46086a9a502439726fe0
|
60ac621843f7c1583a969b6cee17b560a7bf866d
|
refs/heads/master
|
<repo_name>EiderDiaz/proyectomascore<file_sep>/README.md
# proyectomascore
proyecto de swift con core data <br>
#Se necesita una app para iOS , para los aficionados a las películas, <br>
#en esa app se va a registrar el nombre de la película en inglés y español latino, <br>
#los actores y actrices, la fecha en que la mire,<br>
#La interfaz debe de cumplir con los estándares humano computadora de iOS y debe de impedir duplicados,<br>
#tanto de películas como de actores y actrices,<br>
#me debe de permitir consultar cuáles son los actores y actrices que más veo, en qué lugar veo más películas, <br>
# Películas con género <br>
#Tipo de tipos de género y agregarlos tu, dos tipos de género por <br>
#Actrices y actores y autocompletar <br>
#Buenas búsquedas , <NAME> con fulanito <br>
<file_sep>/ListaAlumnosMasCoreData/ProtocoloAlumno.swift
//
// ProtocoloAlumno.swift
// ListaAlumnosMasCoreData
//
// Created by eiderdiaz on 5/15/17.
// Copyright © 2017 eiderdiaz. All rights reserved.
//
import Foundation
|
299fff400e354d1d994840943337bde66254a312
|
[
"Markdown",
"Swift"
] | 2 |
Markdown
|
EiderDiaz/proyectomascore
|
af121d813ef1286fe1ae7931cbca5af4f219e0a5
|
8edc9994e299b0abce7c5bae148a00a7697d213e
|
refs/heads/master
|
<repo_name>joemiller/aws-cf-private-streaming-tools<file_sep>/README.md
aws-cf-private-streaming-tools
==============================
What?
-----------
A set of ruby CLI tools for creating and modifying Amazon Cloudfront
Private Streaming Distributions and Origin Access ID's, using the
RightAWS ruby library.
Why?
----
I created these tools a in late 2010 because I needed to setup a
private streaming distribution (RTMP) on Amazon Cloudfront. However,
the Amazon web management console did not support this and I could
not find any cli tools either.
Luckily the right_aws ruby libraries (>= 2.0.0) already had support
for Private Streaming distributions, so all I had to do was put together
a few CLI wrappers to make them easy for admins to utilize.
Available Commands
------------------
#### cf-streaming-distribution.rb ####
$ ./cf-streaming-distribution.rb --help
Synopsis
--------
cf-streaming-distribution: Manipulate Amazon Cloudfront Streaming
Distributions
Usage
-----
cf-streaming-distribution.rb [OPTIONS] [command] [args]
Commands
--------
list
List all Streaming Distributions
get [aws_id]
Get details about the Streaming Distribution identified by [aws_id].
create [bucket]
Create new Streaming Distribution using S3 origin bucket [bucket]. CNAMEs
can optionally be specified with multiple --cname options, and a comment can
be applied with --comment option
delete [aws_id] [e_tag]
Delete the Streaming Distribution identified by [aws_id] and [e_tag]. A
distribution must first be disabled before it can be deleted. Use 'get'
to retrieve a distribution's e_tag.
modify [aws_id]
Modify attributes on the Streaming Distribution identified by [aws_id]. Must
be used in conjunction with at least one of the following options:
--comment, --enabled, --oai, --trusted-signer, --cname
wait [aws_id]
Loop until a Streaming Distribution specified by [aws_id] enters the 'deployed'
state. You could use this in scripts if you need to know when a
distribution becomes available for use.
#### ./cf-origin-access-id.rb ####
$ ./cf-origin-access-id.rb --help
Synopsis
--------
cf-origin-access-id:
List, create, delete CloudFront Origin Access Identities (OAI's), as well
as grant permissions on S3 objects to CloudFront OAI's.
Usage
-----
cf-origin-access-id.rb [OPTIONS] [command] [args]
commands:
---------
list:
List Origin Access Identities
create [comment]
Create a new Origin Access Identity. The AWS_ID and S3 Canonical ID
will be returned if successful
get [aws_id]
Get details about an Origin Access Identity specified by [aws_id]. This
command will display e_tag which is needed to delete an OAI
delete [aws_id] [e_tag]
Delete the Origin Access Identity specified by [aws_id] and [e_tag]. Use
'get' to retrieve the current e_tag.
grant [aws_id] [bucket]
grant 'FULL_PERMISSION' access on <tt>all</tt> objects inside the S3 bucket specified
by [bucket] to the OAI specified by [aws_id]. There is little reason to
create an OAI other than to give it permissions to some objects within S3,
and this command helps simplify that for you.
Example Workflow
----------------
In this example we will setup a new Cloudfront Private Streaming distribution
with the following attributes:
* S3 origin bucket: my-video-bucket
* CF base URL (CNAME): rtmp://cf.example.com/
#### 1. Setup AWS keys ####
$ export AWS_ACCESS_KEY_ID='xxxxx'
$ export AWS_SECRET_ACCESS_KEY='xxxxxx'
#### 2. Create a new Cloudfront Streaming Distribution ####
$ ./cf-streaming-distribution.rb create my-video-bucket \
--cname cf.example.com \
-m "private streaming distribution (rtmp) with origin bucket: my-video-bucket"
Success!
domain_name: s1loj2pirm00it.cloudfront.net
aws_id: E1UGDLB9XZBD79
#### 3. Configure CNAME in your DNS server #####
This part will depend on DNS server or DNS provider. You'll need to create a new CNAME
for cf.example.com --> s1loj2pirm00it.cloudfront.net
#### 4. Create a new Origin-Access-ID (OAI) ####
$ ./cf-origin-access-id.rb create "OAI for use on the cf.example.com distribution"
Success!
AWS_ID : E2CWXW7A1B3YIU
Location : https://cloudfront.amazonaws.com/origin-access-identity/cloudfront/E2CWXW7A1B3YIU
S3 Canonical ID: 3b5285f7f1b51ff2e63e8ff8127b7ffb76edee24580cb7fff6ef812aa87b749aaa3ed1aab389aaaab4453499a7ba57e7
#### 5. Assign the OAI to the Cloudfront distribution ####
./cf-streaming-distribution.rb modify E1UGDLB9XZBD79 --oai E2CWXW7A1B3YIU
Success!
#### 6. Grant the OAI access to the files in the S3 bucket ####
$ ./cf-origin-access-id.rb grant E2CWXW8B1U3YJU my-video-bucket
Applying grant [E2CWXW8B1U3YJU:'FULL_CONTROL'] on: my-video-bucket/flvs/video01.flv
Applying grant [E2CWXW8B1U3YJU:'FULL_CONTROL'] on: my-video-bucket/flvs/video02.flv
...
#### 7. Create RSA Keypair on the Amazon AWS website ####
You cannot create keypairs with the cloudfront API, so you'll need to do this step
on the AWS website.
* Goto http://aws.amazon.com then login:
* Account > Security Credentials > Key Pairs
* Click “Create New Key Pair” under the “Cloudfront Key Pairs” section
* A keypair will be created and the private key will automatically begin downloading.
You must save this file! it will be in the form “pk-XXXXXX.pem”. If you lose this key,
you can’t get it back because Amazon only stores the public key.
#### 8. Register the account and keypairs on the cloudfront distribution ####
NOTE: the --trusted-signer arguments takes an amazon account ID as an argument.
The special ‘self’ can be used instead.
$ ./cf-streaming-distribution.rb modify E1UGDLB9XZBD79 --trusted-signer self
Success!
#### 9. Verify settings on the new private Streaming Distribution ####
$ ./cf-streaming-distribution.rb get E1UGDLB9XZBD79
AWS_ID : E1UGDLB9XZBD79
E_TAG : EQ3HGAPOK1IFN
Status : InProgress
Enabled : true
domain_name : s1loj2pirm00it.cloudfront.net
origin : my-video-bucket.s3.amazonaws.com
CNAMEs : cf.example.com
Comment : private streaming distribution (rtmp) with origin bucket: my-video-bucket
Origin Access ID: origin-access-identity/cloudfront/E2CWXW7A1B3YIU
Trusted Signers : self
Active Signers:
-> aws_account_number: self
-> key_pair_id : <KEY>
NOTE: The distribution will not be usable until Status changes from InProgress to Deployed.
This can take up to 15minutes.
You can also use the command `cf-streaming-distribution.rb wait AWS_ID` to
wait for a distribution to change from InProgress to Deployed. The command will
exit as soon as the status changes to Deployed. This is useful for scripts
where you need to control timing.
Who?
----
<NAME> - joeym -at- joeym.net<file_sep>/cf-streaming-distribution.rb
#!/usr/bin/ruby
#
# == Synopsis
#
# cf-streaming-distribution: Manipulate Amazon Cloudfront Streaming Distributions
#
# == Usage
#
# cf-streaming-distribution.rb [OPTIONS] [command] [args]
#
# == Commands
# list
# List all Streaming Distributions
#
# get [aws_id]
# Get details about the Streaming Distribution identified by [aws_id].
#
# create [bucket]
# Create new Streaming Distribution using S3 origin bucket [bucket]. CNAMEs
# can optionally be specified with multiple --cname options, and a comment can
# be applied with --comment option
#
# delete [aws_id] [e_tag]
# Delete the Streaming Distribution identified by [aws_id] and [e_tag]. A
# distribution must first be disabled before it can be deleted. Use 'get'
# to retrieve a distribution's e_tag.
#
# modify [aws_id]
# Modify attributes on the Streaming Distribution identified by [aws_id]. Must
# be used in conjunction with at least one of the following options:
# --comment, --enabled, --oai, --trusted-signer, --cname
#
# wait [aws_id]
# Loop until a Streaming Distribution specified by [aws_id] enters the 'deployed'
# state. You could use this in scripts if you need to know when a
# distribution becomes available for use.
#
# == OPTIONS
# -h, --help:
# show help
#
# -c, --cname [cname]:
# Use this CNAME on the bucket (can be used with 'create' and 'modify' commands).
# Multiple --cname options can be used. When used with modify command, will
# overwrite all existing CNAMEs
#
# -o, --oai [origin-access-identity]:
# Use with 'modify' command to set the Origin Access Identity on a Streaming
# Distribution.
#
# -e, --enable:
# Use with 'modify' command to enable a Streaming Distribution.
#
# -d, --disable:
# Use with 'modify' command to disable a Streaming Distribution.
#
# -t, --trusted-signer [aws_account_id | self]:
# Use with 'modify' command to set trusted signers on a Streaming Distribution.
# Can be used multiple times to set multiple signers. This will overwrite all
# existing trusted signers. Use 'self' for [aws_account_id] to refer to the
# parent account of the Streaming Distribution.
#
# -m, --comment ['some descriptive test']:
# Set 'comment' on the distribution
#
# -k, --key [AWS_ACCESS_KEY_ID]
# Amazon AWS ACCESS KEY ID (can also be set in environment variable 'AWS_ACCESS_KEY_ID')
#
# -s, --seckey [AWS_SECRET_ACCESS_KEY]
# Amazon AWS SECRET ACCESS KEY (can also be set in environment variable 'AWS_SECRET_ACCESS_KEY')
# <NAME>, <<EMAIL>>, 10/30/2010
require 'rubygems'
require 'right_aws'
require 'getoptlong'
require 'rdoc/usage'
opts = GetoptLong.new(
[ '--help', '-h', GetoptLong::NO_ARGUMENT ],
[ '--cname', '-c', GetoptLong::REQUIRED_ARGUMENT ],
[ '--oai', '-o', GetoptLong::REQUIRED_ARGUMENT ],
[ '--enable', '-e', GetoptLong::NO_ARGUMENT ],
[ '--disable', '-d', GetoptLong::NO_ARGUMENT ],
[ '--trusted-signer', '-t', GetoptLong::REQUIRED_ARGUMENT ],
[ '--comment', '-m', GetoptLong::REQUIRED_ARGUMENT ],
[ '--key', '-k', GetoptLong::REQUIRED_ARGUMENT ],
[ '--seckey', '-s', GetoptLong::REQUIRED_ARGUMENT ]
)
key = ENV['AWS_ACCESS_KEY_ID']
seckey = ENV['AWS_SECRET_ACCESS_KEY']
cnames = []
signers = []
oai = nil
enabled = nil
comment = nil
opts.each do |opt, arg|
case opt
when '--help'
RDoc::usage
when '--cname'
cnames.push arg
when '--comment'
comment = arg
when '--key'
key = arg
when '--seckey'
seckey = arg
when '--oai'
oai = arg
when '--trusted-signer'
signers.push arg
when '--enable'
enabled = true
when '--disable'
enabled = false
end
end
command = ARGV.shift
args = ARGV
log = Logger.new(STDERR)
log.level = Logger::FATAL
### connect to amazon cloudfront
cf = RightAws::AcfInterface.new(key, seckey,
{:logger => log} )
if command == 'list'
dists = cf.list_streaming_distributions
dists.each do |dist|
cn = []
cn.push dist[:cnames]
puts
puts "AWS_ID : #{dist[:aws_id]}"
puts " Status : #{dist[:status]}"
puts " Enabled : #{dist[:enabled].to_s}"
puts " domain_name : #{dist[:domain_name]}"
puts " origin : #{dist[:s3_origin][:dns_name].split(".")[0]}"
puts " CNAMEs : #{cn.join(", ")}"
puts " Comment : #{dist[:comment]}"
end
elsif command == 'get'
if args.length < 1
puts "'get' requires 1 arg (try --help)"
exit 1
end
aws_id = args.shift
begin
result = cf.get_streaming_distribution(aws_id)
rescue RightAws::AwsError => e
e.errors.each do |code, msg|
puts "Error (#{code}): #{msg}"
end
exit 1
end
cn = []
cn.push result[:cnames]
puts
puts "AWS_ID : #{result[:aws_id]}"
puts " E_TAG : #{result[:e_tag]}"
puts " Status : #{result[:status]}"
puts " Enabled : #{result[:enabled].to_s}"
puts " domain_name : #{result[:domain_name]}"
puts " origin : #{result[:s3_origin][:dns_name].split(".")[0]}"
puts " CNAMEs : #{cn.join(", ")}"
puts " Comment : #{result[:comment]}"
if result[:origin_access_identity]
puts " Origin Access ID: #{result[:origin_access_identity]}"
end
if result[:trusted_signers]
puts " Trusted Signers : " + result[:trusted_signers].join(", ")
#result[:trusted_signers].each do |account|
# puts " -> aws_account_number: #{account}"
#end
end
if result[:active_trusted_signers]
puts " Active Signers:"
result[:active_trusted_signers].each do |signer|
puts " -> aws_account_number: #{signer[:aws_account_number]}"
if signer[:key_pair_ids]
signer[:key_pair_ids].each do |keypair|
puts " -> key_pair_id : #{keypair}"
end
end
end
end
elsif command == 'delete'
if args.length < 2
puts "'delete' requires 2 args (try --help)"
exit 1
end
aws_id = args.shift
etag = args.shift
begin
result = cf.delete_streaming_distribution(aws_id, etag)
rescue RightAws::AwsError => e
e.errors.each do |code, msg|
puts "Error (#{code}): #{msg}"
end
exit 1
end
if result == true
puts "Delete successful"
else
puts "Delete failed"
end
elsif command == 'create'
if args.length < 1
puts "'create' requires 1 arg (try --help)"
exit 1
end
## the CF api expects a canonical bucket name for the origin bucket,
## eg "mybucket.s3.amazonaws.com".
bucket = args.shift
unless bucket =~ /s3\.amazonaws\.com$/
bucket = bucket + '.s3.amazonaws.com'
end
begin
config = {
:s3_origin => {:dns_name => bucket},
:comment => comment,
:enabled => true,
:cnames => Array(cnames),
}
result = cf.create_streaming_distribution(config)
rescue RightAws::AwsError => e
e.errors.each do |code, msg|
puts "Error (#{code}): #{msg}"
end
exit 1
end
## success
puts
puts
puts
puts
puts "Success!"
puts "domain_name: #{result[:domain_name]}"
puts "aws_id: #{result[:aws_id]}"
exit 0
elsif command == 'modify'
if args.length < 1
puts "'create' requires 1 arg (try --help)"
exit 1
end
aws_id = args.shift
begin
config = cf.get_streaming_distribution_config(aws_id)
config[:comment] = comment if comment
config[:trusted_signers] = signers if signers.length > 0
config[:cnames] = cnames if cnames.length > 0
config[:enabled] = enabled if enabled != nil
config[:s3_origin][:origin_access_identity] = "origin-access-identity/cloudfront/#{oai}" if oai
result = cf.set_streaming_distribution_config(aws_id, config)
rescue RightAws::AwsError => e
e.errors.each do |code, msg|
puts "Error (#{code}): #{msg}"
end
exit 1
end
if result == true
puts "Success!"
else
puts "Unknown error occurred"
end
elsif command == 'wait'
if args.length < 1
puts "'wait' requires 1 arg (try --help)"
exit 1
end
aws_id = args.shift
until cf.get_streaming_distribution(aws_id)[:status] == 'Deployed'
puts "Waiting for streaming distribution #{aws_id} to become 'Deployed' .."
sleep 5
end
else
puts "no command given (try --help)"
exit 1
end
exit 0
<file_sep>/cf-origin-access-id.rb
#!/usr/bin/ruby
#
# == Synopsis
#
# cf-origin-access-id:
# List, create, delete CloudFront Origin Access Identities (OAI's), as well
# as grant permissions on S3 objects to CloudFront OAI's.
#
# == Usage
#
# cf-origin-access-id.rb [OPTIONS] [command] [args]
#
# == commands:
# list:
# List Origin Access Identities
#
# create [comment]
# Create a new Origin Access Identity. The AWS_ID and S3 Canonical ID
# will be returned if successful
#
# get [aws_id]
# Get details about an Origin Access Identity specified by [aws_id]. This
# command will display e_tag which is needed to delete an OAI
#
# delete [aws_id] [e_tag]
# Delete the Origin Access Identity specified by [aws_id] and [e_tag]. Use
# 'get' to retrieve the current e_tag.
#
# grant [aws_id] [bucket]
# grant 'FULL_PERMISSION' access on +all+ objects inside the S3 bucket specified
# by [bucket] to the OAI specified by [aws_id]. There is little reason to
# create an OAI other than to give it permissions to some objects within S3,
# and this command helps simplify that for you.
#
# == OPTIONS:
# -h, --help
# show help
#
# -k, --key [AWS_ACCESS_KEY_ID]
# Amazon AWS ACCESS KEY ID (can also be set in environment variable 'AWS_ACCESS_KEY_ID')
#
# -s, --seckey [AWS_SECRET_ACCESS_KEY]
# Amazon AWS SECRET ACCESS KEY (can also be set in environment variable 'AWS_SECRET_ACCESS_KEY')
# <NAME>, <<EMAIL>>, 10/30/2010
require 'rubygems'
require 'right_aws'
require 'getoptlong'
require 'rdoc/usage'
opts = GetoptLong.new(
[ '--help', '-h', GetoptLong::NO_ARGUMENT ],
[ '--key', '-k', GetoptLong::REQUIRED_ARGUMENT ],
[ '--seckey', '-s', GetoptLong::REQUIRED_ARGUMENT ]
)
key = ENV['AWS_ACCESS_KEY_ID']
seckey = ENV['AWS_SECRET_ACCESS_KEY']
opts.each do |opt, arg|
case opt
when '--help'
RDoc::usage
when '--list'
do_list = true
when '--key'
key = arg
when '--seckey'
seckey = arg
end
end
if ARGV.length < 1
puts "no command given (try --help)"
exit 1
end
command = ARGV.shift
args = ARGV
log = Logger.new(STDERR)
log.level = Logger::FATAL
### connect to amazon cloudfront
cf = RightAws::AcfInterface.new(key, seckey, {:logger => log} )
if command == 'list'
oais = cf.list_origin_access_identities
oais.each do |oai|
puts
puts "AWS_ID : #{oai[:aws_id]}"
puts " S3 Canonical ID: #{oai[:s3_canonical_user_id]}"
puts " Comment : #{oai[:comment]}"
end
elsif command == 'create'
if args.length < 1
puts "'create' requires 1 arg (try --help)"
exit 1
end
comment = args.shift
begin
result = cf.create_origin_access_identity(comment)
rescue RightAws::AwsError => e
e.errors.each do |code, msg|
puts "Error (#{code}): #{msg}"
end
exit 1
end
puts "Success!"
puts "AWS_ID : #{result[:aws_id]}"
puts " Location : #{result[:location]}"
puts " S3 Canonical ID: #{result[:s3_canonical_user_id]}"
elsif command == 'get'
if args.length < 1
puts "'get' requires 1 arg (try --help)"
exit 1
end
aws_id = args.shift
begin
result = cf.get_origin_access_identity(aws_id)
rescue RightAws::AwsError => e
e.errors.each do |code, msg|
puts "Error (#{code}): #{msg}"
end
exit 1
end
puts "AWS_ID : #{result[:aws_id]}"
puts " E_TAG : #{result[:e_tag]}"
puts " Caller ref : #{result[:caller_reference]}"
puts " Comment : #{result[:comment]}"
puts " S3 Canonical ID: #{result[:s3_canonical_user_id]}"
elsif command == 'delete'
if args.length < 2
puts "'delete' requires 2 args (try --help)"
exit 1
end
aws_id = args.shift
etag = args.shift
begin
result = cf.delete_origin_access_identity(aws_id, etag)
rescue RightAws::AwsError => e
e.errors.each do |code, msg|
puts "Error (#{code}): #{msg}"
end
exit 1
end
if result == true
puts "Delete successful"
else
puts "Delete failed"
end
elsif command == 'grant'
if args.length < 2
puts "'grant' requires 2 args (try --help)"
exit 1
end
aws_id = args.shift
bucket = args.shift
begin
s3 = RightAws::S3.new(key, seckey, {:logger => log})
s3bucket = s3.bucket(bucket)
s3canonical_id = cf.get_origin_access_identity(aws_id)[:s3_canonical_user_id]
count = 0
s3bucket.keys.each do |key|
count += 1
puts "#{count}: Applying grant [#{aws_id}:'FULL_CONTROL'] on: s3://#{key.full_name}"
grantee = RightAws::S3::Grantee.new(key, s3canonical_id)
grantee.grant('FULL_CONTROL')
end
rescue RightAws::AwsError => e
e.errors.each do |code, msg|
puts "Error (#{code}): #{msg}"
end
exit 1
end
else
puts "no command given (try --help)"
exit 1
end
module Grants
def test
puts 'test'
end
end
class RightAws::S3Interface; include Grants; end
exit 0
|
f531acb3b1eddf637837d6579c2b14a743ef95c2
|
[
"Markdown",
"Ruby"
] | 3 |
Markdown
|
joemiller/aws-cf-private-streaming-tools
|
766450bbbcb80fd407061b674d026c7c7efabb1f
|
c6515fb01836a7368fc2bd6ffca1a4506a7641a5
|
refs/heads/master
|
<repo_name>rareed2021/QRTest<file_sep>/app/src/main/java/com/test/qrtest/MainActivity.kt
package com.test.qrtest
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.core.util.forEach
import com.google.android.gms.vision.CameraSource
import com.google.android.gms.vision.Detector
import com.google.android.gms.vision.text.TextRecognizer
import com.google.android.gms.vision.barcode.Barcode
import com.google.android.gms.vision.barcode.BarcodeDetector
import com.google.android.gms.vision.text.TextBlock
import com.karumi.dexter.Dexter
import com.karumi.dexter.PermissionToken
import com.karumi.dexter.listener.PermissionDeniedResponse
import com.karumi.dexter.listener.PermissionGrantedResponse
import com.karumi.dexter.listener.PermissionRequest
import com.karumi.dexter.listener.single.PermissionListener
import com.test.qrtest.databinding.ActivityMainBinding
import java.lang.StringBuilder
class MainActivity : AppCompatActivity() {
lateinit var detector :BarcodeDetector
lateinit var textDetector: TextRecognizer
lateinit var binding: ActivityMainBinding
lateinit var processor: Detector.Processor<Barcode>
lateinit var textProcessor : Detector.Processor<TextBlock>
lateinit var camera:CameraSource
lateinit var textCamera:CameraSource
var isTaking = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
init()
}
private fun stopCamera() {
isTaking=false
camera.stop()
textCamera.stop()
binding.buttonQr.visibility= View.VISIBLE
binding.buttonText.visibility = View.VISIBLE
binding.buttonStop.visibility= View.GONE
}
@SuppressLint("MissingPermission")
private fun startCamera(camera: CameraSource) {
binding.buttonQr.visibility= View.GONE
binding.buttonText.visibility = View.GONE
binding.buttonStop.visibility= View.VISIBLE
camera.start(binding.surfaceImage.holder)
}
fun init(){
textProcessor = object :Detector.Processor<TextBlock>{
override fun release() {
camera.stop()
}
override fun receiveDetections(p0: Detector.Detections<TextBlock>) {
val builder = StringBuilder()
p0.detectedItems.forEach { id, item ->
Log.d(TAG, "receiveDetections: ${item.language}")
builder.append(item.value)
builder.append("\n")
}
binding.textData.text = builder.toString()
}
}
processor = object:Detector.Processor<Barcode>{
override fun release() {
camera.stop()
}
override fun receiveDetections(p0: Detector.Detections<Barcode>) {
val builder = StringBuilder()
p0.detectedItems.forEach{ id,item->
val url = item.email
Log.d(TAG, "receiveDetections: $url ${url?.address}")
builder.append(item.rawValue)
builder.append("\n")
}
binding.textData.text = builder.toString()
}
}
detector = BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.QR_CODE or Barcode.UPC_A or Barcode.CODABAR or Barcode.UPC_E)
.build().apply {
setProcessor(processor)
}
if(!detector.isOperational){
Log.d(TAG, "Error setting up detector")
Toast.makeText(this, "Could not set up detector", Toast.LENGTH_SHORT).show()
return
}
textDetector = TextRecognizer.Builder(this)
.build().apply {
setProcessor(textProcessor)
}
camera = CameraSource.Builder(applicationContext, detector)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedPreviewSize(1600,1024)
.setRequestedFps(15.0f)
.setAutoFocusEnabled(true)
.build()
textCamera = CameraSource.Builder(this,textDetector)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedPreviewSize(1600,1024)
.setRequestedFps(12.0f)
.setAutoFocusEnabled(true)
.build()
binding.buttonQr.setOnClickListener {
// startActivityForResult(Intent(MediaStore.ACTION_IMAGE_CAPTURE), REQUEST_CODE)
// if(isTaking)
// stopCamera()
// else
handleQR()
}
binding.buttonText.setOnClickListener {
handleText()
}
binding.buttonStop.setOnClickListener {
stopCamera()
}
}
private fun handleText() {
Dexter.withContext(this)
.withPermission(Manifest.permission.CAMERA)
.withListener(object:PermissionListener{
override fun onPermissionGranted(p0: PermissionGrantedResponse?) {
startCamera(textCamera)
}
override fun onPermissionDenied(p0: PermissionDeniedResponse?) {
}
override fun onPermissionRationaleShouldBeShown(p0: PermissionRequest?, p1: PermissionToken?) {
}
}).check()
}
private fun handleQR() {
Dexter.withContext(this)
.withPermission(Manifest.permission.CAMERA)
.withListener(object : PermissionListener {
@SuppressLint("MissingPermission")
override fun onPermissionGranted(p0: PermissionGrantedResponse?) {
startCamera(camera)
}
override fun onPermissionDenied(p0: PermissionDeniedResponse?) {
Log.d(TAG, "onPermissionDenied: ")
}
override fun onPermissionRationaleShouldBeShown(
p0: PermissionRequest?,
p1: PermissionToken?
) {
Log.d(TAG, "onPermissionRationaleShouldBeShown: ")
}
})
.check()
}
private fun takeQR() {
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(resultCode == Activity.RESULT_OK){
if(requestCode== REQUEST_CODE){
val bmp = data?.extras?.get("data") as? Bitmap
bmp?.also {
}
}
}
}
companion object{
const val REQUEST_CODE = 4
private const val TAG = "myapp"
}
}
|
ec0942b67504c36cf6fa5981e79c37023bfa8e67
|
[
"Kotlin"
] | 1 |
Kotlin
|
rareed2021/QRTest
|
48b23ccb15c0f892f0a8415b700ee9aff6e7a430
|
ca00272c9c03fb537976035ad379f30ec368ac31
|
refs/heads/master
|
<repo_name>ThanujaRaju04/capgemini-devops1<file_sep>/README.md
# capgemini-devops1
LearningDevops
<<<<<<< HEAD
hgfdchggggggggggggggggggggggggggbv
developer-1
=======
bgvcjhfv
>>>>>>> 2fc508e970693ca49d328ac6d1b5e91d35b87fdc
<file_sep>/A.java
Class A
{
void welcome()
{
}
void add(int x,int y)
{
int c=x+y;
}
void null()
{
}
//working
//working on feature-5
}
|
3cf836a1ac5b7dfa1ed6274ba9947599ed953291
|
[
"Markdown",
"Java"
] | 2 |
Markdown
|
ThanujaRaju04/capgemini-devops1
|
74e9301b2f029937a59e89b2bc8f1b303dcdb9df
|
1c96c058f3f624c4cb551c11d799f6c14713f9d2
|
refs/heads/master
|
<file_sep>## A very quick demonstration of the samplers. More to come.
## Run the simple example, so that obj and opt are loaded into workspace
library(TMB)
library(adnuts)
TMB::runExample("simple")
## Remake obj without random components
obj <- MakeADFun(data=list(x=x, B=B, A=A),
parameters=list(u=u*0, beta=beta*0, logsdu=1, logsd0=1),
random=NULL, DLL="simple", silent=TRUE)
## Note that this model does not use any box constraints. These can be
## passed to sample_tmb just like with nlminb. Also, there are no explicit
## priors in this model, which can be influential particularly for the
## logsd params.
## init can be a function, or a list of lists, or NULL to use starting
## values in obj.
init <- function() list(mu=u, beta=beta, logsdu=0, logsd0=0)
iter <- 2000
seeds <- 1:3
## First use a diagonal mass matrix (not recommended)
fit1 <- sample_tmb(obj=obj, iter=iter, chains=3, init=init, seeds=seeds,
control=list(adapt_mass=FALSE))
## Extra posterior samples like this
posterior <- extract_samples(fit1)
apply(posterior, 2, mean)
## Check diagnostics with shinystan:
launch_shinytmb(fit1)
## Or look at the values directly
sp <- extract_sampler_params(fit1)
str(sp)
min(fit1$ess)
max(fit1$Rhat)
## Can also use mass matrix adaptation (default -- diagonal only)
fit2 <- sample_tmb(obj=obj, iter=iter, chains=3, init=init, seeds=seeds,
control=list(adapt_mass=TRUE))
## Or pass an estimated one from a previous run (or could be MLE if it
## exists). This will help a lot of there are strong correlations in the
## model.
fit3 <- sample_tmb(obj=obj, iter=iter, chains=3, init=init, seeds=seeds,
control=list(metric=fit2$covar.est))
## Parallel works too
library(snowfall)
path <- system.file("examples", package = "TMB")
## DLL needs to be available in this folder since each node calls MakeADFun
## again to remake obj. So recompile here.
compile(file.path(path,'simple.cpp'))
fit4 <- sample_tmb(obj=obj, iter=iter, chains=3, seeds=1:3, init=init,
parallel=TRUE, cores=3, path=path)
library(vioplot)
## The mass matrix typically doesn't effect ESS since it runs long enough
## to get nearly independent samples. Instead each trajectory is shorter
## and hence the chains run faster
vioplot(fit1$ess, fit2$ess, fit3$ess, fit4$ess)
## Run time:
sum(fit1$time.total)
sum(fit2$time.total)
sum(fit3$time.total)
max(fit4$time.total)
## Efficiency:
min(fit1$ess)/sum(fit1$time.total)
min(fit2$ess)/sum(fit2$time.total)
min(fit3$ess)/sum(fit3$time.total)
min(fit4$ess)/max(fit4$time.total)
|
8c31f15bc3a04987a4acc60b93f69666d2aece75
|
[
"R"
] | 1 |
R
|
Andrea-Havron/adnuts
|
bf64586a58e4706a6575e6f34d52d6566a70d1bc
|
25160d2c84539ee7820a52e7973b42c661648f86
|
refs/heads/master
|
<file_sep>import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class TempoGastoService {
public dataInicio: Date;
public dataFim: Date;
public tempoGastoMinutos: any;
public pegaData() {
this.dataInicio = new Date();
const dataInicioMili = this.dataInicio.getTime();
window.localStorage.setItem('dataInicio', dataInicioMili.toString());
}
public calculadata() {
const dataInicioMili = window.localStorage.getItem('dataInicio');
const dataFimMili = new Date().getTime();
this.dataFim = new Date();
// tslint:disable-next-line: radix
const tempo = (dataFimMili - parseInt(dataInicioMili));
const tempoGasto = (tempo / 1000) / 60;
this.tempoGastoMinutos = Math.round(tempoGasto * 100) / 100;
}
}
<file_sep>import { Component } from '@angular/core';
import { TempoGastoService } from '../service/tempo-gasto.service';
@Component({
selector: 'app-tab3',
templateUrl: 'tab3.page.html',
styleUrls: ['tab3.page.scss']
})
export class Tab3Page {
constructor(private calcTempo: TempoGastoService) {}
public faz() {
this.calcTempo.pegaData();
}
public faz2() {
this.calcTempo.calculadata();
console.log('-------------------------------------------------------------');
console.log('dentro de tab inicio às: ', this.calcTempo.dataInicio);
console.log('dentro de tab fim às: ', this.calcTempo.dataFim);
console.log('dentro de tab tempo gasto em minutos: ', this.calcTempo.tempoGastoMinutos);
console.log('-------------------------------------------------------------');
}
}
<file_sep>import { TestBed } from '@angular/core/testing';
import { TempoGastoService } from './tempo-gasto.service';
describe('TempoGastoService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: TempoGastoService = TestBed.get(TempoGastoService);
expect(service).toBeTruthy();
});
});
|
972ace0074a58a1a5a6798cb1daba38d3bf1922b
|
[
"TypeScript"
] | 3 |
TypeScript
|
paulobrito27/SmartSupply
|
9be12cd9bd93476704b77da08d4d00b7f0983c86
|
2dcb61c24dd349f79aebcea38cc4b351261273f2
|
refs/heads/main
|
<file_sep># Simple-ReactNative-UI
I have started learning React-Native. You can contribute to the repo and can help me to learn more things.
**************************
If you're unable to load your app on your phone due to a network timeout or a refused connection,
a good first step is to verify that your phone and computer are on the same network and that they can reach each other.
Create React Native App needs access to ports 19000 and 19001 so ensure that your network and firewall settings allow access from your device to your computer on both of these ports.
Try opening a web browser on your phone and opening the URL that the packager script prints, replacing exp:// with http://.
So, for example, if underneath the QR code in your terminal you see:
exp://192.168.0.1:19000
<file_sep>import { StatusBar } from "expo-status-bar";
import React from "react";
import { Image, StyleSheet, Text, TouchableOpacity, View } from "react-native";
/* import Swiper from 'react-native-swiper';
Next I am going to add swiper and header
*/
export default class App extends React.Component {
render() {
return (
<View style={styles.container}>
<Image
style={{
width: "100%",
height: 220,
marginBottom: 10,
borderRadius: 200,
}}
source={require("./assets/download.png")}
resizeMode="contain"
/>
<Text style={{ fontSize: 40, fontWeight: "bold" }}>Hello!</Text>
<Text
style={{
fontSize: 16,
color: "gray",
textAlign: "center",
marginHorizontal: 20,
}}
>
Welcome to Masab's UI
</Text>
<View style={{ flexDirection: "row", margin: 1, paddingVertical: 20 }}>
<TouchableOpacity
style={{
backgroundColor: "#0d47a1",
padding: 10,
borderRadius: 30,
width: 120,
marginHorizontal: 2,
}}
>
<Text style={{ textAlign: "center", color: "#fff", fontSize: 18 }}>
LogIn
</Text>
</TouchableOpacity>
<TouchableOpacity
style={{
backgroundColor: "#0d47a1",
padding: 10,
borderRadius: 30,
width: 120,
marginHorizontal: 2,
}}
>
<Text
style={{
textAlign: "center",
color: "#fff",
fontSize: 18,
marginHorizontal: 2,
borderWidth: 1,
borderColor: "#0d47a1",
}}
>
SignUp
</Text>
</TouchableOpacity>
</View>
<Text style={{ fontSize: 20, marginHorizontal: 10 }}>
Or join me on
</Text>
<View style={{ flexDirection: "row", marginTop: 20 }}>
<View
style={{
height: 50,
width: 50,
borderRadius: 50 / 2,
backgroundColor: "#1565c0",
alignItems: "center",
justifyContent: "center",
}}
>
<Text style={{ fontSize: 25, fontWeight: "bold", color: "#fff" }}>
f
</Text>
</View>
<View
style={{
height: 50,
width: 50,
borderRadius: 50 / 2,
backgroundColor: "#ef5350",
marginHorizontal: 10,
alignItems: "center",
justifyContent: "center",
}}
>
<Text style={{ fontSize: 25, fontWeight: "bold", color: "#fff" }}>
G
</Text>
</View>
<View
style={{
height: 50,
width: 50,
borderRadius: 50 / 2,
backgroundColor: "#1565c0",
alignItems: "center",
justifyContent: "center",
}}
>
<Text style={{ fontSize: 25, fontWeight: "bold", color: "#fff" }}>
in
</Text>
</View>
</View>
<StatusBar style="auto" />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
});
|
8104f98f043cc317a43a2713fe96d04556432d3b
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
MasabAli/Simple-ReactNative-UI
|
374d2bbea37ccf02825b8fc5431f3f16ccf32d8a
|
c555c38930cba36ad5758ec7186755901a2653df
|
refs/heads/master
|
<repo_name>franciswalsh/blackJackGame<file_sep>/blackjack/scripts/whoWon.js
function whoWon(yourHand){
let dealersHandValue = Math.ceil(Math.rand * 21);
let yourHandValue = handValue(yourHand);
if (yourHandValue === 21){
if (dealersHandValue === 21){
console.log("You tie");
} else {
console.log("You win!");
}
} else if (dealersHandValue === yourHandValue ){
console.log("You tie");
} else if (yourHandValue > dealersHandValue){
console.log("You win!");
} else {
console.log("You lose");
}
}
|
8f86722328af5e1742109303bf29589cd2339a90
|
[
"JavaScript"
] | 1 |
JavaScript
|
franciswalsh/blackJackGame
|
f04187cb9f6c575c56aa10c5231e2ff8402fb21a
|
b467c5ebca71af6546fcd9bb4698e7e2959872f6
|
refs/heads/master
|
<repo_name>luisamaoli/catalogo_bebidas<file_sep>/app/models/produto.rb
class Produto < ApplicationRecord
belongs_to :departamento, optional: true
validates :preco, presence: true
validates :rotulo, length: { minimum: 4}
end
|
c3aa433165b067b91bd49b3e40730d16b2d5f4f5
|
[
"Ruby"
] | 1 |
Ruby
|
luisamaoli/catalogo_bebidas
|
5a6877dccb1095a8da68de9b153495654f1ec6ab
|
eb97a31ec3ff0a1c1a164e7fcb95adef226650e9
|
refs/heads/master
|
<file_sep>require 'spec_helper'
describe "CacheKeys::Cache" do
before(:each) do
@post = Post.first
end
it "responds to cache_keys" do
@post.comments_cache_key.should eql("comments-#{@post.cache_key}")
@post.tweets_cache_key.should eql("tweets-#{@post.cache_key}")
end
end<file_sep>class Post < ActiveRecord::Base
cache_keys [:comments, :tweets]
end<file_sep>
require "cache_keys/version"
require 'active_record'
module CacheKeys
def cache_keys(keys)
if keys.empty?
raise ArgumentError, "you must provide an array of keys for cache keys"
end
keys.each do |key|
define_method "#{key}_cache_key" do
"#{key}-#{self.cache_key}"
end
end
end
end
ActiveRecord::Base.extend CacheKeys
<file_sep>source "http://rubygems.org"
# Specify your gem's dependencies in cache_keys.gemspec
gemspec
<file_sep># -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "cache_keys/version"
Gem::Specification.new do |s|
s.name = "cache_keys"
s.version = CacheKeys::VERSION
s.authors = ["<NAME>"]
s.email = ["<EMAIL>"]
s.homepage = ""
s.summary = %q{CACHE KEYS: key provider for active record cache}
s.description = %q{key provider for active record cache, by xarala}
s.rubyforge_project = "cache_keys"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
# Widows Dependencies
s.add_development_dependency "win32console"
s.add_development_dependency "rb-fchange"
s.add_development_dependency "rspec"
s.add_development_dependency "guard"
s.add_development_dependency "guard-rspec"
s.add_development_dependency "sqlite3-ruby"
s.add_dependency "activerecord", "~> 3.0"
end
|
bd290cb2989ee27d9663f2103da41146ea782245
|
[
"Ruby"
] | 5 |
Ruby
|
xarala/cache_keys
|
8501bab793b79392a9cc80e756d843c3015788fb
|
ecf11a18ca55959349fa8fd8defaf96487278e3f
|
refs/heads/master
|
<file_sep># 4.10. Exercises: Data & Variables
# Part A, #1 :
print('Part A, #1:')
print(6 * (1 - 2)) #Result should be -6
# Part A, #2 here:
print('\nPart A, #2:')
print((2 + 8 + 10) / 5) #Result should be 4.0
print(2 + (8 + 10) / 5) #Result should be 5.6
# Part A, #3 here:
word = '<PASSWORD>'
#3A
print('\nPart A, #3a:')
print((word + ' ') * 4)
#3B
print('\nPart A, #3b:')
print((word*2 + '\n')*3)
#3C
print('\nPart A, #3c:')
print((((word + '\t') * 3) + '\n') * 3)
print('<----------------------------------------->')
print('\nPart B:')
# 1. Declare and assign your first 4 variables here:
ship_name = 'Determination'
ship_speed_mph = 17500
km_to_mars = 225000000
miles_per_km = 0.621
print("\nName: " + ship_name +
", \nspeed(mph): " + str(ship_speed_mph) +
", \nkm to Mars: " + str(km_to_mars) +
", \nmiles per km: " + str(miles_per_km))
# 2. Create and assign a miles to Mars variable here:
miles_to_mars = km_to_mars * miles_per_km
print("\nMiles to Mars:", miles_to_mars)
# 3 & 4. Calculate and store the hours it takes to get to Mars
# and the days to Mars:
hours_to_mars = miles_to_mars / ship_speed_mph
print("\nHours to Mars:", hours_to_mars)
# 5. Print the sentence, "_____ will take ___ days to reach Mars."
#Fill in the blanks with the spaceship name and the calculated time.
print()
print(ship_name, "will take", miles_to_mars / 24, "days to reach Mars.")
# 6. Code the bonus mission here:
print('\nPart B, Bonus Mission:')
km_to_moon = 384400
miles_to_moon = km_to_moon * miles_per_km
hours_to_moon = miles_to_moon / ship_speed_mph
days_to_moon = hours_to_moon / 24
print()
print(ship_name, "will take", days_to_moon, "days to reach the Moon.")
print('<----------------------------------------->')
print('\nPart C, #1:')
word_input = input('Enter a word: ')
word_length = len(word_input)
print("The word '" + word_input + "' contains " + str(word_length) + " characters.")
print('\nPart C, #2:')
rectangle_length = float(input('Enter a length: '))
rectangle_width = float(input('Enter a width: '))
rectangle_area = rectangle_length * rectangle_width
print("The rectangle has an area of " + str(rectangle_area) + ".")
print('\nPart C, #3:')
miles_driven = float(input('Enter the number of miles driven: '))
gallons_used = float(input('Enter the number of gallons used: '))
miles_per_gal = miles_driven / gallons_used
print('Your car got', miles_per_gal, 'miles per gallon.')
|
e474b41a961006e64579263cc75bb80163d65b88
|
[
"Python"
] | 1 |
Python
|
KristineGray/U3Ch4Exercises
|
5eebdb8994df9711b77f7b448527a94c4235405d
|
0931009cc501df47e513c4114e5b9a75b4422d72
|
refs/heads/main
|
<file_sep>## See the project live!
- https://quorum-challenge.netlify.app/
## Run it locally:
1. `git clone https://github.com/JPGallegos1/quorumit-challenge.git`
2. `cd quorumit-challenge`
3. You will create a `.env` file in the **root of the project** with the variables I sent via e-mail
4. `npm i`
5. `npm run dev`
6. go to `http://localhost:3000`
## Features
- Requirements Implemented:
1. Data from Coingecko API (Coin, coin name, prices)
2. Graphics and tables of price-timestamp
3. Design from Figma
4. All data is saved into Local Storage
- In addition, I've implemented:
1. Server-side strategy for all `/detail/[page]`
2. Logic abstraction using Custom Hooks
3. Routing and custom navigation
4. Layout & media queries for all pages
5. A bunch of reusable components
6. Develop deploys were managed at: https://quorumit-challenge-develop.netlify.app/
And all under TypeScript control.

## Git strategy

<file_sep>/**
* @TYPES
*/
export type CoinName = "bitcoin" | "ethereum" | "dogecoin" | "cardano";
/**
* @INTERFACES
*/
export interface ICoin {
id: string;
name: string;
symbol: string;
image: string;
market_data: {
ath: {
btc: number;
ars: number;
usd: number;
};
current_price: {
btc: number;
ars: number;
usd: number;
};
high_24h: {
btc: number;
ars: number;
usd: number;
};
low_24h: {
btc: number;
ars: number;
usd: number;
};
};
}
export interface IContextValue {
coinName: string;
setCoinName: (coinName: string) => void;
priceInUsd: boolean;
setPriceInUsd: (priceInUsd: boolean) => void;
coin: ICoin;
setCoin: (coin: ICoin) => void;
isLoading: boolean;
setIsLoading: (isLoading: boolean) => void;
isGraphicTab: boolean;
setIsGraphicTab: (isGraphicTab: boolean) => void;
}
export interface ISwitchPrice {
priceInUsd: boolean;
setPriceInUsd: (priceInUsd: boolean) => void;
}
export interface IButton {
onClick: () => void;
condition?: boolean;
label: string;
disabled?: boolean;
}
export interface IDropdown {
coin: ICoin;
setCoinName: (coinName: string) => void;
isLoading: boolean;
}
export interface IDropdownMenu {
setCoinName: (coinName: string) => void;
}
export interface IDropdownCoinInfo {
coin: ICoin;
isLoading: boolean;
}
export interface IDetails {
data: {
prices: [];
};
}
<file_sep>import { extendTheme } from "@chakra-ui/react";
export const theme = extendTheme({
styles: {
global: (props) => ({
"html, body": {
background: "quorum.black.200",
},
a: {
textDecoration: "none",
},
}),
},
colors: {
quorum: {
white: {
100: "#EFEFF2",
},
black: {
100: "#23292F",
200: "#0D0E0E",
300: "#181B21",
},
gray: {
100: "#394251",
200: "#B9C1D9",
300: "#EFEFF2",
400: "#8B95B8",
500: "#E5E5E5",
},
red: {
100: "#EE6855",
},
},
},
textStyles: {
h1: {
fontSize: ["36px", "42px"],
fontFamily: "SF Pro Display",
fontWeight: "bold",
lineHeight: "50px",
letterSpacing: "0.41px",
},
},
});
<file_sep>export const COINS_URL: string = `${process.env.NEXT_PUBLIC_BASE_URL}/${process.env.NEXT_PUBLIC_COINS_ENDPOINT}`;
export const COIN_OPTIONS = [
{
name: "Bitcoin",
label: "BTC",
},
{
name: "Ethereum",
label: "ETH",
},
{
name: "Dogecoin",
label: "DOGE",
},
{
name: "Cardano",
label: "ADA",
},
];
|
6c0a3d25bd3256b714bb115a490b56559768a2e9
|
[
"Markdown",
"TypeScript",
"JavaScript"
] | 4 |
Markdown
|
JPGallegos1/quorumit-challenge
|
155ebcfcbfaab64101ca22ac801086b404485352
|
16f613c395e0c3c3ced9d6a3e99a4b05450c56a4
|
refs/heads/master
|
<file_sep>Copy-Shop
=========
`copy-shop` is a tool for the Sauce Labs support teams.
It simply takes a test report URL and outputs a Java test script with the same capabilities as the original test.
Usage
-----
```
$ pip install -r requirements.txt
...
$ SAUCE_USERNAME=<username> SAUCE_ACCESS_KEY=<access-key> python3 copy-shop.py <sauce-labs-test-report-url>
```
<file_sep>from string import Template
from requests.auth import HTTPBasicAuth
from urllib.parse import urlparse
import argparse
import os
import requests
USERNAME = os.environ["SAUCE_USERNAME"]
ACCESS_KEY = os.environ["SAUCE_ACCESS_KEY"]
def retrieve_job_info(domain, session_id):
url = 'https://{}/rest/v1.1/jobs/{}'.format(domain, session_id)
r = requests.get(url, auth=HTTPBasicAuth(USERNAME, ACCESS_KEY))
return r.json()["base_config"]
def job_info_to_java(info, domain, commands, template):
capabilities = ""
for key, value in info.items():
if value is None:
value = "null"
elif type(value) == bool:
value = str(value).lower()
elif type(value) == str:
value = '"' + escape(str(value)) + '"'
capabilities += "caps.setCapability(\"{}\", {});\n".format(key, value)
if domain == "app.saucelabs.com":
domain = "ondemand.saucelabs.com"
elif domain == "app.eu-central-1.saucelabs.com":
domain = "ondemand.eu-central-1.saucelabs.com"
commands = "\n".join(commands)
return template.substitute(username=USERNAME, access_key=ACCESS_KEY,
capabilities=capabilities,
commands=commands, domain=domain)
def extract_url_info(url):
parsed = urlparse(url)
assert parsed.path.startswith("/tests/")
return {
"domain": parsed.netloc,
"job_id": parsed.path[6:] # remove /tests/
}
def get_log_filename(domain, session_id):
url = 'https://{}/rest/v1/{}/jobs/{}/assets'.format(domain, USERNAME,
session_id)
r = requests.get(url, auth=HTTPBasicAuth(USERNAME, ACCESS_KEY))
return r.json()["sauce-log"]
# return r.json()["base_config"]
def extract_commands(domain, session_id, log_filename):
url = 'https://{}/rest/v1/{}/jobs/{}/assets/{}'.format(domain, USERNAME,
session_id,
log_filename)
r = requests.get(url, auth=HTTPBasicAuth(USERNAME, ACCESS_KEY))
return r.json()
def translate_commands(commands):
java_commands = []
for command in commands:
if "status" in command:
continue
if command["method"] == "GET":
continue
c = "// ignored command"
if command["path"] == "url" and command["method"] == "POST":
c = "driver.get(\"{}\");".format(command["request"]["url"])
elif command["path"] == "element" and command["method"] == "POST":
if command["request"]["using"] == "xpath":
c = "el = driver.findElement(By.xpath(\"{}\"));"\
.format(escape(command["request"]["value"]))
elif command["path"].startswith("element/") and \
command["path"].endswith("/click") and \
command["method"] == "POST":
c = "el.click();"
elif command["path"].startswith("element/") \
and command["path"].endswith("/clear") \
and command["method"] == "POST":
c = "el.clear();"
elif command["path"].startswith("element/") and command["path"] \
.endswith("/value") and command["method"] == "POST":
c = "el.sendKeys(\"{}\");" \
.format(escape(command["request"]["value"][0]))
elif command["path"] == "timeouts" and command["method"] == "POST" \
and command["request"]["type"] == "implicit":
c = "driver.manage().timeouts().implicitlyWait({}," \
"TimeUnit.MILLISECONDS);".format(command["request"]["ms"])
else:
c += ": {} {}".format(command["method"], command["path"])
java_commands.append(c)
return java_commands
def escape(s):
s = s.replace("\"", "\\\"")
# s = s.replace("'", "\'")
return s
def main(arguments=None):
parser = argparse.ArgumentParser()
parser.add_argument("job_urls", nargs="+", help="URL of test to copy.")
args = parser.parse_args(arguments)
for job_url in args.job_urls:
url_info = extract_url_info(job_url)
info = retrieve_job_info(url_info["domain"], url_info["job_id"])
log_filename = get_log_filename(url_info["domain"], url_info["job_id"])
commands = extract_commands(url_info["domain"], url_info["job_id"],
log_filename)
java_commands = translate_commands(commands)
template = Template(open("./template.java").read())
print(job_info_to_java(info, url_info["domain"], java_commands,
template))
if __name__ == "__main__":
main()
|
de32385be04525ae962c9397aa1a28060d8fa02e
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
enriquegh/copy-shop
|
08929f3e2daa0317593798773e9adb7a8fe89776
|
a6d6623ad78b92c608f26cac210dfd992479b6bc
|
refs/heads/master
|
<file_sep>import peakutils
def get_peaks(column):
peaks_array = peakutils.indexes(column, thres=0.55, min_dist=3)
peaks = {
"times": peaks_array,
"number" : len(peaks_array)
}
return peaks<file_sep>import pandas as pd
from explorer import get_files, get_folders, get_subroots, count_files
from building_func import get_building_kind, get_building_state, get_building_city
from make_building_model import make_building_model
from get_peaks import get_peaks
import progressbar
def make_buildings_feats(root, season = "", days = "all"):
buildings_feats = pd.DataFrame()
subroots = get_subroots(root)
bar = progressbar.ProgressBar(maxval=count_files(root), widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()])
i=0
for subroot in subroots:
print(subroot)
for folder in get_folders(root + subroot):
print(folder)
for file in get_files(root + subroot + folder):
bar.update(i)
i+=1
building_model = make_building_model(root + subroot + folder, file, season = season, days = days)
electricity_cons = building_model["Electricity:Facility [kW](Hourly)"]
#electricity_cons_scaled = minmax_scale(np.float64(electricity_cons.values))
electricity_cons_scaled = electricity_cons / electricity_cons.max()
peaks = get_peaks(electricity_cons)
building_features_dict = {"building_kind" : get_building_kind(file),
"building_state" : get_building_state(file),
"building_city" : get_building_city(file),
"n_peaks" : peaks["number"],
"time_peaks" : peaks["times"],
"std_dev" : electricity_cons.std(),
"consumption_max" : electricity_cons.max(),
"consumption_avg" : electricity_cons.mean(),
"highest_peak_time" : electricity_cons.idxmax(),
"file_path" : file,
}
electricity_cons_dict = dict(zip(
(str(i) for i in range(0, 24)),
electricity_cons_scaled
))
row = dict(electricity_cons_dict, **building_features_dict)
buildings_feats = buildings_feats.append(row, ignore_index = True)
print("DONE")
return buildings_feats<file_sep>import pandas as pd
from explorer import get_files, get_folders, get_subroots, count_files
from make_building_feats import make_building_feats
import progressbar
def make_buildings_dataset(root, season = "", days = "all"):
buildings_feats = pd.DataFrame()
subroots = get_subroots(root)
bar = progressbar.ProgressBar(maxval=count_files(root), widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()])
i=0
for subroot in subroots:
# print(subroot)
for folder in get_folders(root + subroot):
# print(folder)
for file in get_files(root + subroot + folder):
bar.update(i)
i+=1
row = make_building_feats(root + subroot + folder + file)
buildings_feats = buildings_feats.append(row, ignore_index = True)
print("DONE")
return buildings_feats<file_sep>spring_start = "2004-03-01"
spring_end = "2004-05-31"
summer_start = "2004-06-01"
summer_end = "2004-08-31"
autumn_start = "2004-09-01"
autumn_end = "2004-11-30"
winter_start = "2004-12-01"
winter_end = "2004-02-28"
<file_sep>import matplotlib
import matplotlib.pyplot as plt
from make_df import make_df
from calendar_funcs import get_workdays, get_all_days, get_not_workdays
def plot_range(path, start_date, end_date, **kwargs):
df = make_df(path)
workdays = get_workdays(start_date, end_date)
all_days = get_all_days(start_date, end_date)
not_workdays = get_not_workdays(start_date, end_date)
for day in all_days:
plt.subplot(131)
plt.plot(df[day].index.hour,
df[day]['Electricity:Facility [kW](Hourly)'], color=(0,0,0,0.1))
plt.xlim([0, 23])
plt.xlabel("Hour of the day")
plt.ylabel("Load profile")
for day in workdays:
plt.subplot(132)
plt.plot(df[day].index.hour,
df[day]['Electricity:Facility [kW](Hourly)'], color=(0,0,0,0.1))
plt.xlim([0, 23])
plt.xlabel("Hour of the day")
plt.ylabel("Load profile")
plt.title(path.split("/")[-1] + " (all, working, weekends)", fontsize = 20)
for day in not_workdays:
plt.subplot(133)
plt.plot(df[day].index.hour,
df[day]['Electricity:Facility [kW](Hourly)'], color=(0,0,0,0.1))
plt.xlim([0, 23])
plt.xlabel("Hour of the day")
plt.ylabel("Load profile")
if "output_folder" in kwargs:
save_path = folder + kwargs["output_folder"]
if not os.path.exists(save_path):
os.makedirs(save_path)
plt.savefig(save_path + "/" + file_input.split(".")[0] + "_loads.png")
plt.rcParams["figure.figsize"] = (50,8)
return plt.show()
def plot_day(df, days, line_color="blue"):
for day in days:
plt.plot(df[day].index.hour,
df[day]['Electricity:Facility [kW](Hourly)'], color = line_color)
plt.xlim([0, 23])
plt.xlabel("Hour of the day")
plt.ylabel("Load profile")
plt.show()<file_sep># Loads Clustering
Data science project using this open dataset: http://en.openei.org/datasets/files/961/pub/
The `all_commercial.csv` file already contains a dataset made of the models of every building in the original dataset.
Other csv files have been used for tests.
The clustering and plotting part is done in the iPython Notebook. Pardon me if you'll find it messy, i use it for prototyping and quick tests :)
If you want to make your own dataset, download the dataset from the link above, and unzip them. Then use the function `make_buildings_dataset(root, season = "", days = "all")` contained in `tools/make_buildings_dataset.py`.<file_sep>import pandas as pd
import numpy as np
from sklearn.preprocessing import minmax_scale
import seasons
from make_df import make_df
from make_calendar_df import get_business_df, get_not_working_df
def make_building_model(file, days = "all", season = ""):
df = make_df(file)
if days == "business":
df = get_business_df(df)
elif days == "not_working":
df = get_not_working_df(df)
if season == "summer":
df = df[seasons.summer_start : seasons.summer_end]
elif season == "spring":
df = df[seasons.spring_start : seasons.spring_end]
elif season == "autumn":
df = df[seasons.autumn_start : seasons.autumn_end]
elif season == "winter":
df = pd.concat([df[:seasons.winter_end], df[seasons.winter_start:]])
building_model= pd.DataFrame(columns = df.columns.tolist(),
index = range(0,24))
for column in df.columns.tolist():
for hour in range(0,24):
building_model.loc[hour, column] = df.loc[df.index.hour == hour,column].mean()
#building_model[column] = minmax_scale(np.float64(building_model[column].values))
return building_model<file_sep>import pandas as pd
def describe_clusters(df, cluster):
for cluster_number in range(0, len(cluster.cluster_centers_)):
print("================================")
print("CLUSTER", str(cluster_number))
print("total elements:", str((cluster.labels_ == cluster_number).sum()))
for unique in df.ix[cluster.labels_ == cluster_number, "building_kind"].unique():
print("n ", unique, "=", str(len(df.ix[cluster.labels_ == cluster_number].loc[df["building_kind"] == unique])),
"out of", len(df.loc[df["building_kind"] == unique]))<file_sep>import pandas as pd
import datetime
from pandas.tseries.offsets import CDay
from pandas.tseries.holiday import Holiday, USFederalHolidayCalendar, USColumbusDay, USMemorialDay, AbstractHolidayCalendar
class WorkCalendar(AbstractHolidayCalendar):
rules = [
USMemorialDay,
USColumbusDay
] + USFederalHolidayCalendar.rules
WorkCalendar.start_date = datetime.date(2004,1,1)
WorkCalendar.start_date = datetime.date(2004,12, 31)
cal = WorkCalendar()
def get_workdays(start_date, end_date):
days = pd.DatetimeIndex(start = start_date, end = end_date, freq = CDay(calendar = cal))
return list(days.strftime('%Y-%m-%d'))
def get_all_days(start_date, end_date):
days = pd.date_range(start_date,end_date)
return list(days.strftime('%Y-%m-%d'))
def get_not_workdays(start_date, end_date):
workdays = pd.DatetimeIndex(start = start_date, end = end_date, freq = CDay(calendar = cal))
all_days = pd.date_range(start_date,end_date)
days = all_days - workdays
return list(days.strftime('%Y-%m-%d'))
<file_sep>from explorer import get_folders, get_files, get_subroots
files = []
root = "RESIDENTIAL/"
for subroot in get_subroots(root):
for folder in get_folders(root + subroot):
for file in get_files(root + subroot + folder):
files.append(file)<file_sep>#from scipy.interpolate import interp1d
#from sklearn.linear_model import Ridge
#from sklearn.preprocessing import PolynomialFeatures
#from sklearn.pipeline import make_pipeline
#from statsmodels.nonparametric.kernel_regression import KernelReg
#clf = Ridge()
import peakutils
def get_peaks(column):
#interpol = interp1d(column.index.values[1::2], column.values[1::2], kind = "cubic")
#n_datapoints = 24
#x = column.index.values[1:]
#y = interpol(x)
#y = signal.savgol_filter(column.values, 5,2)
#clf.fit(column.index.values.reshape(24,1), column.values)
#y = clf.predict(column.index.values.reshape(24,1))
#x = column.index.values
#y, y_std = kr.fit(x)
# model = make_pipeline(PolynomialFeatures(5), Ridge())
# model.fit(column.index.values.reshape(24,1), column.values)
#
# y = model.predict(column.index.values.reshape(24,1))
#plt.subplot(121)
plt.plot(column)
#plt.subplot(122)
#plt.plot(x, y)
plt.show()
#peakutils.indexes(column, thres=0.6, min_dist=3)
#signal.argrelmax(y, order = 2)
peaks = peakutils.indexes(column, thres=0.35, min_dist=3)
return peaks
for file in files:
column = make_building_model(folder, file)["Electricity:Facility [kW](Hourly)"]
peaks = get_peaks(column)
print(peaks)
#print("n peaks = ", len(maxs[0]))
print("n peaks = ", len(peaks))
threshold = 0.3
print("--------------------------------------------------------------")<file_sep>def get_building_kind(filename):
if "RefBldg" in filename:
return filename.split(str(2004))[0].split("RefBldg")[1]
else:
return "residential"
def get_building_state(filename):
return filename.split("USA_")[1].split("_")[0]
def get_building_city(filename):
if "RefBldg" in filename:
return filename.split(get_building_state(filename))[1][1:-4]
else:
return ", ".join(filename.split("_")[2].split(".")[0:-2])<file_sep>import pandas as pd
import datetime
def make_df(path):
df = pd.read_csv(path)
#add year and change midnight from 24 to 00 as pandas wants
df["Date/Time"] = "2004/" + df["Date/Time"].str.replace("24:","00:").str.replace(" ","")
df["Date/Time"] = pd.to_datetime(df["Date/Time"], format ="%Y/%m/%d%H:%M:%S")
#remove only datapoint of 2005 and use it to fill missing datapoint of 2004-1-1 at midnight
df.set_index("Date/Time", inplace=True)
#set time = 0 as first hour of next day
df.index += pd.to_timedelta((df.index.hour == 0) * datetime.timedelta(days=1))
#fix problem with 29 of February
df.index += pd.to_timedelta(((df.index.day == 29) & (df.index.month == 2)) * datetime.timedelta(days=1))
#make last row the first
first_row = df.ix[[-1]]
first_row.index -= pd.to_timedelta(datetime.timedelta(days=366))
df = pd.concat([first_row, df.ix[0:-1]])
#fix daylight time shifts and make dataset consistent
# Daylight Saving Time starts the 12 of March and ends the 5 of november
df = pd.concat([df[:"2004-03-11"],
df["2004-03-12":"2004-11-5"].shift(1),
df["2004-11-6":]])
df.fillna(method="bfill",inplace=True)
# ATTENTION! the dataset is all shifted by 4 days, in fact by doing that you
# can see that on weekends energy demand is lower, as well as on public holidays
# (check Martin Luther king day on January 19)
df = df.shift(3 * 24)
return df.dropna(axis = 1, how = "all").dropna(how = "all") <file_sep>import os
def get_folders(root):
return [folder + "/" for folder in os.listdir(root) if folder.startswith(".") == False]
def get_files(folder):
return [file for file in os.listdir(folder) if file.endswith(".csv")]
def get_subroots(root):
return [folder + "/" for folder in os.listdir(root) if
(folder.startswith(".") == False and folder.endswith(".tar.gz") == False)]
def count_files(root):
i = 0
for subroot in get_subroots(root):
for folder in get_folders(root + subroot):
for file in get_files(root + subroot + folder):
i += 1
return i<file_sep>import pandas as pd
from calendar_funcs import get_workdays, get_not_workdays
def get_business_df(df):
business_df = pd.DataFrame()
workdays = get_workdays(str(df.ix[[1]].index.strftime('%Y-%m-%d')[0]),
str(df.ix[[-1]].index.strftime('%Y-%m-%d')[0]))
for day in workdays:
business_df = business_df.append(df[day])
return business_df
def get_not_working_df(df):
not_working_df = pd.DataFrame()
workdays = get_not_workdays(str(df.ix[[1]].index.strftime('%Y-%m-%d')[0]),
str(df.ix[[-1]].index.strftime('%Y-%m-%d')[0]))
for day in workdays:
not_working_df = not_working_df.append(df[day])
return not_working_df<file_sep>import pandas as pd
from building_func import get_building_kind, get_building_state, get_building_city
from make_building_model import make_building_model
from get_peaks import get_peaks
def make_building_feats(file, season = "", days = "all"):
building_model = make_building_model(file, season = season, days = days)
if "Electricity:Facility [kW](Hourly)" in building_model.columns:
electricity_cons = building_model["Electricity:Facility [kW](Hourly)"]
measure = "kW"
elif "Electricity:Facility [J](Hourly)" in building_model.columns:
electricity_cons = building_model["Electricity:Facility [J](Hourly)"]
measure = "J"
elif "Electricity:Facility [kWh](Hourly)" in building_model.columns:
electricity_cons = building_model["Electricity:Facility [kWh](Hourly)"]
measure = "kWh"
#electricity_cons_scaled = minmax_scale(np.float64(electricity_cons.values))
electricity_cons_scaled = electricity_cons / electricity_cons.max()
peaks = get_peaks(electricity_cons)
building_features_dict = {"building_kind" : get_building_kind(file),
"building_state" : get_building_state(file),
"building_city" : get_building_city(file),
"n_peaks" : peaks["number"],
"time_peaks" : peaks["times"],
"std_dev" : electricity_cons.std(),
"consumption_max" : electricity_cons.max(),
"consumption_avg" : electricity_cons.mean(),
"highest_peak_time" : electricity_cons.idxmax(),
"measure" : measure,
"file_path" : file,
}
electricity_cons_dict = dict(zip(
(str(i) for i in range(0, 24)),
electricity_cons_scaled
))
return dict(electricity_cons_dict, **building_features_dict)
|
632f2cb63f8d26e4e9ec9b9c38605656bfe358b3
|
[
"Markdown",
"Python"
] | 16 |
Python
|
geoffyang/loads_clustering
|
5e4535068f6cbbf70df59977beff244b3105929a
|
bb79712d85b4134f4aab74b0c0a7d05df781deae
|
refs/heads/master
|
<repo_name>allanwk/LogisimComputer<file_sep>/compiler.py
import pandas as pd
import numpy as np
import sys
#Get instruction codes from spreadsheet
df = pd.read_excel('16bit_set.xlsx', dtype=str)
df = df.set_index(df['Instruction'])
instructions = pd.unique(df['Instruction'])
codes = {}
for instruction in instructions[1:]:
codes[instruction] = df.loc[instruction, ['Code']].iloc[0]['Code']
def compile(filename):
"""
Compiles a simple language containing labels, jumps (gotos) and constants,
generating a text file with hex values for the computer RAM.
"""
with open(filename, 'r') as file:
lines = file.read().splitlines()
var_address = 192
constants = {}
memory = {}
labels = {}
instruction_address_counter = 0
#Extract constants and commands
const = [line.split('//')[0].strip() for line in lines if line != '' and '=' in line]
commands = [line.split('//')[0].strip() for line in lines if line != '' and '=' not in line]
#Map constants to memory
for c in const:
name, value = c.replace(" ", "").split("=")
constants[name] = var_address
memory[var_address] = hex(int(value))[2:].zfill(4)
var_address += 1
#Map labels to memory
for index, line in enumerate(commands):
if ':' in line:
label = line[:line.index(':')]
labels[label] = var_address
memory[var_address] = hex(int(index))[2:].zfill(4)
var_address += 1
commands[index] = commands[index].split(':')[1].strip()
"""For each line, create a binary string containing 8 instruction bits
and 8 address bits. Convert this string to hex and save to memory dict.
The mrmory dict is used to generate a numpy array, which is saved as
the RAM.txt file.
"""
for line in commands:
l = line.split(" ")
hex_str = ""
if len(l) == 2:
instruction, operand = l
binary_str = codes[instruction]
if operand in labels:
binary_str += bin(int(labels[operand]))[2:].zfill(8)
elif operand in constants:
binary_str += bin(int(constants[operand]))[2:].zfill(8)
else:
memory[var_address] = hex(int(operand))[2:].zfill(4)
constants[operand] = var_address
var_address += 1
binary_str += bin(int(constants[operand]))[2:].zfill(8)
hex_str = hex(int(binary_str, 2))[2:].zfill(4)
else:
instruction = l[0]
binary_str = codes[instruction] + "0"*8
hex_str = hex(int(binary_str, 2))[2:].zfill(4)
memory[instruction_address_counter] = hex_str
instruction_address_counter += 1
arr = np.full((1,256), '0', dtype=np.dtype('U100'))
for key, value in memory.items():
arr[0,key] = value
arr = arr.reshape(16,16)
np.savetxt('RAM.txt', arr, delimiter=' ', fmt='%s')
with open('RAM.txt', 'r+') as f:
line = 'v2.0 raw'
content = f.read()
f.seek(0, 0)
f.write(line.rstrip('\r\n') + '\n' + content)
print("Compiled to RAM.txt")
if __name__ == '__main__':
compile(sys.argv[1])<file_sep>/README.md
LogisimComputer
==================
16-bit fully programmable computer built in Logisim.

Software
------------
- `compiler.py` for expandable instruction set
- Grammar supporting labels, conditional jumps, constants and comments
- Script `create_rom_file.py` for converting the instruction set spreadsheet
into hex ROM values
Hardware
------------
- Control Unit: Instruction register and decoder, program and step counter, clock
- ALU: Adder, subtractor, bit-shifter, comparator and flags register
- I/O: 7-segment displays controlled by output register; simple TTY and keyboard
- 2 General Purpose Registers
- RAM, 512 bytes adress space
Sample Programs
------------
- Turing Machine: simulate a TM that adds 1 to a binary number input via keyboard
- Fibonacci: Generates the Fibonacci sequence, printing each number on the 7-segment displays
References
------------
- Based on <NAME>'s [breadboard computer guide](https://eater.net/8bit)<file_sep>/create_rom_file.py
import pandas as pd
import numpy as np
from tqdm import tqdm
#Opening spreadsheet containing instruction codes and control words
df = pd.read_excel('16bit_set.xlsx', dtype=str)
n_instructions = len(df)
#Creating multiples for handling flag signals
df = pd.concat([df]*32, ignore_index=True)
#List of all possibilities for the 5 flag bits
flags_list = [bin(i)[2:].zfill(5) for i in range(pow(2, 5))]
flags_df = pd.DataFrame(np.repeat(flags_list, n_instructions, axis=0), columns=['Flags'])
#Check if flag at given position is set
def check_flag(string, index):
return string[-(index + 1)] == '1'
#Combining instruction dataframe with flags and organizing columns
df = pd.concat([df, flags_df], axis=1)
cols = df.columns.tolist()
cols = cols[:3] + cols[-1:] + cols[3:-1]
df = df[cols]
#Getting ROM addresses in decimal to create Logisim memory file
data = {}
converted_addr = []
for index, row in df[['Code', 'Step', 'Flags']].iterrows():
dec_addr = int(str(row['Code']) + str(row['Step']) + str(row['Flags']), base=2)
data[dec_addr] = 0
converted_addr.append(dec_addr)
df['Code'] = converted_addr
#Setting microcode for conditional jumps
for i in tqdm(range(len(df))):
if df.loc[i, ['Instruction']]['Instruction'] == 'JEQ' and check_flag(df.loc[i, ['Flags']]['Flags'], 2) and df.loc[i, ['Step']]['Step'] == '011':
df.loc[i, ['RO']] = 1
df.loc[i, ['J']] = 1
elif df.loc[i, ['Instruction']]['Instruction'] == 'JG' and check_flag(df.loc[i, ['Flags']]['Flags'], 3) and df.loc[i, ['Step']]['Step'] == '011':
df.loc[i, ['RO']] = 1
df.loc[i, ['J']] = 1
elif df.loc[i, ['Instruction']]['Instruction'] == 'JL' and check_flag(df.loc[i, ['Flags']]['Flags'], 4) and df.loc[i, ['Step']]['Step'] == '011':
df.loc[i, ['RO']] = 1
df.loc[i, ['J']] = 1
elif df.loc[i, ['Instruction']]['Instruction'] == 'JC' and check_flag(df.loc[i, ['Flags']]['Flags'], 0) and df.loc[i, ['Step']]['Step'] == '011':
df.loc[i, ['RO']] = 1
df.loc[i, ['J']] = 1
#Generating microcode from columns and saving to data dict
for index, row in df.iterrows():
binary_str = ""
for col in df.columns[4:]:
binary_str += str(row[col])
data[row['Code']] = hex(int(binary_str, base=2))
#Converting data to array and save to text file
arr = np.full((1,pow(2, 16)), '0', dtype=np.dtype('U100'))
for key, value in data.items():
arr[0,key] = value.split('x')[1]
arr = arr.reshape(4096,16)
np.savetxt('instructions_rom16.txt', arr, delimiter=' ', fmt='%s')
#Adding Logisim memory header
with open('instructions_rom16.txt', 'r+') as f:
line = 'v2.0 raw'
content = f.read()
f.seek(0, 0)
f.write(line.rstrip('\r\n') + '\n' + content)
|
e1c41aac9b922ad7398a0408f845dca8e04397fc
|
[
"Markdown",
"Python"
] | 3 |
Python
|
allanwk/LogisimComputer
|
cd647bf504248c6efa5cd215fdcb4e1b924e15ad
|
df3e383261a4d7ca60d1adf618cbd350e84ba72e
|
refs/heads/master
|
<repo_name>stuarthannig/poke_calculator<file_sep>/README.md
# PokéCalculator
`npm install & npm run dev`
<file_sep>/src/client/app/index.jsx
import React from 'react';
import {render} from 'react-dom';
import CalculatorWrapper from './containers/CalculatorWrapper.jsx';
class App extends React.Component {
render () {
return (
<div>
<p>Hello, World!</p>
<CalculatorWrapper url="http://pokeapi.co/api/v2/pokedex/2/" />
</div>
);
}
}
render(<App/>, document.getElementById('app'));
<file_sep>/src/client/app/components/CalculatorForm.jsx
import React from 'react';
class CalculatorForm extends React.Component {
constructor(props) {
super(props);
this.state = { pokemon: '', candy: '' };
}
handlePokemonChange(e) {
this.setState({ pokemon: e.target.value });
}
handleCandyChange(e) {
this.setState({ candy: e.target.value });
}
handleSubmit(e) {
e.preventDefault();
let pokemon = this.state.pokemon;
let candy = this.state.candy;
if (!candy || !pokemon) {
return;
}
this.props.onCalculatorSubmit({ pokemon: pokemon, candy: candy });
}
render() {
const pokemonNodes = this.props.data.map(function(pokemon) {
return (
<option key={ pokemon.entry_number } value={ pokemon.entry_number }>
{ pokemon.pokemon_species.name }</option>
);
});
return (
<form className="calculatorForm" onSubmit={ this.handleSubmit.bind(this) }>
<select
onChange={ this.handlePokemonChange.bind(this) }>
{ pokemonNodes }</select>
<input
type="number"
max="9999"
onChange={ this.handleCandyChange.bind(this) } />
<input
type="submit"
value="Calculate" />
</form>
);
}
}
export default CalculatorForm;
|
cef37aaffc087bde1b1da3dec6c071e91f022186
|
[
"Markdown",
"JavaScript"
] | 3 |
Markdown
|
stuarthannig/poke_calculator
|
7f417140a52bff0755f410fe543d70ff3be0ddce
|
393c58fa64bc35ba70db1b845c6d011a610bf3a5
|
refs/heads/master
|
<file_sep>import React, { Component } from 'react';
import 'tachyons';
import './style.css'
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
import './style.css';
import {Button, Container, Row, Col } from 'react-bootstrap/Button';
import 'bootstrap/dist/css/bootstrap.min.css';
import About from './about'
import Home from './home'
import Users from './userpage'
import AddUser from './adduser'
const Header = () => {
return (
<div class="flex flex-row bg-gold">
<div class="w-25 pa3 mr2 mt2 h2">
<img src="https://image.shutterstock.com/image-vector/shield-letter-s-logosafesecureprotection-logomodern-260nw-633031571.jpg" className='br-100 pa1 ba b--black-10 h3 w3' alt='avatar' />
</div>
<div class="w-75 pa3 mr2 mt2">
<ul class="list dib fl">
<li class="fl pa1">
<Link to="/home">Home</Link>
</li>
<li class="fl pa1">
<Link to="/about">About</Link>
</li>
<li class="fl pa1">
<Link to="/users">Users</Link>
</li>
<li class="fl pa1">
<Link to="/add">Add Post</Link>
</li>
</ul>
</div>
</div>
);
}
export default Header;
<file_sep>import {addPost, fetchProductsPending, fetchProductsSuccess, fetchProductsError} from './actions';
export function fetchProducts(name) {
console.log("my name is "+name)
return dispatch => {
fetch('https://jsonplaceholder.typicode.com/users',
{
method: 'get',
}).then(res => res.json())
.then(res => {
if(res.error) {
throw(res.error);
}
dispatch(fetchProductsSuccess(res));
return res;
})
.catch(error => {
dispatch(fetchProductsError(error));
})
}
}
export function addUser(title,body) {
return dispatch => {
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title: title,
body: body,
userId: 1
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(res => {
if(res.error) {
throw(res.error);
}
dispatch(addPost("Record has been added successfully"));
console.log(res)
setTimeout(() => {
// Yay! Can invoke sync or async actions with `dispatch`
dispatch(addPost("Record has been added successfully"));
}, 1000);
return res;
})
}
}
<file_sep>import React from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
import './style.css';
import asyncComponent from './AsyncComponent'
import 'tachyons'
const Home = asyncComponent(() =>
import('./home').then(module => module.default)
)
const AddUser = asyncComponent(() =>
import('./adduser').then(module => module.default)
)
const About = asyncComponent(() =>
import('./about').then(module => module.default)
)
const Users = asyncComponent(() =>
import('./userpage').then(module => module.default)
)
export default function Routes() {
return (
<div class="h-auto pa2 ma2">
<Switch>
<Route path="/about" component={About} />
<Route path="/users" component={Users} />
<Route path="/home" component={Home} />
<Route path="/add" component={AddUser} />
<Route path="/" component={Home} />
</Switch>
</div>
);
}
<file_sep>import * as actionTypes from './ActionTypes';
export function fetchProductsPending() {
return {
type: actionTypes.FETCH_PRODUCTS_PENDING
}
}
export function fetchProductsSuccess(products) {
return {
type: actionTypes.FETCH_PRODUCTS_SUCCESS,
payload: products
}
}
export function fetchProductsError(error) {
return {
type: actionTypes.FETCH_PRODUCTS_ERROR,
error: error
}
}
export function addPost(payload) {
console.log(payload)
console.log(payload);
return {
type: actionTypes.ADD_POST,
payload: payload
}
}
<file_sep># react-zbqwdn
[Edit on StackBlitz ⚡️](https://stackblitz.com/edit/react-zbqwdn)<file_sep>export const MY_LOGIN = 'MY_LOGIN';
export const FETCH_PRODUCTS_PENDING = 'FETCH_PRODUCTS_PENDING';
export const FETCH_PRODUCTS_SUCCESS = 'FETCH_PRODUCTS_SUCCESS';
export const FETCH_PRODUCTS_ERROR = 'FETCH_PRODUCTS_ERROR';
export const ADD_POST = 'ADD_POST';
<file_sep>import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import Header from './header';
import Router from './Router'
import Footer from './footer';
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
class Home extends Component {
constructor() {
super();
this.state = {
name: 'React'
};
}
myclick = () => {
alert("hello");
}
render() {
return (
<div class="wrapper">
welcome to home
</div>
);
}
}
export default Home;
|
1cfd6363b97f593e27568ae8ede01fd39ed5b52f
|
[
"JavaScript",
"Markdown"
] | 7 |
JavaScript
|
himmat1981/react-zbqwdn
|
382d7fda84f843861028420bd7f07a8edc01f89d
|
69e6d27807e29761c74ddcc8437c1019235ffdaa
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.